-
Notifications
You must be signed in to change notification settings - Fork 1
/
randomNDE.py
238 lines (216 loc) · 8.31 KB
/
randomNDE.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import classes
import aiNDE
import sys, os
import random
def choosePiece(pieceList):
"""
Rolls die and returns the piece to be moved. Randomly choses higher
or lower
"""
dice = [1, 2, 3, 4, 5, 6]
if len(pieceList) > 1:
diceRoll = random.choice(dice)
print("Dice Roll:", diceRoll)
if not any(piece for piece in pieceList if piece.value == diceRoll):
# Piece is dead, finds next highest/lowest
nextUp = -1
nextDown = -1
for i in range(diceRoll + 1,6):
if any(piece for piece in pieceList if piece.value == i):
nextUp = i
break
for i in range(diceRoll - 1, -1, -1):
if any(piece for piece in pieceList if piece.value == i):
nextDown = i
break
if nextUp == -1:
print("Piece", diceRoll, "is dead.")
diceRoll = nextDown
elif nextDown == -1:
print("Piece", diceRoll, "is dead.")
diceRoll = nextUp
else:
print("Piece ", diceRoll, " is dead. ", end = '')
diceRoll = random.choice([nextUp,nextDown])
print("Randome Pick:", diceRoll)
else:
diceRoll = pieceList[0].value
print("Only 1 piece left.")
return [piece for piece in pieceList if piece.value == diceRoll][0]
# choosing move (random)
def chooseMove(piece, board, currentPlayer):
while True:
# moves: "U", "D", "L", "R", "X"
if currentPlayer == "red":
move = random.choice(["D","R","X"])
else:
move = random.choice(["U","L","X"])
if isMoveValid(piece, move):
# return new position
if move == "U": # blue
print("Random Pick: Up")
return [piece.row-1, piece.col]
elif move == "D": # red
print("Random Pick: Down")
return [piece.row+1, piece.col]
elif move == "L": # blue
print("Random Pick: Left")
return [piece.row, piece.col-1]
elif move == "R": # red
print("Random Pick: Right")
return [piece.row, piece.col+1]
elif move == "X":
print("Random Pick: Diagonal")
if piece.color == "blue":
return [piece.row-1, piece.col-1]
elif piece.color == "red":
return [piece.row+1, piece.col+1]
# check if move is valid
def isMoveValid(piece, move):
if piece.color == "blue":
if move != "U" and move != "L" and move != "X":
print("Invalid move. Blue player can only go up['U'], left['L'], or diagonal-up['X'].")
return False
elif move == "U":
if piece.row > 0: return True
elif move == "L":
if piece.col > 0: return True
elif move == "X":
if piece.col > 0 and piece.row > 0: return True
else:
return False
if piece.color == "red":
if move != "D" and move != "R" and move != "X":
print("Invalid move. Red player can only go down['D'], right['R'], or diagonal-down['X'].")
return False
elif move == "D":
if piece.row < 4: return True
elif move == "R":
if piece.col < 4: return True
elif move == "X":
if piece.col < 4 and piece.row < 4: return True
else:
return False
return False
# check winning conditions
def check_winner(board, redPieces, bluePieces):
redCorner = board.board[0][0]
blueCorner = board.board[4][4]
if redCorner and redCorner.color == "blue":
return "blue"
elif blueCorner and blueCorner.color == "red":
return "red"
elif len(redPieces) == 0:
return "blue"
elif len(bluePieces) == 0:
return "red"
else:
# no winner yet
return False
def get_next_player(currentPlayer):
return "red" if currentPlayer == "blue" else "blue"
# plays the game
def play():
print("Test the AI against a random player.")
print("AI is red; random player is blue.\n")
# Choose how many times to run the program
while True:
numberRuns = input("Play how many games?\n> ")
try:
numberRuns = int(numberRuns)
break
except:
print('Invalid input. Please try again.\n> ')
randomWins = 0
AIWins = 0
if input("Turn off printing? (Type x for yes)\n> ") == "x":
sys.stdout = open(os.devnull, 'w')
for i in range(numberRuns):
# initialize board
board = classes.Board(5, 5)
red1 = classes.Piece(0, 0, "red", 1)
red2 = classes.Piece(0, 1, "red", 2)
red3 = classes.Piece(0, 2, "red", 3)
red4 = classes.Piece(1, 0, "red", 4)
red5 = classes.Piece(1, 1, "red", 5)
red6 = classes.Piece(2, 0, "red", 6)
blue1 = classes.Piece(4, 4, "blue", 1)
blue2 = classes.Piece(4, 3, "blue", 2)
blue3 = classes.Piece(4, 2, "blue", 3)
blue4 = classes.Piece(3, 3, "blue", 4)
blue5 = classes.Piece(3, 4, "blue", 5)
blue6 = classes.Piece(2, 4, "blue", 6)
pieces = [red1, red2, red3, red4, red5, red6, blue1, blue2, blue3, blue4, blue5, blue6]
redPieces = [red1, red2, red3, red4, red5, red6]
bluePieces = [blue1, blue2, blue3, blue4, blue5, blue6]
for piece in redPieces:
board.addPiece(piece)
for piece in bluePieces:
board.addPiece(piece)
# randomly choose a player to start
currentPlayer = random.choice(["blue","red"])
print(currentPlayer, "goes first.")
while True:
print("-"*30)
print("{}'s turn:\n".format(currentPlayer))
if currentPlayer == "blue":
pieceToMove = choosePiece(bluePieces)
elif currentPlayer == "red":
aiMoveAndPiece = aiNDE.evaluateMoves(board, redPieces)
pieceToMove = aiMoveAndPiece[0]
print(pieceToMove, "is chosen.\n")
print(board)
if pieceToMove.color == "blue":
newPos = chooseMove(pieceToMove, board, currentPlayer)
else:
updatedRow = pieceToMove.row
updatedCol = pieceToMove.col
if aiMoveAndPiece[1] == "D":
updatedRow = pieceToMove.row + 1
elif aiMoveAndPiece[1] == "R":
updatedCol = pieceToMove.col + 1
elif aiMoveAndPiece[1] == "X":
updatedRow = pieceToMove.row + 1
updatedCol = pieceToMove.col + 1
newPos = [updatedRow, updatedCol]
# get previously occupied piece at new position if any
prevPiece = board.get_piece(newPos[0], newPos[1])
if prevPiece: # remove previously occupied piece from board
if prevPiece.color == "blue":
board.removePiece(prevPiece)
bluePieces.remove(prevPiece)
print(prevPiece,"is removed...")
elif prevPiece.color == "red":
board.removePiece(prevPiece)
redPieces.remove(prevPiece)
print(prevPiece,"is removed...")
board.movePiece(pieceToMove, newPos[0], newPos[1])
# Check if game is over
winner = check_winner(board, redPieces, bluePieces)
if winner:
print(board)
if winner == "red":
print("AI player won!")
AIWins += 1
break
if winner == "blue":
print("Random player won!")
randomWins += 1
break
print(board)
# next player's turn
currentPlayer = get_next_player(currentPlayer)
sys.stdout = sys.__stdout__
print("\n========================================\n")
print("RESULTS:")
print("Number of Games:", numberRuns)
print("Random Wins:", randomWins)
print("AI Wins:", AIWins)
print("AI Win Rate: ", (AIWins / numberRuns)*100 ,"%", sep ="")
print("\nConclusion:")
if randomWins >= AIWins:
print("AI Sucks :(")
else:
print("AI is better :)")
if __name__ == "__main__":
play()