我目前正在使用Python 3制作一个简单的Battleships游戏,但我似乎无法让棋盘显示出来。这是我的代码;
# Battleships
def main():
pass
if __name__ == '__main__':
main()
from random import randint
# this initialises the board
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print (" ".join(row))
# this starts the game and prints the board
print ("Let's play Battleship!")
print_board(board)
# defines the location of the ship
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
# asks the player to make a guess
for turn in range(5):
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
# if the player guesses correctly, then the game ends cleanly
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
else:
# if the player guesses outside the board, then the following message appears
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print ("Oh dear, you've hit an island!")
# a warning if the guess has already been made by the player
elif(board[guess_row][guess_col] == "X"):
print ("That guess has already been made.")
# if the guess is wrong, then the relevant board place is marked with an X
else:
print ("You've missed my battleship!")
board[guess_row][guess_col] = "X"
# prints the turn and updates the board accordingly
print ("Turn " + str(turn+1) + " out of 5.")
print_board(board)
# if the user has had 5 guesses, it's game over
if turn >= 3:
print ("You sunk my battleship! We're gonna need a bigger boat.")
游戏接受坐标,但不会打印任何与棋盘有关的内容,或者玩家是否重复猜测或者是否在游戏区域之外。
非常感谢任何帮助!
答案 0 :(得分:2)
你的代码在对它们做任何事情之前要求5组猜测,因为响应猜测的代码在循环之外要求猜测。我,咳咳,猜测你在测试中从未输入足够的猜测来超越那个循环。将猜测处理代码移动到循环中,您至少应该看到对这些猜测的反应。
答案 1 :(得分:0)
你正在循环遍历所有if语句。将所有if语句放在for循环中。添加一个计数器,如果你点击我的船只添加一个点(score += 1
)然后
if score >= 3:
print ("You sunk my battleship! We're gonna need a bigger boat.")