我需要发表一个休息声明,代码的说明说:你的休息时间应该在你的"祝贺之后进入你的if语句!"消息。
from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
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)
print ship_row
print ship_col
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
break
print "Congratulations! You sunk my battleship!"
#I want to put my break satement here, but how?
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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"
# Print (turn + 1) here!
print_board(board)
if turn ==0:
print "Game Over"
答案 0 :(得分:1)
你需要一个while循环并将变量设置为一个值,如果错过了战舰,则将其减少1。
turn = 5 #set turn
while True:
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!" # print before you break
break
#I want to put my break statement here, but how?
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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!"
turn-=1 # decrease turn if player misses
board[guess_row][guess_col] = "X"
# Print (turn + 1) here!
print_board(board)
if turn ==0:
print "Game Over"
break
请记住,如果用户输入非int值,程序将崩溃。
答案 1 :(得分:0)
break
语句在您的代码中的任何位置都没有意义。 break
仅允许在循环内部(它突破)。你当前没有循环,尽管你应该这样做。
尝试使用while True
(永远循环直到你break
出来):
#board setup and function definitions omitted
print "Let's play Battleship!"
print_board(board)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
while True:
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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"
print_board(board)