gpt4 book ai didi

python - 如何在 Pygame 中使用 Sprite Collide

转载 作者:行者123 更新时间:2023-11-28 19:49:40 25 4
gpt4 key购买 nike

我正在制作一个非常简单的游戏,小鸟(玩家)必须躲避岩石,如果它被岩石击中,你就输了。我正在尝试使用 pygame.sprite.collide_rect() 来判断它们是否接触过,但我似乎无法弄清楚如何正确使用它。

这是我的代码:

import pygame
import os, sys
import random
import time

img_path = os.path.join('C:\Python27', 'player.png')
img_path2 = os.path.join('C:\Python27', 'rock.png')

class Bird(object):
def __init__(self):
self.image_s = pygame.image.load(img_path)
self.image_b = self.image_s.get_rect()
self.x = 0
self.y = 0

def handle_keys(self):
key = pygame.key.get_pressed()
dist = 2
if key[pygame.K_DOWN]:
self.y += dist
elif key[pygame.K_UP]:
self.y -= dist
if key[pygame.K_RIGHT]:
self.x += dist
elif key[pygame.K_LEFT]:
self.x -= dist

def draw(self, surface):
surface.blit(self.image, (self.x, self.y))

def background(self, surface):
bg = os.path.join('C:\Python27', 'bg.png')
self.image2 = pygame.image.load(bg)
surface.blit(self.image2, (0,0))

class Rock(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 rock(self):
dist = 10
self.x -=dist

def rock_draw(self, surface):
surface.blit(self.image, (self.x, self.y))

def checkCollision(sprite1, sprite2):
col = pygame.sprite.collide_rect(sprite1, sprite2)
if col == True:
sys.exit()

pygame.init()
screen = pygame.display.set_mode((640, 200))

bird = Bird()
rock = Rock()
clock = pygame.time.Clock()


running = True
while running:

for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False

if rock.x < 0:
y = random.randint(10, 190)
rock = Rock(640, y)
rock.checkCollision(bird.image_b, rock.image_b)

bird.handle_keys()
rock.rock()

screen.fill((255,255,255))
bird.background(screen)
bird.draw(screen)
rock.rock_draw(screen)
pygame.display.update()

clock.tick(40)

当我尝试运行它时,它告诉我它只需要 2 个参数,当我尝试修复时我给出了三个参数,但我收到了各种不同的错误消息。

最佳答案

def checkCollision(sprite1, sprite2):
col = pygame.sprite.collide_rect(sprite1, sprite2)
if col == True:
sys.exit()

应该是

def checkCollision(self, sprite1, sprite2):
col = pygame.sprite.collide_rect(sprite1, sprite2)
if col == True:
sys.exit()

因为它是绑定(bind)到对象的方法。

关于python - 如何在 Pygame 中使用 Sprite Collide,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16227616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com