1

这是一两只老鼠吃球芽甘蓝的游戏的python代码。它包含一个 Rat 类和 Maze 类:

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


class Maze:
    """ A 2D maze. """

    # Write your Maze methods here.
    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):
        walls = False

        if WALL in Maze.content[row*col]:
            walls = True
        return walls

现在,如果我通过调用 Rats 1 和 Rats 2 的迷宫和位置来初始化类。

Maze([['#', '#', '#', '#', '#', '#', '#'], 
      ['#', '.', '.', '.', '.', '.', '#'], 
      ['#', '.', '#', '#', '#', '.', '#'], 
      ['#', '.', '.', '@', '#', '.', '#'], 
      ['#', '@', '#', '.', '@', '.', '#'], 
      ['#', '#', '#', '#', '#', '#', '#']], 
      Rat('J', 1, 1),
      Rat('P', 1, 4))

字符“#”代表一堵墙,“.” 代表走廊或路径,“@”代表每个球芽甘蓝……

现在,如果墙壁('#')位于老鼠遇到的特定设置位置,我如何确保布尔值为 True,如果该特定设置位置没有墙壁,则返回 False?在这种情况下是走廊还是球芽甘蓝?

PS。这是 RAT_1_CHAR = 'J' RAT_2_CHAR = 'P' 在 Rats 和 Maze 类之前的定义...thnx

# Do not import any modules. If you do, the tester may reject your submission.
# Constants for the contents of the maze.
# 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
4

1 回答 1

3
def is_wall(self, row, col): return self.content[row][col] == '#'

您访问列表项的语法是错误的。您定义成员函数的语法也是如此。这一切都不可能发生。

当你学习一门语言时,一定要确保在构建更大的程序之前尝试编写和执行小程序(在这种情况下,是一个包含单个类的程序)。

于 2013-05-01T16:40:55.977 回答