我的代码有问题。所以,我想在Pygame创造一个游戏,香蕉从天而降,猴子必须抓住它们。我很难在这两者之间造成碰撞(花了几个小时尝试)。
所以,这是我的代码:
import pygame, sys, random, time, os
from pygame.locals import *
#Variáveis necessárias
banana_speed = 5
monkey_speed = 20
WIDTH = 800
HEIGHT = 800
pontos = 0
vidas = 3
#Nome do jogo
pygame.display.set_caption("Catch the fruit")
#Tamanho do ecrã do jogo
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load('monkey.png')
self.rect = self.image
self.x = 300
self.y = 640
def keyboard(self):
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
self.x += monkey_speed
elif key[pygame.K_LEFT]:
self.x -= monkey_speed
def draw (self, screen):
screen.blit(self.rect, (self.x, self.y))
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class Banana(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load('banana.png')
self.rect = self.image
self.x = random.randrange(0,WIDTH)
self.y = -50
def draw(self, screen):
self.y = self.y + banana_speed
screen.blit(self.rect,(self.x, self.y))
#Funções necessárias para o Loop
macaco = Macaco()
banana = Banana()
Background = Background('background.png', [0,0])
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
while vidas > 0:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
screen.blit(Background.image, Background.rect)
pressed_keys = pygame.key.get_pressed()
macaco.keyboard()
macaco.draw(screen)
banana.draw(screen)
pygame.display.update()
编辑: 所以我尝试了另一种解决方案并做到了这一点:
import pygame, sys, random, time, os
from pygame.locals import *
#Variáveis necessárias
banana_speed = 5
monkey_speed = 20
WIDTH = 800
HEIGHT = 800
pontos = 0
vidas = 3
green = (0, 0 , 255)
#Nome do jogo
pygame.display.set_caption("Catch the fruit")
#Tamanho do ecrã do jogo
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.image.load('monkey.png')
self.image = pygame.Surface([WIDTH, HEIGHT])
self.x = 300
self.y = 640
self.image.fill(green)
def keyboard(self):
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
self.x += monkey_speed
elif key[pygame.K_LEFT]:
self.x -= monkey_speed
def draw (self, screen):
screen.blit(self.rect, (self.x, self.y))
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class Banana(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.image.load('banana.png')
self.image = pygame.Surface([WIDTH, HEIGHT])
self.x = random.randrange(0, WIDTH)
self.y = -50
def draw(self, screen):
self.y = self.y + banana_speed
screen.blit(self.rect,(self.x, self.y))
#Funções necessárias para o Loop
macaco = Macaco()
banana = Banana()
Background = Background('background.png', [0,0])
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
while vidas > 0:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
screen.blit(Background.image, Background.rect)
pressed_keys = pygame.key.get_pressed()
macaco.keyboard()
macaco.draw(screen)
banana.draw(screen)
blocks_hit_list = pygame.sprite.spritecollide(macaco, banana, True)
for blocks in blocks_hit_list:
pontos +=1
pygame.display.update()
请你给我一些帮助吗?
答案 0 :(得分:0)
我创建了两个精灵组:all_sprites
,其中包含所有精灵,用于仅用两行代码更新和绘制它们,以及用于检查的bananas
组对于macaco和香蕉之间的碰撞。然后我们需要pygame.sprite.spritecollide
函数来获取碰撞的精灵。你必须传递一个精灵实例和一个精灵组,如果精灵与组中的精灵发生碰撞,它就会检查你。它将碰撞的香蕉作为列表返回,您可以通过该列表迭代以对其执行某些操作,或者例如增加点计数器。
你必须在sprite中调用父类的__init__
方法才能正确使用sprite组(使用super
函数super().__init__()
(在Python中) 2 super(Macaco, self).__init__()
)。
要更新精灵的位置,请将topleft
(或center
)属性设置为新的x,y坐标。
从图像调用self.rect = self.image.get_rect()
获取矩形。
import sys
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((190, 140, 20))
self.rect = self.image.get_rect()
self.x = 300
self.y = 640
self.speed = 20
def keyboard(self, keys):
if keys[pygame.K_RIGHT]:
self.x += self.speed
elif keys[pygame.K_LEFT]:
self.x -= self.speed
def update(self):
self.rect.topleft = self.x, self.y
class Banana(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((230, 230, 40))
self.rect = self.image.get_rect()
self.x = random.randrange(0, 770)
self.y = -50
self.speed = 5
def update(self):
self.y += self.speed
self.rect.topleft = self.x, self.y
macaco = Macaco()
banana = Banana()
all_sprites = pygame.sprite.Group(macaco, banana)
bananas = pygame.sprite.Group(banana)
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
keys = pygame.key.get_pressed()
macaco.keyboard(keys)
all_sprites.update()
# Collision detection. Check if macaco collided with bananas group,
# return collided bananas as a list. dokill argument is True, so
# that collided bananas will be deleted.
collided_bananas = pygame.sprite.spritecollide(macaco, bananas, True)
for collided_banana in collided_bananas:
print('Collision.')
screen.fill((70, 40, 70))
all_sprites.draw(screen)
pygame.display.update()
clock.tick(30)
pygame.quit()
sys.exit()