Skip to content

Commit eacd610

Browse files
Célande AdrienCDaffyJr
authored andcommitted
[3] check player input
1 parent 39802e0 commit eacd610

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

torpydo/battleship.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
myFleet = []
1515
enemyFleet = []
16+
BAD_POSITION_INPUT_MSG = "The position is invalid. Please try enter a letter and a number like: 'A1'"
1617

1718

1819
def main():
@@ -78,7 +79,11 @@ def start_game():
7879
start_colouring(Fore.GREEN)
7980
print("Player, it's your turn")
8081
print("Coordinates should be written in the following format 'LetterNumber' as in C1, F4")
81-
position = parse_position(input("Enter coordinates (A-H, 1-8) for your shot :"))
82+
try:
83+
position = parse_position(check_position_input("Enter coordinates (A-H, 1-8) for your shot :"))
84+
except Exception:
85+
print(BAD_POSITION_INPUT_MSG)
86+
continue
8287
end_colouring()
8388

8489
is_hit = GameController.check_is_hit(enemyFleet, position)
@@ -188,9 +193,16 @@ def initialize_myFleet():
188193
print()
189194
print(f"Please enter the positions for the {ship.name} (size: {ship.size})")
190195

191-
for i in range(ship.size):
192-
position_input = input(f"Enter position {i+1} of {ship.size} (i.e A3):")
196+
i = 0
197+
while i < ship.size:
198+
try:
199+
position_input = check_position_input(f"Enter position {i+1} of {ship.size} (i.e A3):")
200+
except Exception:
201+
print(BAD_POSITION_INPUT_MSG)
202+
continue
203+
else:
193204
ship.add_position(position_input)
205+
i += 1
194206
TelemetryClient.trackEvent('Player_PlaceShipPosition', {'custom_dimensions': {'Position': position_input, 'Ship': ship.name, 'PositionInShip': i}})
195207

196208
def initialize_enemyFleet():
@@ -220,5 +232,11 @@ def initialize_enemyFleet():
220232
enemyFleet[4].positions.append(Position(Letter.C, 5))
221233
enemyFleet[4].positions.append(Position(Letter.C, 6))
222234

235+
def check_position_input(msg: str):
236+
string = input(msg)
237+
assert len(string) == 2 and string[0].isalpha() and string[1:].isnumeric()
238+
return string
239+
240+
223241
if __name__ == '__main__':
224242
main()

0 commit comments

Comments
 (0)