街机中的碰撞错误:当我在python中使用arcade.check_for_Collision方法时,发生了碰撞,它会给



我正在制作一个蛇游戏,当我想实现蛇与苹果的碰撞时,我遇到了以下错误。街机中的碰撞错误:当我在python中使用arcade.check_for_collision方法时,发生了碰撞,它会给出一个错误:

ValueError: Error trying to get the hit box of a sprite, when no hit box is set.
Please make sure the Sprite.texture is set to a texture before trying to draw or do collision testing.
Alternatively, manually call Sprite.set_hit_box with points for your hitbox.
import random, arcade
WIDTH_SCREEN = 500
HEIGHT_SCREEN = 500
class Game(arcade.Window):
def __init__(self):
super().__init__(width=WIDTH_SCREEN, height=HEIGHT_SCREEN, title='Snake')
arcade.set_background_color(arcade.color.SAND)
self.snake = Snake()
self.apple = Apple()
def on_draw(self):
arcade.start_render()
self.snake.draw()
self.apple.draw_apple()
def on_update(self, delta_time: float):
self.snake.move()
***if arcade.check_for_collision(self.snake, self.apple):***
self.snake.eat()
self.apple = Apple()
print(self.snake.score)
def on_key_release(self, key: int, modifiers: int):
if key == arcade.key.LEFT:
self.snake.change_x = -1
self.snake.change_y = 0
elif key == arcade.key.RIGHT:
self.snake.change_x = 1
self.snake.change_y = 0
elif key == arcade.key.UP:
self.snake.change_x = 0
self.snake.change_y = 1
elif key == arcade.key.DOWN:
self.snake.change_x = 0
self.snake.change_y = -1         
class Snake(arcade.Sprite):
def __init__(self):
super().__init__()
self.width = 16
self.height = 16
self.change_x = 0   
self.change_y = 0
self.center_x = WIDTH_SCREEN // 2
self.center_y = HEIGHT_SCREEN //2
self.color = arcade.color.RED
self.score = 0
self.speed = 1
def move(self):
if self.change_x > 0:
self.center_x += self.speed
elif self.change_x < 0:
self.center_x -= self.speed
elif self.change_y > 0:
self.center_y += self.speed
elif self.change_y < 0:
self.center_y -= self.speed      
def eat(self):
self.score += 1
def draw(self):
arcade.draw_rectangle_filled(self.center_x, self.center_y, self.width, self.height, self.color)      
class Apple(arcade.Sprite):
def __init__(self):
super().__init__()
self.radius = 10
self.center_x = random.randint(0, WIDTH_SCREEN)
self.center_y = random.randint(0, HEIGHT_SCREEN)
self.color = arcade.color.YELLOW
def draw_apple(self):
arcade.draw_circle_filled(self.center_x, self.center_y, self.radius, self.color)
game_board = Game()
arcade.run()

您也应该为Apple类设置widthheight属性。

class Apple(arcade.Sprite):
def __init__(self):
super().__init__()
self.radius = 10
self.center_x = random.randint(0, WIDTH_SCREEN)
self.center_y = random.randint(0, HEIGHT_SCREEN)
self.color = arcade.color.YELLOW
self.width = 20
self.height = 20

'打印(self.snake.score('不是在运行的街机窗口中显示分数的正确方式。街机有一种内置的方法";arcade.draw_text(("。此外,这个方法可能不会在更新中调用,但您应该在绘图中调用它。

最新更新