0
我正在研究用python编写的2人战舰游戏。我的player_turns()使它在玩家1和玩家2之间交替。但是当你玩的时候它只停留在玩家1上,为什么会这样呢?另外,我注意到如果你找到了船的位置并开始一个新的游戏,那么这艘船就没有找到一个新的位置并且保持和上一次游戏相同的坐标。我怎样才能让坐标改变每场比赛?为什么我的player_turns()不增加1?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns():
total_turns = 0
if total_turns % 2 == 0:
return player_one
total_turns += 1
else:
return player_two
# Allows new game to start
def play_again():
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
total_turns = 0
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns() == player_one:
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns() == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 6:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
每当您调用'player_turns'时,您将'total_turns'重置为0. – asongtoruin
当我将total_turns = 0作为全局变量时,我得到以下错误'在分配前引用了局部变量total_turns'。 – zalidael
您确实需要阅读Python中的范围规则:什么是局部/全局变量,如何在函数之间共享变量等等。 – polku