这是创建我的 Snake 基础的代码。
class Snake(object):
x_coordinate = 0
y_coordinate = 0
def __init__(self, x_coordinate, y_coordinate):
grid[x_coordinate][y_coordinate] = 1
Snake.x_coordinate = x_coordinate
Snake.y_coordinate = y_coordinate
print(Snake.x_coordinate)
print(Snake.y_coordinate)
@staticmethod
def move_snake(direction):
if direction == "UP":
old_x = Snake.x_coordinate
old_y = Snake.y_coordinate
grid[old_x][old_y] = 0
grid[old_x - 1][old_y] = 1
Snake.x_coordinate = old_x - 1
print("UP")
if direction == "DOWN":
old_x = Snake.x_coordinate
old_y = Snake.y_coordinate
grid[old_x][old_y] = 0
grid[old_x + 1][old_y] = 1
Snake.x_coordinate = old_x + 1
print("DOWN")
if direction == "LEFT":
old_x = Snake.x_coordinate
old_y = Snake.y_coordinate
grid[old_x][old_y] = 0
grid[old_x][old_y - 1] = 1
Snake.y_coordinate = old_y - 1
print("LEFT")
if direction == "RIGHT":
old_x = Snake.x_coordinate
old_y = Snake.y_coordinate
grid[old_x][old_y] = 0
grid[old_x][old_y + 1] = 1
Snake.y_coordinate = old_y + 1
print("RIGHT")
print("Your X and Y coordinates are {0} and {1}".format(Snake.x_coordinate, Snake.y_coordinate))
这是创建我需要获取的随机对象的代码。
class RandomObject(object):
x_coordinate = 0
y_coordinate = 0
def __init__(self):
x_coordinate = random.randint(1, 15)
y_coordinate = random.randint(1, 15)
grid[x_coordinate][y_coordinate] = 2
print("The items x and y coordinates are {0} and {1}".format(x_coordinate, y_coordinate))
我将它们声明为 Snake 和 random_item 变量。我也将其放入我的 pygame 事件函数中。
elif snake.x_coordinate == randomItem.x_coordinate and snake.y_coordinate == randomItem.y_coordinate:
print("You got the item.")
那么这里的问题是什么?它应该可以工作,因为当我将蛇移动到随机项目坐标时,它会打印出它们位于同一坐标但没有任何反应,该事件不会被触发。
您从未设置实例属性:
class RandomObject(object):
x_coordinate = 0
y_coordinate = 0
def __init__(self):
x_coordinate = random.randint(1, 15)
y_coordinate = random.randint(1, 15)
grid[x_coordinate][y_coordinate] = 2
print("The items x and y coordinates are {0} and {1}".format(x_coordinate, y_coordinate))
__init__
方法设置本地值,当函数退出时这些值会再次丢失。 RandomObject
实例没有设置属性,因此当您访问 randomItem
上的属性时,只能找到类属性(均设置为 0
) >.
将它们设置在实例上:
class RandomObject(object):
x_coordinate = 0
y_coordinate = 0
def __init__(self):
self.x_coordinate = random.randint(1, 15)
self.y_coordinate = random.randint(1, 15)
grid[self.x_coordinate][self.y_coordinate] = 2
print("The items x and y coordinates are {0} and {1}".format(self.x_coordinate, self.y_coordinate))
注意self.
引用。
我是一名优秀的程序员,十分优秀!