<span style="font-family: 'Open Sans', 'Hevetica Neue', Helvetica, sans-serif; background-color: rgb(255, 255, 255);">这个项目中我们创建一个简单的,一人操控的经典班游戏"找战舰"。游戏中,一艘战舰被藏在5x5的方格中,玩家尝试10组数猜出这艘战舰的位置,即坐标。</span>
<span style="font-family: 'Open Sans', 'Hevetica Neue', Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="python">from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)//创建一个5x5的方格,全部标为o,表示大海范围
#打印出二维的表格
def print_board(board):
for row in board:
print " ".join(row)//.join()用来将list中的项目转变为字符串,并且用空格将里面的元素链接起来
print "Let's play Battleship!"
print_board(board)
#战舰所在的位置信息ship_row,ship_col
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
# 循化4次,即用户可以猜4次
for turn in range(4):
print "Turn",turn+1//变量turn+1
guess_row = int(raw_input("Guess Row:"))//玩家输入的值guess_row,guess_col
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 < 0 or guess_row > 4) or (guess_col <0 or guess_col > 4):
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!"//对找过的位置,更改方格的信息X
board[guess_row][guess_col] = "X"
if turn==3:
print "Game Over"
print_board(board)
<span style="font-family: 'Open Sans', 'Hevetica Neue', Helvetica, sans-serif; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: 'Open Sans', 'Hevetica Neue', Helvetica, sans-serif; background-color: rgb(255, 255, 255);">图1,战舰位置为[3,4],在第2次猜测下猜中战舰位置。<img src="https://img-blog.csdn.net/20150114184027081?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZW1iZWRjbHViX0xZRg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span>
<span style="font-family: 'Open Sans', 'Hevetica Neue', Helvetica, sans-serif; background-color: rgb(255, 255, 255);">图2,战舰位置是[2,1],4次都没有猜中,最后返回方格信息,标定X的即为踩过的位置。<img src="https://img-blog.csdn.net/20150114184009953?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZW1iZWRjbHViX0xZRg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span>
<span style="font-family:Open Sans, Hevetica Neue, Helvetica, sans-serif;"><转载请注明出处></span>