-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameLogic.py
421 lines (382 loc) · 14.6 KB
/
GameLogic.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""@package docstring
GameLogic.py (or, MineSweeper.py) should deal with the handling of the game's
run time logic.
Question: Maybe both client AND server side logic should be handled here. Since
we're currently looking at three different game modes, we can throw all of our
logic here and then just have the three modes do everything on their own?
That way there's no need to worry about client/server stuff if you're in
single player mode
"""
from Board import *
from colorama import Fore, Style
from OFF_Network import *
from Time import *
from Leaderboard import *
def show(board, lose=False):
"""
Shows current state of board in command line.
:param Board board: The current Board object.
:return None:
"""
if lose:
for i in range(board.height):
for j in range(board.width):
if not board.grid[i][j].isBomb:
board.grid[i][j].isRevealed = True
print(" ", end="")
for i in range(board.width):
print(" " + f"{i:02}" + " ", end="")
print()
print(" ", end="")
for i in range(board.width):
print('----', end="")
print()
for i in range(board.height):
print(f"{i:02}", end="")
print("|",end="")
for j in range(board.width):
if board.grid[i][j].isFlagged:
print(Fore.RED + " F ", end='')
elif board.grid[i][j].isRevealed:
if board.grid[i][j].adj == 0:
print(Fore.GREEN + " _ ", end='')
else:
print(Fore.CYAN + " " + str(board.grid[i][j].adj)+ " ", end='')
elif lose:
if board.grid[i][j].isBomb:
print(Fore.MAGENTA + " B ", end='')
else:
print(Fore.WHITE + " X ", end="")
else:
print(Fore.WHITE + " X ", end="")
print(Style.RESET_ALL)
def cheat_show(board):
"""
Fully displays board, regardless of reveals/flags.
:param Board board: The current Board object.
:return None:
"""
print(" ", end="")
for i in range(board.width):
print(" " + f"{i:02}" + " ", end="")
print()
print(" ", end="")
for i in range(board.width):
print('----', end="")
print()
for i in range(board.height):
print(f"{i:02}", end="")
print("|",end="")
for j in range(board.width):
if board.grid[i][j].isBomb:
print(Fore.MAGENTA + " B ", end='')
elif board.grid[i][j].adj == 0:
print(Fore.GREEN + " _ ", end='')
else:
print(Fore.CYAN + " " + str(board.grid[i][j].adj)+ " ", end='')
print(Style.RESET_ALL)
def cheatMode(board):
"""
Activates cheat mode, which reveals the entire board. Only accessible in single-player mode.
:param Board board: The current Board object.
:return None:
"""
#board.displayBoard(); for checking correct output
cheat_show(board);
for x in range(1, 6):
print (f"{x}...")
time.sleep(1)
def inputNumber(prompt):
"""
Catches inputs by user for anything other than an integer.
:param string prompt: The input provided by the user.
:return int: The prompt converted to an int.
"""
while True:
try:
userInput = int(input(prompt))
except ValueError:
print("Pick a whole number, silly goose... try again.")
else:
return userInput
def promptCheck(prompt):
"""
Checks for valid inputs at the menu prompt.
:param string prompt: The input provided by the user.
:return int: True if the input is valid, False otherwise.
"""
arr = prompt.split(" ")
if arr[0] not in ["r", "f", "q", "-c", "l"]:
return False
if arr[0] == "r" or arr[0] == "f":
if len(arr) < 3:
return False
try:
int(arr[1])
int(arr[2])
except ValueError:
return False
return True
def game_input():
'''
@pre Handles start game initial board parameters
@post None
@return height,width,mines tuple (ints)
'''
height = inputNumber("Enter the height of the board: ")
while height > 24 or height < 2:
height = inputNumber("Please enter a height between 2 and 24: ")
width = inputNumber("Enter the width of the board: ")
while width > 24 or width < 2:
width = inputNumber("Please enter a width between 2 and 24: ")
mines = inputNumber("Enter the number of mines: ")
while mines >= height*width or mines <= 0:
mines = inputNumber(f"Please use from 1 to {height*width - 1} mines: ")
#add bounds checking
return height, width, mines
def click(board, row, column, action):
"""
Selects Cell to perform intended action on.
:param Board board: The current Board object.
:param int row: The row within the grid.
:param int column: The column within the grid.
:param string action: The action to perform on the Cell.
:return bool: True if the user selects a bomb, False otherwise.
"""
if action == "r":
if board.grid[row][column].isBomb:
return True
elif board.grid[row][column].isFlagged:
print("You can't reveal a flagged square. Please remove the flag and try again.")
return False
else:
spread(board, row, column)
return False
elif action == "f":
if board.grid[row][column].isRevealed:
print("You cannot flag an space that's already revealed.")
elif board.grid[row][column].isFlagged:
board.flagCount -= 1
board.grid[row][column].isFlagged = False
else:
if board.flagCount == board.mines:
print("You cannot use more flags than bombs... remove a flag to place another;\n"
"place a flag on a square that has a flag in order to remove it.")
else:
board.flagCount += 1
board.grid[row][column].isFlagged = True
return False
def spread(board, row, column):
"""
Recursively reveals adjacent Cells if they are empty.
:param Board board: The current Board object.
:param int row: The row within the grid.
:param int column: The column within the grid.
"""
if (board.grid[row][column].adj > 0 or board.grid[row][column].isRevealed):
board.grid[row][column].isRevealed = True
else:
board.grid[row][column].isRevealed = True
if row-1 >= 0:
spread(board, row-1, column)
if row+1 < board.height:
spread(board, row+1, column)
if column-1 >= 0:
spread(board, row, column-1)
if column+1 < board.width:
spread(board, row, column+1)
def run_singleplayer(board):
"""
User is prompted for board params in host,
run_singleplayer plays game
param Board board: require the game board at start
:return None:
"""
timeTaken = Time()
show(board)
lose = False
flaggedBombCount = 0
leaders = Leaderboard('leaderboard.txt')
#begin game loop
while not lose and flaggedBombCount != board.mines:
choice = input("MENU:\n Reveal Square: r x y\n Add or Remove Flag: f x y\n Quit: q\n Show Leaderboard: l\n <Prompt>: ").lower() #TODO discuss possible prompts, like turn counter
if promptCheck(choice):
action = choice.split()[0]
if action == "-c":
cheatMode(board)
show(board)
if action == "r" or action == "f":
column, row = int(choice.split()[1]), int(choice.split()[2])
if column >= board.width or column < 0:
print ("Out of bounds x coordinate!")
while True:
try:
column = int(input("x: "))
while column >= board.width or column < 0:
column = int(input("Out of bounds! x: "))
break
except ValueError:
print ("Invalid input!")
if row >= board.height or row < 0:
print ("Out of bounds y coordinate!")
while True:
try:
row = int(input("y: "))
while row >= board.height or row < 0:
row = int(input("Out of bounds! y: "))
break
except ValueError:
print ("Invalid input!")
lose = click(board, row, column, action)
if board.grid[row][column].isBomb and board.grid[row][column].isFlagged:
flaggedBombCount += 1
show(board)
elif action == "q":
break
elif action == 'l':
leaders.get_leaderboard(10)
input("Press enter to return to game: ")
show(board)
else:
print("Invalid command. Pick a whole number, silly goose... try again.")
timeTaken.game_over_time()
if lose:
print("Bomb detonated! You need more practice, young grasshopper.")
show(board, True)
leaders.get_leaderboard(10)
return timeTaken.show_total()
elif choice == "q":
print("Thank you for playing... come again!")
return timeTaken.show_total()
else:
print("*Mario Voice* You are the weiner!")
score = int(float((board.calculate_3bv()*100)/timeTaken.show_total()))
print("Your score calculated by board difficulty times time is", score)
if leaders.get_score(10) < score:
print("Congratulations, you made the leaderboard!")
leaders.add_entry(score)
leaders.get_leaderboard(10)
return timeTaken.show_total()
def run_coop(socket,address,turn,board):
"""
client side version of coop multiplayer
param Socket socket for sending each move
param string address of client socket
param bool turn, determine who's turn it is
param Board board, game board object
"""
print("You are: ", end="")
if turn:
print("player 1")
else:
print("player 2")
lose = False
flaggedBombCount = 0
show(board)
#begin game loop
while not lose and flaggedBombCount != board.mines:
if turn:
choice = input("MENU:\n Reveal Square: r x y\n Add or Remove Flag: f x y\n Quit: q\n <Prompt>: ").lower()
while not promptCheck(choice):
print("Invalid command. Pick a whole number, silly goose... try again.")
choice = input("MENU:\n Reveal Square: r x y\n Add or Remove Flag: f x y\n Quit: q\n <Prompt>: ").lower()
action = choice.split()[0]
if action == "r" or action == "f":
column, row = int(choice.split()[1]), int(choice.split()[2])
if column >= board.width or column < 0:
print ("Out of bounds x coordinate!")
while True:
try:
column = int(input("x: "))
while column >= board.width or column < 0:
column = int(input("Out of bounds! x: "))
break
except ValueError:
print ("Invalid input!")
if row >= board.height or row < 0:
print ("Out of bounds y coordinate!")
while True:
try:
row = int(input("y: "))
while row >= board.height or row < 0:
row = int(input("Out of bounds! y: "))
break
except ValueError:
print ("Invalid input!")
lose = click(board, row, column, action)
if board.grid[row][column].isBomb and board.grid[row][column].isFlagged:
flaggedBombCount += 1
show(board)
elif action == "q":
choice = serialize_data(choice)
send_comm(choice, socket,address)
break
#choice = serialize_data(choice)
choice = action + ' ' + str(column) + ' ' + str(row)
send_comm(choice, socket,address)
turn = False
else:
print("Waiting for the other player's turn!")
response = False
while response == False or response == 'False':
try:
response, address = socket.recvfrom(2048 * 2 * 2)
response = response.decode()
except:
print("Something went wrong")
print (response)
other_player_choice = response
action = other_player_choice.split()[0]
if action == "r" or action == "f":
column, row = int(other_player_choice.split()[1]), int(other_player_choice.split()[2])
lose = click(board,row,column,action)
if board.grid[row][column].isBomb and board.grid[row][column].isFlagged:
flaggedBombCount += 1
show(board)
elif action == "q":
print("Other player quit the game!")
break
turn = True
if lose:
print("Bomb detonated! You need more practice, young grasshopper.")
show(board, True)
elif choice == "q":
print("Thank you for playing... come again!")
else:
print("*Mario Voice* You are the weiner!")
def run_versus(socket, address, board):
'''
simple versus implementation
should allow for different ip addresses after some work
param Socket socket for communication, the local socket being used to
output info
param string address, the other player's IP address
param Board board object to track game board
'''
print("Starting game with these parameters:\n")
print("Height: " + str(board.height))
print("Width: " + str(board.width))
print("Mines: " + str(board.mines))
time.sleep(1)
for x in range(3,0,-1):
print (f"{x}...")
time.sleep(1)
print("GO!")
my_time = run_singleplayer(board)
my_time = str(my_time)
print("Your time is: " + my_time + "\nCompare this to your friend!")
my_time = float(my_time)
#countdown
#run_singleplayer
#receive other player's time
#compare em
#say who won
#the end
'''
def end_game()
player won
submit score
try again
player lost
try again
'''