当我输入正确的整数以调用hit()或miss()时,print语句将第一次打印到控制台,但此后不打印到控制台。 每次都会调用players_turn()函数,但不会调用print语句。 我的控制台也没有出现任何错误
import numpy as np
from random import randint
board = []
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print (" ".join(row))
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)
def players_turn():
for turn in range(4):
print ("turn", turn +1)
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
def hit():
print ("direct hit")
board[guess_col][guess_row] = "H"
print_board(board)
players_turn()
def miss():
print ("you missed, try again")
board[guess_col][guess_row]
print_board(board)
players_turn()
def out_of_range():
print ("this is out of the range of the battle field")
players_turn()
if_yes = str(raw_input("Do you want to play Battleship? "))
if if_yes == 'yes':
print ship_row
print ship_col
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
if guess_col == ship_col and guess_row == ship_row:
hit()
elif guess_col not in range(5) or guess_row not in range(5) :
out_of_range()
else:
miss()
我希望每次输入正确的hit()凭据时,我都会得到: “直接命中”,棋盘将被打印到控制台。 如果符合miss()凭证,我将得到: “您错过了,再试一次”,然后将打印出木板。
答案 0 :(得分:0)
您的代码存在多个问题。我在不做太多修改的情况下移动了您的代码。我使用Python 3.7。这里是问题。
raw_input
已停产。请改用input
。print
作为函数。因此,您需要括号。如果您使用的是Python 2.x,则可以忽略它。players_turn
。因此,其余的输入请求和函数调用都在其下。否则,它只会要求用户输入而不会执行任何操作players_turn
时,不要从hit
,miss
和out_of_range
等其他函数中调用它。这是更新的代码
import numpy as np
from random import randint
board = []
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print (" ".join(row))
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
def hit():
print ("direct hit")
board[guess_col][guess_row] = "H"
print_board(board)
def miss():
print ("you missed, try again")
board[guess_col][guess_row]
print_board(board)
def out_of_range():
print ("this is out of the range of the battle field")
def players_turn():
for turn in range(4):
print ("turn", turn +1)
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
if guess_col == ship_col and guess_row == ship_row:
hit()
elif guess_col not in range(5) or guess_row not in range(5) :
out_of_range()
else:
miss()
ship_row = random_row(board)
ship_col = random_col(board)
if_yes = str(input("Do you want to play Battleship? "))
if if_yes == 'yes':
print (ship_row)
print (ship_col)
players_turn()