MCPcopy Create free account
hub / github.com/Mrinank-Bhowmick/python-beginner-projects / game

Function game

projects/Battleship/main.py:53–121  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

51
52
53def game():
54 global board
55 print(
56 "Welcome to Battleship.\n\nA ship, one cell long, has been randomly placed on the below %dx%d grid.\nYou have %d turns to find it.\n"
57 % (size, size, size)
58 )
59
60 # Randomly places Battleship
61 ship_row = random_row(board)
62 ship_col = random_col(board)
63
64 # The next two lines are for debugging purposes. They display the position of the battleship.
65 # print(ship_row + 1)
66 # print(ship_col + 1)
67
68 print_board(board)
69
70 # Give the user the amount of turns they chose, between 5 and 10.
71 for turn in range(size):
72 print("\nTurn", turn + 1, "of", size, "\n")
73
74 # Check if Guess Row and Column are numbers before continuing
75 while True:
76 try:
77 guess_row = int(input("Guess Row: ")) - 1
78 if guess_row not in range(0, size):
79 raise ValueError()
80 except ValueError:
81 print("Enter a valid selection!")
82 continue
83 else:
84 break
85
86 while True:
87 try:
88 guess_col = int(input("Guess Column: ")) - 1
89 if guess_col not in range(0, size):
90 raise ValueError()
91 except ValueError:
92 print("Enter a valid selection!")
93 continue
94 else:
95 break
96
97 # Checks if Player wins
98 if guess_row == ship_row and guess_col == ship_col:
99 input(
100 "Congratulations! You sank my battleship!\n\nPress enter to continue."
101 )
102 board = []
103 new_game()
104 break
105 else: # Guesses are outside of playing field
106 if (guess_row > size or guess_row < 0) or (
107 guess_col > size or guess_col < 0
108 ):
109 print("Oops, that's not even in the ocean.")
110 # Player previously guessed their current guesses

Callers 1

new_gameFunction · 0.70

Calls 4

random_rowFunction · 0.70
random_colFunction · 0.70
print_boardFunction · 0.70
new_gameFunction · 0.70

Tested by

no test coverage detected