在Pygame中碰撞图像

时间:2018-06-20 18:23:53

标签: python pygame collision

im正在尝试检查两个图像是否发生冲突,但是我只是找回一条错误消息说  “'pygame.Surface'对象没有属性'colliderect'”。图像是电池和playerPic,我进行了定义以查看它们是否发生碰撞。如果它们发生碰撞,它将返回黑屏。 注意:我从这里的代码中删除了drawScene

#initialize pygame
from pygame import * 
import os
import random
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 0)
init()
#set screen size
size = width, height = 800, 600
screen = display.set_mode(size)
#set fonts
fontGame=font.SysFont("Times New Roman", 30)
fontBack=font.SysFont("Ariel", 30)
fontTitle=font.SysFont("Ariel", 100)
fontResearch=font.SysFont ("Times New Roman", 18)
#set button and page to 0
button = 0
page=0



#setting colours
BLACK = (0, 0, 0)
RED = (255,0,0)
GREEN = (0, 255, 0)
BLUE = (106,186,232)
#loading image
backgroundPic=image.load("Background.jpg")
backgroundGame=image.load("gameBackground.jpg")
backgroundGame=transform.scale(backgroundGame,(800,600))
battery=image.load("Battery.png")
battery=transform.scale(battery,(100,100))

backgroundx=0
playerPic=image.load("player.png")
playerPic=transform.scale(playerPic,(70,70))

batteryx=[]


#defining what is going to be shown on the screen
def drawScene(screen, button,page,locationx,locationy): 
    global batteryx
    mx, my = mouse.get_pos() #will get where the mouse is
    #if the user does nothing
    if page==0:
        draw.rect(screen, BLACK, (0,0, width, height))

        screen.fill(BLACK)
        rel_backgroundx= backgroundx % backgroundGame.get_rect().width
        screen.blit(backgroundGame, (rel_backgroundx - backgroundGame.get_rect().width,0))
        if rel_backgroundx < width:
            screen.blit (backgroundGame, (rel_backgroundx,0))
        screen.blit(playerPic,(locationx,locationy))


        screen.blit(battery,(batteryx,420))                
        batteryx-=1               

    display.flip()
    return page
def collision (battery, playerPic):
    if battery.colliderect(playerPic):
        return True
    return False
running = True
myClock = time.Clock()

KEY_LEFT= False
KEY_RIGHT= False
KEY_UP= False
KEY_DOWN= False
locationx=0
jumping=False
accel=20
onGround= height-150
locationy=onGround

batteryx=random.randrange(50,width,10)  

# Game Loop
while running:
    button=0
    print (KEY_LEFT, KEY_RIGHT)
    for evnt in event.get():             # checks all events that happen
        if evnt.type == QUIT:
            running=False
        if evnt.type == MOUSEBUTTONDOWN:
            mx,my=evnt.pos
            button = evnt.button
        if evnt.type== KEYDOWN:
            if evnt.key==K_LEFT:
                KEY_LEFT= True
                KEY_RIGHT= False
            if evnt.key==K_RIGHT:
                KEY_RIGHT= True
                KEY_LEFT= False
            if evnt.key==K_UP and jumping==False:
                jumping=True 
                accel=20
            if evnt.key== K_DOWN:
                KEY_DOWN= True
                KEY_UP= False 
        if evnt.type==KEYUP:
            if evnt.key==K_LEFT:
                KEY_LEFT= False
            if evnt.key==K_RIGHT:
                KEY_RIGHT= False
            if evnt.key==K_DOWN:
                KEY_DOWN=False

    if KEY_LEFT== True:
        locationx-=10
        backgroundx+=10
    if KEY_RIGHT== True:
        locationx+=10
        backgroundx-=10
    if jumping==True:
        locationy-=accel
        accel-=1
        if locationy>=onGround:
            jumping=False
            locationy=onGround

    #player cannot move off screen
    if locationx<0:
        locationx=0
    if locationx>400:
        locationx=400
    if collision(battery, playerPic)==True:
        screen.fill(BLACK)

    page=drawScene(screen,button,page,locationx,locationy)
    myClock.tick(60)  # waits long enough to have 60 fps
    if page==6:  #if last button is clicked program closes
        running=False

quit()

1 个答案:

答案 0 :(得分:0)

Images / pygame。表面不能用于碰撞检测。您必须为电池和播放器创建pygame.Rect个对象,然后使用它们的colliderect方法。您可以使用表面的get_rect方法来获取矩形的大小,然后在每次移动播放器或电池时更新其位置。

# Create a rect with the size of the playerPic with
# the topleft coordinates (0, 0).
player_rect = playerPic.get_rect()

在while循环中:

# Adjust the position of the rect.
player_rect.x = locationx
player_rect.y = locationy
# You can also assign the location variables to the topleft attribute.
player_rect.topleft = (locationx, locationy)

# Then pass the battery_rect and player_rect to the collision function.
if collision(battery_rect, player_rect):

您还可以缩短collision函数:

def collision(battery_rect, player_rect):
    return battery_rect.colliderect(player_rect)

或者在while循环中调用battery_rect.colliderect(player_rect)

这是一个最小的完整示例:

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

player_image = pg.Surface((30, 50))
player_image.fill(pg.Color('dodgerblue1'))
battery_image = pg.Surface((30, 50))
battery_image.fill(pg.Color('sienna1'))

speed_x = 0
location_x = 100
# Define the rects.
# You can pass the topleft position to `get_rect` as well.
player_rect = player_image.get_rect(topleft=(location_x, 100))
battery_rect = battery_image.get_rect(topleft=(200, 100))

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_a:
                speed_x = -4
            elif event.key == pg.K_d:
                speed_x = 4

    # Update the location and the player_rect.
    location_x += speed_x
    player_rect.x = location_x

    if player_rect.colliderect(battery_rect):
        print('collision')

    # Blit everything.
    screen.fill(BG_COLOR)
    screen.blit(player_image, player_rect)
    screen.blit(battery_image, battery_rect)
    pg.display.flip()
    clock.tick(30)

pg.quit()
相关问题