0
我試圖學習Python和Codecademy一直很好的幫助。在他們的課程之一中,我製作了一個簡化的戰列艦遊戲。現在我試圖通過添加第二條船來擴展它,但是它在「while」函數的「其他」附近給我一個「無效的語法」錯誤。 「while」功能的全部含義是在船上找到尚未被原船採用的第二艘船的位置。所有幫助表示讚賞!Python無效的語法......?
from random import randint
#Defines the board
board = []
for x in range(5):
board.append(["O"] * 5)
#How it should print the board
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!")
for turn in range(1):
print ("TURN ", turn + 1)
break
print_board(board)
#Spawns the boat on a random location on the board
def random_row1(board):
return randint(0, len(board) - 1)
def random_col1(board):
return randint(0, len(board[0]) - 1)
ship1_row = random_row1(board)
ship1_col = random_col1(board)
#Spawns the 2nd boat
def random_row2(board):
return randint(0, len(board) - 1)
def random_col2(board):
return randint(0, len(board[0]) - 1)
ship2_row = random_row2(board)
ship2_col = random_col2(board)
#Finds a new location for the 2nd boat if it is already taken by the 1st
#boat. It procceds with the game when an untapped location has been found.
while ship1_row == ship2_row and ship1_col == ship2_col:
ship2_row = randint(0, len(board) - 1)
ship2_col = randint(0, len(board[0] - 1)
else:
#Debugging
print ("Ship 1 row: ", ship1_row)
print ("Ship 1 col: ", ship1_col)
print (" ")
print ("Ship 2 row: ", ship2_row)
print ("Ship 2 col: ", ship2_col)
for turn in range(4):
realturn = turn + 1
guess_row = int(input("Guess row: "))
guess_col = int(input("Guess colum: "))
if guess_row == ship_row and guess_col == ship_col:
print ("CONGRATULATIONS! You sunk the battleship!")
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print ("Oops, that location isn't even in the ocean!")
elif(board[guess_row][guess_col] == "X"):
print ("You guessed that location already!")
else:
print ("You missed the battleship!")
board[guess_row][guess_col] = "X"
if turn == 3:
print ("GAME OVER!")
break
print (" ")
print ("TURN ", realturn + 1)
print_board(board)
你缺少一個括號:'randint(0,LEN(板[ 0] - 1))' – Keiwan
給出行號,而不是僅僅在「while」函數的「else」周圍說* * * – smci