这次的练手程序依然来自于Knight lab的博客文章Five mini programming projects for the Python beginner,任务的名字叫做TextBased Adventure Game,也就是文字冒险游戏
目标:我们的目标是完整的建立一个文字小游戏,这个小游戏基于玩家的输入让玩家在不同的房间中移动,并且玩家可以知道当前房间的描述信息。为了完成这个游戏,我们需要定义可移动的方向,还要监控玩家已经移动的距离,她/他现在在那个房间里,并且需要在房间周围放置“墙壁”来做一下范围限制。
需要用到的python知识:
- string(字符串)
- Variables(变量定义)
- Input/Output(输入/输出)
- If/Else Statements(If/Else控制流语句)
- Print(输出语句)
- List(列表)
- Integers(整数类型)
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Firstly , we need a room, maybe it's length is 10m, width is 10m , and has a wall
# that length 5m in the meddle of the room
# the room looks like below
#
# ————————————————————
# | x |
# | |
# | |
# | |
# |—————————— |
# | |
# | |
# | o |
# |———————————————————|
# x is the starting point , and o is the destination
# use a list of list to discribe a room
room = [(x,y) for x in range(10) for y in range(10)]
# define which positions are in wall
wall = []
for position in room:
if position[0] == 0 or position[0] == 9:
wall.append(position)
elif position[1] == 0 or position[1] == 9:
wall.append(position)
elif position[1] == 4 and position[0] <= 4:
wall.append(position)
# define the function of how to move
def move(original_position, direction):
if direction == "r":
return original_position[0]+1, original_position[1]
elif direction == "l":
return original_position[0]-1, original_position[1]
elif direction == "u":
return original_position[0], original_position[1]-1
elif direction == "d":
return original_position[0], original_position[1]+1
#def mv_left(original_positin):
# return original_positin[0]-1, original_positin[1]
#
#def mv_up(original_positin):
# return original_positin[0], original_positin[1]-1
#
#def mv_down(original_positin):
# return original_positin[0], original_positin[1]+1
def adventure():
original_position = (1,1)
destination = (1,8)
while True:
if original_position == destination:
print "Congratulations, you got it!"
break
else:
direction = raw_input("Which direction would you like to move?(r/l/u/d) ").strip().lower()
if direction in ['r', 'd', 'l', 'u']:
final_position = move(original_position, direction)
if final_position in wall:
print "This direction is the wall"
print "You are on (%d,%d) now." % (original_position[0], original_position[1])
continue
else:
original_position = final_position
print "You are on (%d,%d) now." % (original_position[0], original_position[1])
continue
else:
print "You must input r,l,u or d"
continue
if __name__ == "__main__":
adventure()
以上是编写的text adventure 小脚本