Michael的Python笔记(二)

本文详细介绍了Battleship游戏的操作流程与实现细节,包括如何检查玩家猜测的准确性,实现玩家与计算机之间的交互,以及如何处理正确和错误的猜测情况。通过代码示例,深入浅出地展示了Battleship游戏的开发过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Battle ship

操作规程

You win!

Okay—now for the fun! We have the actual location of the ship and the player’s guess so we can check to see if the player guessed right.

For a guess to be right, guess_col should be equal to ship_col and guess_row should be equal to ship_row.

if guess_col == 0 and guess_row == 0:
print “Top-left corner.”

The example above is just a reminder about if statements.
说明

On line 29, add an if guess_row equals ship_row and guess_col equals ship_col.
If that is the case, please print out "Congratulations! You sank my battleship!"

源码

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)
guess_row = int(raw_input(“Guess Row:”))
guess_col = int(raw_input(“Guess Col:”))

print ship_row
print ship_col

if guess_row == ship_row and guess_col == ship_col:
print “Congratulations! You sank my battleship!”

生成控制台图示

这里写图片描述


接下来

Great! Of course, the player isn’t going to guess right all the time, so we also need to handle the case where the guess is wrong.

The example above prints out “O”, the element in the 3rd row and 4th column.
说明

Add an else under the if we wrote in the previous step.
Print out "You missed my battleship!"
Set the list element at guess_row, guess_col to "X".
As the last line in your else statement, call print_board(board) again so you can see the "X".

Make sure to enter a col and row that is on the board!

好玩的代码

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)
guess_row = int(raw_input(“Guess Row:”))
guess_col = int(raw_input(“Guess Col:”))

print ship_row
print ship_col

if guess_row == ship_row and guess_col == ship_col:
print “Congratulations! You sank my battleship!”
else:
print “You missed my battleship!”
board[guess_row][guess_col] = “X”
print_board(board)

图示

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值