-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbs.py
More file actions
281 lines (227 loc) · 7.94 KB
/
Copy pathbs.py
File metadata and controls
281 lines (227 loc) · 7.94 KB
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
SQUARE_TYPE = {"NONE": " ", "HIT": "X", "MISS": "O"}
TOP_ROW_INDEX = 1
BOTTOM_ROW_INDEX = 10
RIGHTMOST_COLUMN_INDEX = 10
MAX_COLUMNS = 10
MAX_ROWS = 10
# BOARD STYLING
letters = "ABCDEFGHIJ"
boxPadding = "| "
rowPadding = (boxPadding * 10) + "|\n"
boxBorder = " |" + ("-" * 69) + "|\n"
def appendLetters(output):
output += " "
for i in range(10):
output += " " + letters[i] + " "
output += "\n"
return output
def newBoard():
board = []
for rows in range(MAX_ROWS):
newRow = []
for columns in range(MAX_COLUMNS):
newRow.append({"ship": None, "type": SQUARE_TYPE["NONE"]})
board.append(newRow)
return board
def printBoard(board, showShips):
if not currentState["visibleBoard"]:
return
boardOutput = "\n"
boardOutput = appendLetters(boardOutput)
boardOutput += boxBorder
for row in range(MAX_ROWS):
boardOutput += " " + rowPadding
if row + 1 > 9:
boardOutput += str(row + 1) + ""
else:
boardOutput += str(row + 1) + " "
for column in range(MAX_COLUMNS):
spot = board[row][column]
boxChar = ""
if showShips and spot["ship"]:
boxChar = spot["ship"]
else:
boxChar = spot["type"]
boardOutput += "| " + str(boxChar) + " "
boardOutput += "| " + str(row + 1) + "\n"
boardOutput += " " + rowPadding
boardOutput += boxBorder
boardOutput = appendLetters(boardOutput)
print(boardOutput)
def getNewState():
return {
"visibleBoard": True,
"player1Turn": True,
"p1board": newBoard(),
"p2board": newBoard(),
}
def deep_copy(obj):
if isinstance(obj, list):
return [deep_copy(item) for item in obj]
elif isinstance(obj, dict):
return {deep_copy(key): deep_copy(value) for key, value in obj.items()}
elif isinstance(obj, set):
return {deep_copy(item) for item in obj}
elif isinstance(obj, tuple):
return tuple(deep_copy(item) for item in obj)
else:
return obj
# game state
# not showing to prevent overwriting
savedGames = {}
currentState = getNewState()
def play():
print("Welcome to BattleShip! (NOT the movie)")
evalMenuChoice(getMenuOption())
def getMenuOption():
print("Please select an option:")
print("1 Start new game")
print("2 Load saved game")
print("3 See rules")
print("4 Settings")
print("5 Quit")
return input("Enter menu option")
def loadSavedGame():
msg = "Choose a game by its game name:\n"
for gameName in savedGames.keys():
msg += "- " + gameName + "\n"
chosenGameName = input(msg)
if chosenGameName in savedGames:
currentState = deep_copy(savedGames[chosenGameName])
makeGuesses()
else:
print("Game not found :(")
evalMenuChoice(getMenuOption())
def evalMenuChoice(c):
if c == "1":
setupBoard(1)
setupBoard(2)
makeGuesses()
elif c == "2":
loadSavedGame()
elif c == "3":
print("You don't know how to play BattleShip?... FFFF\n\n\n")
evalMenuChoice(getMenuOption())
elif c == "4":
print("Sorry we only have 1 setting")
print("Enter Yes/yes/Y/or y if you want to play with a visible board.")
print("Any other option will make the board invisible")
choice = input("Show board or play invisibly: ")
if choice.upper() in ["YES", "Y"]:
currentState["visibleBoard"] = True
else:
currentState["visibleBoard"] = False
evalMenuChoice(getMenuOption())
elif c == "5":
print("GG")
else:
print("Input Error, try again")
evalMenuChoice(getMenuOption())
def allHitsMade(board):
for i in range(MAX_ROWS):
for j in range(MAX_COLUMNS):
spot = board[i][j]
if spot["ship"] and spot["type"] != SQUARE_TYPE["HIT"]:
return False
return True
def isGameOver():
if currentState["player1Turn"]:
return allHitsMade(currentState["p2board"])
else:
return allHitsMade(currentState["p1board"])
def saveGame():
global savedGames, currentState
gameName = input(
"Enter a name to save this game under, it will overwrite anything with the same name: "
)
savedGames[gameName] = deep_copy(currentState)
currentState = getNewState()
def makeGuesses():
while True:
goAgain = False
print("Player " + str(1 if currentState["player1Turn"] else 2) + " it is your turn")
printBoard(currentState["p2board"] if currentState["player1Turn"] else currentState["p1board"], False)
guess = input("Where should we aim? (Enter QUIT to save and quit): ")
if guess.upper() == "QUIT":
saveGame()
print("See you soon!")
play()
break
else:
goAgain = handleGuess(guess)
if isGameOver():
print("Player " + str(1 if currentState["player1Turn"] else 2) + " wins!")
play()
break
if not goAgain:
currentState["player1Turn"] = not currentState["player1Turn"]
def handleGuess(guess):
if not guess:
print("Wasted turn")
return
row = int(guess[1:]) - 1
col = letters.index(guess[0].upper())
if col < 0 or col > 9 or row < 0 or row > 9:
print("Wasted turn")
return
spot = ""
if currentState["player1Turn"]:
spot = currentState["p2board"][row][col]
else:
spot = currentState["p1board"][row][col]
if spot["type"] != SQUARE_TYPE["NONE"]:
print("Wasted turn")
return
if spot["ship"]:
print("HIT")
spot["type"] = SQUARE_TYPE["HIT"]
return True
else:
print("MISS")
spot["type"] = SQUARE_TYPE["MISS"]
def setupBoard(playerNum):
curBoard = currentState["p1board"] if playerNum == 1 else currentState["p2board"]
setupShip(playerNum, curBoard, "aircraft carrier", 5)
setupShip(playerNum, curBoard, "battleship", 4)
setupShip(playerNum, curBoard, "destroyer", 3)
setupShip(playerNum, curBoard, "submarine", 3)
setupShip(playerNum, curBoard, "cruiser", 2)
def setupShip(playerNum, board, msg, size):
printBoard(board, True)
start = None
end = None
while not validateShipPlacement(start, end, size):
start = input("Player " + str(playerNum) + ", Where would you like your " + msg + " (size " + str(size) + ") to start? e.g. A1: ")
end = input("Player " + str(playerNum) + ", Where would you like your " + msg + " (size " + str(size) + ") to end? e.g. A2: ")
addShip(board, start, end, size)
print(msg + " added!")
# TODO don't place ships on other ships
def validateShipPlacement(start, end, size):
if not start or not end:
return False
if start == "quit" or end == "quit":
raise Exception("cheat code to restart")
startLetter = start[0].upper()
endLetter = end[0].upper()
startNumber = int(start[1:])
endNumber = int(end[1:])
return (
(startLetter == endLetter and abs(startNumber - endNumber) == size - 1)
or (
startNumber == endNumber
and abs(letters.index(startLetter) - letters.index(endLetter)) == size - 1
)
)
def addShip(board, start, end, size):
if start[0].upper() == end[0].upper():
i = int(start[1:]) - 1
j = letters.index(start[0].upper())
for k in range(size):
board[i + k][j]["ship"] = size
else:
i = int(start[1:]) - 1
j = letters.index(start[0].upper())
for k in range(size):
board[i][j + k]["ship"] = size
# start game
play()