这里将介绍一个采用声纳寻找宝藏的游戏。
首先来了解一下这个游戏涉及到一些概念,并且介绍这个游戏是如何玩的。
目录
(五)getRandomChests(numChests):
(七)makeMove(board, chests, x, y):
(八)enterPlayerMove(previousMoves):
(一)游戏说明
先来了解一些简单的概念
笛卡尔坐标系:所谓笛卡尔坐标系,就是常见的xoy平面直角坐标系。
数据结构:数据结构是存储表示某些事物的值的排列组合。这个游戏采用列表的列表这样的复杂变量作为数据结构。
声纳:声纳是轮船用于定位海底物体的一种技术。这个游戏的“声纳”设备将告诉玩家距离最近的宝藏有多远,但是不会告诉玩家藏宝箱在哪个方向。
游戏规则:
玩家要收集3个藏宝箱,而玩家只有16个声纳设备可以用于找到它们。
下面分析这个游戏的源代码,将分为一下几个部分。
(二)导入模块
在程序的开始处,我们导入random、sys和math模块:
#Sonar Treasure Hunt
import random
import sys
import math
这里需要介绍的是sys模块。sys模块包含了exit()函数,该函数立即终止了程序的执行。在sys.exit()调用之后,就没有要运行的代码行了。
下面将自定义一些函数。
(三)getNewBoard():
通过这个函数拆功能键一个新的游戏版,包含列表的列表。通过在循环里嵌套循环实现,并通过random()函数随机绘制符号,构成海洋。
#创建一个新的游戏板,Sonar游戏的游戏版是周围由X轴和Y轴坐标包围这的一个ASCII字符图“海洋”。
# board数据结构是字符串的列表的一个列表。
def getNewBoard():
#Create a new 60x15 board date structure.
board = []
for x in range(60):
#The main list is a list of 60 lists.
board.append([])
for y in range(15):
#Each list in the main list has 15 single-caracter string.
#Use different character for the ocean to make it more readable.
if random.randint(0, 1) == 0:
board[x].append('~')
else:
board[x].append('`')
return board
(四)drawBoard(board):
通过drawBoard()函数打印游戏版。游戏版就是一个笛卡尔坐标系。
#绘制游戏板
def drawBoard(board):
#Draw the board data structure.
tensDigitsLine = ' '#Initial space for the numbers down the left side of the board.
for i in range(1, 6):
tensDigitsLine += (' ' * 9) + str(i)
#Print the numbers across the top of the board.
print(tensDigitsLine)
print(' ' + ('0123456789' * 6))
print()
# Print each of the 15 rows.
for row in range(15):
#Single-digit numbers need to be padded with an extra space.
if row < 10:
extraSpace = ' '
else:
extraSpace = ''
# Creat the string for this row on the board.
boardRow = ''
for column in range(60):
boardRow += board[column][row]
print('%s%s %s %s' % (extraSpace, row, boardRow, row))
# Print the numbers across the bottom of the board.
print()
print(' ' + ('0123456789' * 6))
print(tensDigitsLine)
运行这个函数的话将会打印如下的游戏版:
1 2 3 4 5
012345678901234567890123456789012345678901234567890123456789
0 ```~~~`~~`~`~~~~```~~~`~~`~``~~~~~~~~``~~``~``~~``~~``~`~``` 0
1 ~~~``~~````~`~~`~~~~~~`~~~~```~`~~``~~``~~`~``~`~``~``~~~~~` 1
2 ~`~~~```~~~~```~``~`~~`~~~`~`~``~``~~``~`~~~~`~``~~```~``~~~ 2
3 ~~`~`~~``~`~~~``~~~~`~``~`~`~~~~`~`~~`~~`~````~`~``~~`~`~`~~ 3
4 ~~~~~`~`~~``~`~~~`~``~`~~```~`~```~~~~~``~~~`````~`~`~````~~ 4
5 ~~`~`~~``~~`~`~`~~~`~`~`~~~`~~~`~~`~~`~````~``~````~~~~`~~~` 5
6 ~~`````~`~````~`~`~```~`~~~~~~~`~~``~````~``~```~`~~~```~~~` 6
7 ~````~~`~~~`~````~```~`~`~`~~``~`~~~~``~`~```~``~~~~~```~`~~ 7
8 `~~```~~~~`~~`~`~~`~~```~~`~~~~~```~~~~~~````~~``~`````~~`~~ 8
9 ``~``~~~``~`~`~~~~`````~~``~~`~`~`~```~`~~~~`~````~``~~``~~~ 9
10 `~~~``~~```~``~`~~````~`````~~~``~``~``~~~~~~`~``~``&