-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
76 lines (57 loc) · 2.1 KB
/
main.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
# main program for creating the game board
from solution_search import decide
# main game board class
class Board(object):
def __init__(self, board):
self.board = board
def update(self, piles, num):
self.board[piles] -= num
def computerUpdate(self):
self.board = decide(self.board, -float('inf'), float('inf'), True)[1][1]
# check whether user input is valid
def isValid(remove, board):
if not remove or len(remove) != 2: return False
if remove[0] > 0 and remove[1] >= 0 and remove[1] < len(board) and remove[0] <= board[remove[1]]:
return True
return False
if __name__ == "__main__":
print("Starting Nim!")
# initializing size of the game board
ele = int(input("Input the number of piles "))
lis = []
print("Input the number of sticks in each pile (separate with ENTER)")
for _ in range(ele):
lis.append(int(input()))
game = Board(lis)
print("Enter the number of sticks to remove, then space followed by the pile to remove them from (starting from 0)")
print("The person who removes the last stick loses!")
print("Example: to remove 3 sticks from pile 2, enter 3 2")
player_win = True
while True:
print("Pile state %s" % (game.board))
# player's turn
user = str(input("Player turn: "))
player_remove = [int(i) for i in user.split(' ')]
while not isValid(player_remove, game.board):
print("Invalid move! Please input again.")
user = str(input("Player turn: "))
player_remove = [int(i) for i in user.split(' ')]
game.update(player_remove[1], player_remove[0])
if sum(game.board) == 0:
player_win = False
break
elif sum(game.board) == 1:
break
print("Computer turn")
game.computerUpdate()
if sum(game.board) == 0:
break
elif sum(game.board) == 1:
player_win = False
break
if player_win:
print(game.board)
print("You won!")
else:
print(game.board)
print("You lost!")