【问题标题】:Pygame snake game attribute error when trying to draw characters尝试绘制角色时Pygame蛇游戏属性错误
【发布时间】:2020-05-05 11:56:01
【问题描述】:

第 134 行我收到一个属性错误,我对 pygame 还很陌生,所以我相信这与我的论点有关,但我不确定。这是错误所在的行:

pygame.draw.rect(window.pygame.Color("RED"), pygame.Rect(int(foodpos[0]), int(foodpos[1]), 10, 10))

确切的错误是:

AttributeError: 'pygame.Surface' object has no attribute 'pygame'. 
Traceback (most recent call last):
  File "C:\Program Files (x86)\Thonny\lib\site-packages\thonny\backend.py", line 1744, in _trace
    return self._trace_and_catch(frame, event, arg)
  File "C:\Program Files (x86)\Thonny\lib\site-packages\thonny\backend.py", line 1819, in _trace_and_catch
    assert last_custom_frame.event.startswith("before_")
AssertionError
Traceback (most recent call last):
  File "D:\CS 20 School Projects\Daily Work.py", line 134, in <module>
    pygame.draw.rect(window.pygame.Color("RED"), pygame.Rect(int(foodpos[0]), int(foodpos[1]), 10, 10))
AttributeError: 'pygame.Surface' object has no attribute 'pygame'"""
import pygame, sys, random, time

BLACK = (0, 0, 0)
WHITE = (225, 225, 225)
BLUE = (0, 0, 225)
RED = (225, 0, 0)


class Snake(object):
    def __init__(self):
        self.position = [100, 50]  # sets initial position of the snake
        self.body = [[100, 50], [90, 50], [80, 50]]  # sets initial length of the snakes body to 3 segments
        self.direction = "RIGHT"
        self.change_direction_to = self.direction

    # ---------------------------- Makes it possible to change directions but you cannot go directly backwards
    def change_direction_to(self, dir):
        if dir == "RIGHT" and not self.direction == "LEFT":
            self.direction = "RIGHT"
        elif dir == "LEFT" and not self.direction == "RIGHT":
            self.direction = "LEFT"
        elif dir == "UP" and not self.direction == "DOWN":
            self.direction = "UP"
        elif dir == "DOWN" and not self.direction == "UP":
            self.direction = "DOWN"

    # ----------------------------

    # -------------------------------- Sets the speed of the snake
    def move(self):
        if self.direction == "RIGHT":
            self.position[0] += 10
        if self.direction == "LEFT":
            self.position[0] -= 10
        if self.direction == "UP":
            self.position[0] += 10
        if self.direction == "DOWN":
            self.position[0] -= 10
        # ---------------------------------

        # ----------------------------- Checks if snake has ate food
        self.body.insert(0, list(self.position))
        if self.position == foodpos:
            return 1
        else:
            self.body.pop()
            return 0

    # -----------------------------

    # ---------------------------------checks if snake has hit a wall
    def check_collision(self):
        if self.position[0] > 490 or self.position < 0:
            return 1
        elif self.position[1] > 490 or self.position < 0:
            return 1
        # ----------------------------------

        # ---------------------------checks if snake has hit itself
        for body_part in self.body[1:]:
            if self.position == body_part:
                return 1
        return 0

    # ---------------------------

    def get_head_position(self):
        return self.position

    def get_body(self):
        return self.body


class FoodSpawner:

    def __init__(self):
        self.position = [random.randrange(1, 50) * 10], [random.randrange(1, 50) * 10]
        self.is_food_on_screen = True

    def spawn_food(self):
        if not self.is_food_on_screen:
            self.position = [random.randrange(1, 50) * 10], [random.randrange(1, 50) * 10]
            self.is_food_on_screen = True
        return self.position

    def set_food_on_screen(self, b):
        self.is_food_on_sceen = b


window = pygame.display.set_mode((700, 600))
pygame.display.set_caption("Definitely Not Snake")
fps = pygame.time.Clock()

score = 0

snake = Snake()
food_spawner = FoodSpawner()


def game_over():
    pygame.quit()
    sys.exit()


while True:
    for event in pygame.event.get():

        # ------------------------- quits the game
        if event.type == pygame.QUIT:
            game_over()
        # -------------------------

        # ------------------------- movement of the snake
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                snake.change_dir_to("RIGHT")
            if event.key == pygame.K_LEFT:
                snake.change_dir_to("LEFT")
            if event.key == pygame.K_RIGHT:
                snake.change_dir_to("UP")
            if event.key == pygame.K_RIGHT:
                snake.change_dir_to("DOWN")
    # -------------------------

    # ----------------------------- adds to score if the snake eats the food
    foodpos = food_spawner.spawn_food()
    if snake.move(foodpos) == 1:
        score += 1
        food_spawner.set_food_on_screen(False)
    # ------------------------------

    # ------------------------------ draws the screen, the snake, and its food
    window.fill(pygame.Color("BLACK"))
    for pos in snake.get_body():
        pygame.draw.rect(window, pygame.Color("BLUE"), pygame.Rect(pos[0], pos[1], 10, 10))
    pygame.draw.rect(window.pygame.Color("RED"), pygame.Rect(int(foodpos[0]), int(foodpos[1]), 10, 10))
    # ------------------------------

    if snake.check_collision() == 1:
        game_over()
    pygme.display.set_caption("Definitely not Snake | Score : " + str(score))
    pygame.display.flip()
    fps.tick(24)

【问题讨论】:

  • pygame.draw.rect(window, pygame.Color("RED") 中的window 之后需要comma 而不是dot。 (而不是pygame.draw.rect(window.pygame.Color("RED")
  • self.position = [random.randrange(1, 50) * 10], [random.randrange(1, 50) * 10] 必须是 self.position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10] 第一个是一个元组,其中每个元素都是一个列表 ([x], [y]) 第二个是一个包含 2 个元素的列表 [x, y]

标签: python pygame attributeerror


【解决方案1】:

spawn_food方法中

self.position = [random.randrange(1, 50) * 10], [random.randrange(1, 50) * 10]

必须是

self.position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]

第一个是一个元组,其中每个元素都是一个列表([x], [y]),第二个是一个包含 2 个元素的列表[x, y]

注意,spawn_food 返回 self.position 并将返回值分配给 foodpos

foodpos = food_spawner.spawn_food()

由于foodpos 是一个包含具有 1 个元素 (([x], [y])) 的列表的元组,因此会导致错误

pygame.Rect(int(foodpos[0]), int(foodpos[1]), 10, 10)

【讨论】:

    【解决方案2】:
        for pos in snake.get_body():
            pygame.draw.rect(window,pygame.Color("BLUE"),pygame.Rect(pos[0],pos[1],10,10))
                                   ^
        pygame.draw.rect(window.pygame.Color("RED"), pygame.Rect(int(foodpos[0]), int(foodpos[1]), 10, 10))
                               ^
    

    我相信有一个错字。由于您的蓝色绘图没有错误,因此应该是“window.pygame”错误。

    【讨论】:

    • 这是正确的 - 哎呀。但是当我修复它时,我只是在该行上得到一个错误: AttributeError: 'pygame.Surface' object has no attribute 'pygame' Daily Work.py, line 133
    • 又是同样的错误?检查pygame 在您的代码中出现的位置,并确保在这些位置之前不再有拼写错误。
    • 同样的错误(我看不到拼写错误。)..这就是它所说的和寻找的建议.. .AttributeError:'pygame.Surface'对象没有属性'pygame' Daily Work.py,第 133 行您的程序尝试访问类型为“pygame.Surface”的对象的属性 pygame,但此类型没有此类属性。你拼错名字了吗?不要忘记字母的大小写也很重要!你期待另一种类型吗?
    • 它在你画蓝色矩形的那一行吗?您是否意外更改了正确的行?
    • """认为解决了以前的问题 - 我认为我的矩形参数有问题 - 我得到错误的部分代码如下所示:(上面完整代码的第 134 行)TypeError : 参数必须是 rect 样式对象 Daily Work.py,第 134 行 Python 被要求对不支持它的对象进行操作。""" window.fill(pygame.Color("BLACK")) for pos in snake.get_body(): pygame.draw.rect(window,pygame.Color(0,225,0),pygame.Rect(pos[0],pos[1],10,10)) pygame.draw.rect(window, pygame.Color(225,0,0),pygame.Rect(foodpos[0],foodpos[1],10,10))
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多