gpt4 book ai didi

python - 对于简单的迷宫游戏,如何使代码更短?

转载 作者:行者123 更新时间:2023-12-01 07:14:34 24 4
gpt4 key购买 nike

美好的一天。我是编码初学者,基本上我使用 python 制作了一个简单的迷宫游戏。它是 3x3,所以我创建了 9 个字典变量,详细说明了每个图 block 可能的移动(北、南、东、西)。我的代码由嵌套的 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

这是将重复的代码块的片段,几乎没有变化(字面意思是重复)。

    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。这就是为什么我询问有关如何缩短/压缩代码的任何想法的原因。

我不需要你给我你的代码,但一些关于如何继续的指导会很好,因为我现在感觉迷失了。

最佳答案

尝试创建迷宫数据结构。一个典型的想法是创建一个二维单元阵列,每个单元都有北/西/南/东墙。

让我们创建一个类,以便更好地理解。我希望您忽略除 can_move() 方法之外的所有内容

class Cell:
def __init__(self, walls):
self.walls = walls

def __str__(self):
"""Allows us to call print() on a Cell!"""
return '\n'.join(self.draw())

def _draw_wall(self, wall, s):
return s if wall in self.walls else ' ' * len(s)

def draw(self, inner=' '):
"""Draw top, mid, and bottom parts of the cell."""
n = self._draw_wall('N', '___')
w = self._draw_wall('W', '|')
e = self._draw_wall('E', '|')
s = self._draw_wall('S', '___')
top = ' ' + n + ' '
mid = w + inner + e
bot = w + s + e
return top, mid, bot

def can_move(self, direction):
return direction not in self.walls

让我们制作一些单元格,看看它们是什么样子:

>>> Cell('NWSE')
___
| |
|___|

>>> Cell('NWS')
___
|
|___

现在,迷宫是由二维单元列表组成的。这是一个小迷宫:

maze = Maze(width=3, height=3, rows=[
[Cell('NWE'), Cell('NW'), Cell('NE')],
[Cell('WE'), Cell('WE'), Cell('WE')],
[Cell('WS'), Cell('SE'), Cell('WSE')]
])

看起来像这样:

>>> maze
___ ___ ___
| x || |
| || |

| || || |
| || || |

| || |
|___ ___||___|

但是等等!我们还没有定义什么是Maze。再次忽略所有与绘图相关的内容并专注于move_direction()

class Maze:
def __init__(self, width, height, rows):
self.width = width
self.height = height
self.rows = rows
self.position = (0, 0)

def __str__(self):
return '\n'.join(self.draw_row(i) for i, _ in enumerate(self.rows))

def _inner(self, i, j):
return ' x ' if (i, j) == self.position else ' '

def draw_row(self, i):
triples = [
cell.draw(self._inner(i, j)) for j, cell in enumerate(self.rows[i])
]
return '\n'.join([
''.join(t for t, _, _ in triples),
''.join(m for _, m, _ in triples),
''.join(b for _, _, b in triples)])

def cell_at_position(self, i, j):
return self.rows[i][j]

def move_direction(self, direction):
curr_cell = self.cell_at_position(*self.position)
if not curr_cell.can_move(direction):
print("Can't go in that direction!")
return
deltas = {'N': (-1, 0), 'W': (0, -1), 'S': (1, 0), 'E': (0, 1)}
y, x = self.position
dy, dx = deltas[direction]
self.position = y + dy, x + dx

要使用它,只需创建一个简单的小循环:

while True:
print(maze)
direction = input('What direction? ')
maze.move_direction(direction)

观看奇迹发生!

你可以试试here .

关于python - 对于简单的迷宫游戏,如何使代码更短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com