由于某种原因,我用于检查猜测的位置和实际位置是否相同的if语句不起作用。我已经设置好了,所以我知道船在哪里。我已经尝试在输入猜测之后立即打印出所有变量及其各自的类型,并且在检查它们之前它们是相同的但是由于某种原因它只是继续并说我错过了。
但无论如何它是:
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)
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
##########################################
#Value error checking and guess row inputs
##########################################
def get_guess_row():
guess_row = int(raw_input("Guess Row:"))
return guess_row
def value_guess_row():
try:
y = get_guess_row()
except ValueError:
print ("Please enter a valid number.")
y = value_guess_row()
return y
##########################################
#Value error checking and guess col inputs
##########################################
def get_guess_col():
guess_col = int(raw_input("Guess Col:"))
return guess_col
def value_guess_col():
try:
x = get_guess_col()
except ValueError:
print ("Please enter a valid number.")
x = value_guess_col()
return x
###############################
#Get the coloumn and row values
###############################
guess_col = value_guess_col()
guess_row = value_guess_row()
guess_col -= 1
guess_row -= 1
print ("Guessed coloumn: ", guess_col, "the type is: ", (type(guess_col)))
print ("Guessed row: ", guess_row, "the type is: ", (type(guess_row)))
print ("Actual coloumn: ", ship_row, "the type is: ", (type(ship_row)))
print ("Actual row: ", ship_col, "the type is: ", (type(ship_col)))
# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sank my battleship!")
elif guess_row not in range(5) or \
guess_col not in range(5):
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)
答案 0 :(得分:1)
我刚刚运行了您的代码,它似乎工作正常:
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
4
1
Guess Col:2
Guess Row:5
('Guessed coloumn: ', 1, 'the type is: ', <type 'int'>)
('Guessed row: ', 4, 'the type is: ', <type 'int'>)
('Actual coloumn: ', 4, 'the type is: ', <type 'int'>)
('Actual row: ', 1, 'the type is: ', <type 'int'>)
Congratulations! You sank my battleship!
要记住的一些事情可能让您感到困惑:
1)当您打印随机列和行时,您将完全按照列表索引的外观显示它: 4 1
但是当你要求值时,你从读取值中减去1(因此如果随机行是3
,你输入的应该是4
)
2)当您打印系统生成的值时,您错放了行和列,将其更改为:
print ("Actual coloumn: ", ship_col, "the type is: ", (type(ship_row)))
print ("Actual row: ", ship_row, "the type is: ", (type(ship_col)))