【发布时间】:2019-09-22 10:16:30
【问题描述】:
美好的一天。我是编码初学者,基本上我用python做了一个简单的迷宫游戏。 它是 3x3,所以我制作了 9 个字典变量,详细说明了每个图块(北、南、东、西)的可能移动。 我的代码由嵌套的 if-elif 和一个主 while 循环组成。
if level == 1: #level of difficulty.
i = 0
maplist1 = {'directions1':'south'}
maplist2 = {'directions1':'south','directions2':'east'}
maplist3 = {'directions1':'west'}
maplist4 = {'directions1':'north','directions2':'east','directions3':'south'}
....
....
current_position = 1 #local variable within the first if statement
这是将重复的代码块的 sn-p,几乎没有变化(字面意思是重复)。
while i == 0: #to continuously loop the program
if current_position == 1:
directions = maplist1['directions1']
direction = input(f"What direction do you want to go: {directions} ").title() #choose the possible directions to go to.
if direction == "S" or direction == "South":
current_position = 4
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 2:
directions = maplist2['directions1']
directions2 = maplist2['directions2']
direction = input(f"What direction do you want to go: {directions} {directions2} ").title()
if direction == "S" or direction == "South":
current_position = 5
print(f"You are in cell {current_position}.")
elif direction == "E" or direction == "East":
current_position = 3
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 3:
directions = maplist3['directions1']
direction = input(f"What direction do you want to go: {directions} ").title()
if direction == "W" or direction == "West":
current_position = 2
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 4:
directions = maplist4['directions1']
directions2 = maplist4['directions2']
directions3 = maplist4['directions3']
direction = input(f"What direction do you want to go: {directions} {directions2} {directions3} ").title()
if direction == "N" or direction == "North":
current_position = 1
print(f"You are in cell {current_position}.")
elif direction == "S" or direction == "South":
current_position = 7
print(f"You are in cell {current_position}.")
elif direction == "E" or direction == "East":
current_position = 5
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
.......
......
.......
if current_position == 9:
print("Congratulations, you finished the game.")
i += 1 #to stop the loop
我的问题是如何使它更简单、更紧凑?
- 每次移动都必须记住当前位置
- 我知道如何使用 def,但不确定如何在我的迷宫游戏中实现它。
这个游戏有 3 个关卡,基本上是 3x3、4x4 和 5x5。这就是我询问有关如何缩短/压缩代码的任何想法的原因。
我不需要你给我你的代码,但是一些指导会很好地指导我如何继续,因为我现在感觉很迷茫。
【问题讨论】:
-
1.使用数据结构。 (列表、字典。) 2. 提取方法。
-
另外,这个问题可能更适合codereview.stackexchange.com
标签: python python-3.x