如果两个图像发生碰撞,我如何进行Pygame检查?

时间:2017-10-19 03:02:14

标签: python pygame

我已经尝试了所有方法,无法判断我的两个方块是否发生了碰撞。

这是我的代码:

import pygame
import random
pygame.init()

display_width = 600
display_height = 300

class player:#Just info for player
    width = 30
    height = 30
    x = display_width // 2
    y = display_height - height - 5
    a = x + 30
    pic = 'SnakePart.png'
    thing = pygame.image.load(pic)
    def place(x,y):#function for placing player object
        gameDisplay.blit(player.thing, (player.x,player.y))
class enemy:#enemy info class
    width = 30
    height = 30
    x = random.randint(0,display_width - width)
    y = 1
    a = x + 30
    pic = 'Apple.png'
    thing = pygame.image.load(pic)
    speed = 10#sets speed
    def change_x():
        enemy.x = random.randint(0,display_width - enemy.width)
    def change_y():
        enemy.y += enemy.speed
    def make(x,y):#set up funtion
        gameDisplay.blit(enemy.thing, (x,y))
    def respawn():#reseting enemy entity
        enemy.y = 1
        gameDisplay.blit(enemy.thing, (enemy.x,enemy.y))
player.thing#uses the variables in the classes to set up the images for use
enemy.thing

black = (0,0,0)
white = (255,255,255)


player_height = 30
player_width = 30

clock = pygame.time.Clock()

x_change = 0#This is to make movment

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Bullet Hell.')

dodged = 0#counter will be used in the more polished vesion.

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:#Checks for keypress, to make player entity move
            if event.key == pygame.K_RIGHT:
                x_change = 5
            if event.key == pygame.K_LEFT:
                x_change = -5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT or pygame.K_LEFT:
                x_change = 0

    player.x += x_change
    gameDisplay.fill(black)
    enemy.make(enemy.x,enemy.y)
    player.place(player.x,player.y)
    enemy.change_y()
    if enemy.y > display_height:#Brings enemy back to top once it has gotten to th bottom
        enemy.change_x()
        dodged += 1
        enemy.respawn()
    pygame.display.update()
    clock.tick(60)

这真的是碰撞,我觉得我会很好。哦,是的,如果你们也能告诉我如何显示那些很棒的文字!

1 个答案:

答案 0 :(得分:0)

查看pygame.Rect类及其碰撞检测方法。通过调用图像/曲面的 695050 nanoseconds spent acquiring 1 JDBC connections; 46807 nanoseconds spent releasing 1 JDBC connections; **1009874 nanoseconds spent preparing 3 JDBC statements;** 351373 nanoseconds spent executing 3 JDBC statements; 0 nanoseconds spent executing 0 JDBC batches; 0 nanoseconds spent performing 0 L2C puts; 0 nanoseconds spent performing 0 L2C hits; 0 nanoseconds spent performing 0 L2C misses; 21867159 nanoseconds spent executing 1 flushes (flushing a total of 440 entities and 16 collections); 9618 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections) 方法,将对象作为属性赋予。每帧更新这些rects的坐标,并在主循环中调用.get_rect()以检查两个rects是否发生碰撞。

player.rect.colliderect(enemy.rect)

我已经改变了更多的东西(顺便说一下,更好地调用图片import pygame import random pygame.init() BLACK = pygame.Color('black') display = pygame.display.set_mode((600, 300)) # Create a rect with the dimensions of the screen at coords (0, 0). display_rect = display.get_rect() clock = pygame.time.Clock() # SNAKE_IMAGE = pygame.image.load('SnakePart.png').convert_alpha() # APPLE_IMAGE = pygame.image.load('Apple.png').convert_alpha() # Replacement images. SNAKE_IMAGE = pygame.Surface((30, 30)) SNAKE_IMAGE.fill((30, 150, 0)) APPLE_IMAGE = pygame.Surface((30, 30)) APPLE_IMAGE.fill((150, 30, 0)) class Player: def __init__(self): self.x = display_rect.w // 2 self.y = display_rect.h - 30 - 5 self.image = SNAKE_IMAGE # Create a rect with the size of the image at coords (0, 0). self.rect = self.image.get_rect() # Set the topleft coords of the rect. self.rect.x = self.x self.rect.y = self.y self.x_change = 0 def update(self): """Move the player.""" self.x += self.x_change # Always update the rect, because it's # needed for the collision detection. self.rect.x = self.x def draw(self, display): display.blit(self.image, self.rect) class Enemy: def __init__(self): self.x = random.randint(0, display_rect.w - 30) self.y = 1 self.image = APPLE_IMAGE # You can also pass the coords directly to `get_rect`. self.rect = self.image.get_rect(topleft=(self.x, self.y)) self.speed = 10 def change_x(self): self.x = random.randint(0, display_rect.w - self.rect.w) self.rect.x = self.x def change_y(self): self.y += self.speed self.rect.y = self.y def draw(self, display): display.blit(self.image, self.rect) def reset(self): """Reset self.y position.""" self.y = -30 player = Player() enemy = Enemy() dodged = 0 done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: player.x_change = 5 if event.key == pygame.K_LEFT: player.x_change = -5 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or pygame.K_LEFT: player.x_change = 0 # Game logic. player.update() enemy.change_y() # Brings enemy back to top once it has gotten to th bottom if enemy.y > display_rect.h: enemy.change_x() dodged += 1 enemy.reset() # Check if the player and the rect collide. if player.rect.colliderect(enemy.rect): print('Collided!') # Draw everything. display.fill(BLACK) enemy.draw(display) player.draw(display) pygame.display.update() clock.tick(60) pygame.quit() 而不是self.image;)),特别是在课程中:

类的属性应该在thing方法中,以使它们成为实例属性而不是类属性(由所有实例共享)。另外,请查看如何创建类的实例。

这些方法都应该有__init__作为第一个参数(这是对实例的引用)。要访问类中的属性,请使用self作为前缀,例如self

self.x += self.x_change行更适合player.x += x_change类' Player方法,因此您只需调用update即可更新位置和其他玩家属性。

有一个约定,类名应该是大写的player.update(),而实例应该有小写的名字MyClass