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) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1# Print (turn + 1) here!
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 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)
if turn == 3:
print "Game Over"
我对此代码有一些疑问:
1
,2
,3
等)时,它显示为2
,3
,{{ 1}}因此。我希望它从4
计算,而不是从1
计算;我该怎么做?答案 0 :(得分:0)
1:board[guess_row][guess_col] = "X"
应为board[guess_row-1][guess_col-1] = "X"
。
2:见下文:
try:
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
except ValueError:
print "Your gunners were asleep on the job!"
if turn == 3:
print "Game Over"
continue
3:而不是:
board = []
for x in range(5):
board.append(["O"] * 5)
使用列表理解:
board = [['O' for i in range(5)] for j in range(5)]
在Python 2中,通常最好使用xrange
而不是range
。在Python 3中使用range
。
除此之外,您的代码非常好且简单明了。 :)
以下是该计划的完整代码。我没有安装Python 2,所以我在Skulpt
进行了测试,结果非常好。
from random import randint
board = [['O' for i in range(5)] for j in range(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) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1# Print (turn + 1) here!
try:
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
except ValueError:
print "Your gunners were asleep on the job!"
if turn == 3:
print "Game Over"
continue
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if 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-1][guess_col-1] = "X"
print_board(board)
if turn == 3:
print "Game Over"