1
В настоящее время я работаю над простым pygame, у которого есть кролик и конфеты, падающие на экран, если кролик касается конфеты, конфеты исчезают. Но обнаружение столкновения не работает. Когда я бегу, я получаю следующее сообщение об ошибке:Ошибка обнаружения столкновений Pygame, Sprites
Traceback (most recent call last):
File "C:\mashi.py", line 79, in <module>
candy.checkCollision(bunny.image_b, candy.image_b)
TypeError: checkCollision() takes exactly 2 arguments (3 given)
Вот мой код:
import pygame
import os, sys
import random
import time
pygame.display.set_caption("Mashimaro Game")
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('mashimaro.png')
img_path2 = os.path.join('candy.png')
background_image = pygame.image.load('food.png')
class Bunny(object): # represents the bunny, not the game
def __init__(self):
""" The constructor of the class """
self.image_s = pygame.image.load(img_path)
self.image_b = self.image_s.get_rect()
# the bunny's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 5 # distance moved in 5 frame
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
class Candy(object):
def __init__(self, x=640, y=0):
self.image_s = pygame.image.load(img_path2)
self.image_b = self.image_s.get_rect()
self.x = x
self.y = y
dist = 10
self.dist = dist
def candy(self):
dist = 10
self.x -=dist
def candy_draw(self, surface):
surface.blit(self.image, (self.x, self.y))
def checkCollision(sprite1, sprite2):
col = pygame.sprite.spritecollide(sprite1, sprite2)
if col == True:
sys.exit()
return col
pygame.init()
screen = pygame.display.set_mode((640, 400))
bunny = Bunny() # create an instance
candy = Candy()
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
if candy.x < 0:
y = random.randint(10, 190)
candy = Candy(640, y)
candy.checkCollision(bunny.image_b, candy.image_b)
bunny.handle_keys() # handle the keys
candy.candy()
screen.blit(background_image,[0,0]) # fill the screen with background
bunny.draw(screen) # draw the bunny to the screen
rock.rock_draw(screen)
pygame.display.update() # update the screen
clock.tick(120)
Что я делал неправильно?
Спасибо за отзыв! – Luluyun
Итак, я добавил в себя, и теперь это дает мне: Traceback (последний последний звонок): Файл «C: \ mashi.py», строка 79, в candy.checkCollision (bunny.image_b, candy.image_b) Файл «C: \ mashi.py», строка 56, в checkCollision col = pygame.sprite.spritecollide (sprite1, sprite2) ТипError: spritecollide() принимает не менее 3 аргументов (2 данных). Поэтому я изменил код на: col = pygame.sprite.spritecollide (self, sprite1, sprite2) –
Luluyun
Но тогда он дает мне новую ошибку: Traceback (последний последний звонок): Файл «C: \ mashi.py», линии 79, в candy.checkCollision (bunny.image_b, candy.image_b) Файл "C: \ mashi.py", строка 56, в checkCollision Col = pygame.sprite.spritecollide (само, sprite1, sprite2) Файл «C: \ Python27 \ lib \ site-packages \ pygame \ sprite.py», строка 1513, в spritecollide spritecollide = sprite.rect.colliderect AttributeError: объект «Candy» не имеет атрибута «rect» –
Luluyun