如何在Python中的迷宫中移动老鼠

问题描述 投票:0回答:3

我对Python真的很陌生,我正在尝试做一个游戏,迷宫中的老鼠试着吃布鲁塞尔芽菜-所以我有2只老鼠-'J'和'P'和2类-Rat和Maze。到目前为止,Rat类的所有功能都可以工作-而我在迷宫类的最后一个功能上陷于困境!这两类是交织在一起的。我在解决Maze类的move方法时遇到问题-这是下面的两个类。

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'
num_sprouts_eaten = 0



class Rat:
    """ A rat caught in a maze. """

    # Write your Rat methods here.
    def __init__(Rat, symbol, row, col):
        Rat.symbol = symbol
        Rat.row = row
        Rat.col = col

        num_sprouts_eaten = 0

    def set_location(Rat, row, col):

        Rat.row = row
        Rat.col = col

    def eat_sprout(Rat):
        num_sprouts_eaten += 1        

    def __str__(Rat):
        """ (Contact) -> str

        Return a string representation of this contact.
        """
        result = ''

        result = result + '{0} '.format(Rat.symbol) + 'at '

        result = result + '('+ '{0}'.format(Rat.row) + ', '
        result = result + '{0}'.format(Rat.col) + ') ate '
        result = result + str(num_sprouts_eaten) + ' sprouts.'
        return result

迷宫类:“”“ 2D迷宫。”“”

    def __init__(Maze, content, rat_1, rat_2):
        Maze.content= content

        Maze.rat_1 = RAT_1_CHAR
        Maze.rat_2 = RAT_2_CHAR

    def is_wall(Maze, row,col):

        return (Maze.content[row][col] == '#') 

    def get_character(Maze,row, col):
        chars = ''
        if 'J' in Maze.content[row][col]:
            chars = 'J'
        elif 'P' in Maze.content[row][col]:
            chars = 'P'
        elif '#' in Maze.content[row][col]:
            chars = WALL
        else:
            chars = HALL
        return chars

    def move(Maze, Rat, hor, ver):
        num_sprouts_left = sum(x.count('@') for x in Maze.content[row][col])
        nowalls = False
        if Rat in Maze.content[row][col] and Maze.is_wall(row, col) == True:
            NO_CHANGE = Rat.set_location(row+0,col+0)

        if Rat in Maze.content[row][col] and Maze.is_wall(row, col) == False:
            UP = Rat.set_location(row,col+1)
            if UP == SPROUT:
               Rat.eat_sprout(Rat)
               num_sprouts_left -= 1
               SPROUT=HALL
        if Rat in Maze.content[row][col] and Maze.is_wall(row, col) == False:
            DOWN = Rat.set_location(row,col-1)
            if DOWN == SPROUT:
               Rat.eat_sprout(Rat)
               num_sprouts_left -= 1
               SPROUT=HALL
        if Rat in Maze.content[row][col] and Maze.is_wall(row, col) == False:
            LEFT = Rat.set_location(row-1,col)
            if LEFT == SPROUT:
               Rat.eat_sprout(Rat)
               num_sprouts_left -= 1
               SPROUT=HALL
        if Rat in Maze.content[row][col] and Maze.is_wall(row, col) == False:
            RIGHT = Rat.set_location(row+1,col)
            if RIGHT == SPROUT:
               Rat.eat_sprout(Rat)
               num_sprouts_left -= 1
               SPROUT=HALL 

            nowalls = True

        return nowalls

因此,当我通过迷宫对象调用move方法时,会收到错误消息!

>>> d = Maze([['#', '#', '#', '#', '#', '#', '#'], 
      ['#', '.', '.', '.', '.', '.', '#'], 
      ['#', '.', '#', '#', '#', '.', '#'], 
      ['#', '.', '.', '@', '#', '.', '#'], 
      ['#', '@', '#', '.', '@', '.', '#'], 
      ['#', '#', '#', '#', '#', '#', '#']], 
      Rat('J', 1, 1),
      Rat('P', 1, 4))
>>> d.move('J',2,2)

Traceback (most recent call last):
  File "<pyshell#167>", line 1, in <module>
    d.move('J',2,2)
  File "C:\Users\gijoe\Downloads\a2.py", line 96, in move
    num_sprouts_left = sum(x.count('@') for x in Maze.content[row][col])
NameError: global name 'row' is not defined
>>> 

[请帮助我修复错误消息,并将老鼠移动到迷宫中的任意位置(只要它在走廊中!)!

python list move messages maze
3个回答
1
投票

[当您执行Maze.content[row][col]时,python查找名为rowcol的变量,并尝试将它们用作Maze.content的索引。由于row(和col)未在move()中定义,并且也未全局定义,因此python会抛出NameError

尽管还有另一个问题。即使if在该行之前设置了row = someNumbercol = someOtherNumber,也仍然无法获得预期的结果。调用Maze.content[row][col]将返回长度为一的字符串。 (值“#”,“ @”或“ _”)。因此,在该字符串上执行x.count(“ @”)会返回1或0。由于您正在对长度为1的字符串进行操作,因此num_sprouts_left将仅采用值1或0。

我假设您希望遍历entire迷宫以计算出芽的数量。您可以这样做:

num_sprouts_left = sum(row.count('@') for row in Maze.content)

在上述情况下,row 在生成器表达式中被分配了一个值。 (实际上,它被分配了多个值,每次迭代都分配一个不同的值)

关于使用MazeRat作为self参数的说明:

首先,您的第一个参数叫什么并不重要。您可以轻松完成:

def set_location(balloons, row, col):

    balloons.row = row
    balloons.col = col

这是因为python将class instance作为第一个参数传递。您键入的名称只有一个变量名,以便您可以在在特定方法内]引用它。

但是

该参数习惯上称为self。您应将其命名为self,以使代码清晰。

好吧,为什么不像我一直在叫它MazeRat

首先,因为它令人困惑。您实际上并没有在任何方法中引用class MazeRat,python将这些名称分配为class instance。某个人(包括您自己)可能稍后会阅读您的代码,并认为您是在引用类而不是实例。

第二,因为它会覆盖该方法中的类名。如果您实际上想在该方法中引用该类怎么办?不能,因为您用名称不正确的参数覆盖了该名称。


1
投票

您的程序有几个问题。我将指出一些主要的方面,然后让您进行研究。在学习Python时,请记住python.org上的Python文档是您的朋友。


0
投票

python迷宫解决方案(递归)递归可能是一个解决方案

© www.soinside.com 2019 - 2024. All rights reserved.