为什么我的碰撞检测或掉落的图像不起作用?

时间:2019-04-20 22:41:40

标签: python pygame collision-detection rect

我最近编写了这段代码,其中水果和其他东西从屏幕顶部掉落,而底部的青蛙必须设法抓住它们。碰撞检测不起作用,下落的图像似乎也掉落并卡在屏幕顶部,下落的图像也不起作用。这是我的大部分代码,因为我似乎无法找出实际错误所在的区域:

import pygame, sys, time, random
from pygame.locals import *
######### constants ##########
jumpvel=20
fallingspeed=0.5
running= True
blue= [129,183 ,253]
pink=[255,174,201]
textcolour= [255,255,255]
x=700//2
y=1000//2

score=0

#### fruits and naughty ######
thingylist= ['fruit1.bmp','fruit2.bmp','fruit3.bmp','fruit4.bmp','fruit5.bmp','fruit1.bmp','fruit2.bmp','fruit3.bmp','fruit4.bmp','fruit5.bmp','naughty1.bmp','naughty2.bmp','naughty3.bmp',]
all_things=[]
for i in range (12):
    new_thing_image=pygame.image.load(thingylist[(random.randrange(0,12))])
    new_thing_image.set_colorkey(pink)
    new_thing_rect=new_thing_image.get_rect()
    new_thing_rect.x=random.randrange(0,950)
    new_thing_rect.y=-random.randrange(50,500)
    all_things.append([new_thing_image,new_thing_rect])


################collision###############
def checkCollision (frog_rect,all_things,score):
    collides_with=None
    for i in range (len(all_things)):
        thing_rect=all_things[i][1]
        if (frog_rect.colliderect(thing_rect)):
            score=score+100
    return collides_with



######## initialising screen#########        
pygame.init()
gamedisplay=pygame.display.set_mode((1000,600)) #making the screen
pygame.display.set_caption('frog')
clock=pygame.time.Clock()# frames per second
bg=pygame.image.load('actual clouds.bmp').convert()


############ initialising sprites##############
frog= pygame.image.load('actual frog.bmp')
frog.set_colorkey(blue)
frog_rect=frog.get_rect()
frog_rect.centerx=(x)
frog_rect.centery=(y)


####### score###########
pygame.font.init()
font= pygame.font.SysFont ('Dubai MS', 48)

##########drawing things#############
def drawThings (all_things):
    for item in all_things:
        new_thing_image, new_thing_rect= item
        gamedisplay.blit(new_thing_image, (new_thing_rect.x, new_thing_rect.y))



#########update display function###########
def update(x,y,all_things,score):
    gamedisplay.blit(bg,[0,0])
    gamedisplay.blit(frog,(x,y))
    for thing in range (len(all_things)):
        new_thing_rect=all_things[i][1]
        #thing_rect.y=thing_rect.y+fallingspeed
        new_thing_rect.y+= fallingspeed
    drawThings(all_things)
    label=font.render("score "+ str(score) ,1,textcolour)
    gamedisplay.blit(label,(750,10))
    pygame.display.update()
    pygame.time.delay(50)



#########main game loop ############
while running == True:
    gamedisplay.blit(bg,[0,0])
    gamedisplay.blit(frog,(x,y))
    drawThings(all_things)
    label=font.render("score "+ str(score) ,1,textcolour)
    gamedisplay.blit(label,(750,10))
    pygame.display.flip()
    pygame.event.pump()
    key=pygame.key.get_pressed()

    ########### escape ###########
    if key [pygame.K_ESCAPE]:
        sys.exit()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    ########### controls ##############        
    if key[pygame.K_LEFT]:
        x -=2

    elif key[pygame.K_RIGHT]:
        x +=2

    elif key[pygame.K_SPACE]or key[pygame.K_UP]:
        for i in range (5):
            y -= jumpvel
            update(x,y,all_things,score)
        for i in range (5):
            y += jumpvel
            update(x,y,all_things,score)
    ######## limits ####################
    if x < 10:
        x = 10
    elif (x > (900 - 2)):
        x= 900-2

    ######### falling###########

    for item in all_things:
        new_thing_image, new_thing_rect= item
        #new_thing_rect=all_things[i][1]
        #thing_rect.y=thing_rect.y+fallingspeed
        new_thing_rect.y+= fallingspeed

    ############collision detection##########
    detect=checkCollision (frog_rect, all_things,score)
    if (detect !=None):
        score=score+100

update(x,y,all_things,score)

“事物”是指落入屏幕的底部,以便青蛙抓住,但它们似乎都陷在顶部。当我测试用于碰撞检测的代码时,即使两个图像发生碰撞,它也对得分没有影响-表示某些功能无效。

1 个答案:

答案 0 :(得分:0)

下降的图像因此而停止

fallingspeed = 0.5

rect使用整数值保持正数,因此它将0.5变成整数-int(0.5) == 0

当您拥有y = 0并添加0.5时-因此可以预期y = 0.5-会将其四舍五入为y = 0。在下一个循环中,您将再次添加0.5并将其再次舍入到y = 0。这样,它会在y = 0

处停止

当您拥有y = -5并添加0.5时,您可能会想到-4.5但它四舍五入到-4(不是-5),所以它在移动

使用

fallingspeed = 1

它不会在y = 0

处停止
old_y = 0
new_y = int(old_y+0.5)
print(old_y, new_y) 

# 0 0

old_y = -5
new_y = int(old_y+0.5)
print(old_y, new_y) 

# -5 -4

有时在更复杂的代码中,保持位置在浮点值中很重要,然后您必须使用float变量而不是rect来保持正位置并将其仅复制到rect当您需要绘制或检查碰撞时


碰撞

checkCollision内部,您设置了collides_with = None,但从未将其更改为`True

 def checkCollision (frog_rect,all_things, score):
     collides_with = None

     for i in range (len(all_things)):
         thing_rect = all_things[i][1]
         if (frog_rect.colliderect(thing_rect)):
              score=score+100
              collides_with = True

     return collides_with

您可以写短些

 def checkCollision(frog_rect,all_things, score):
     collides_with = None

     for thing_image, thing_rect in all_things:
         if frog_rect.colliderect(thing_rect):
              score = score+100
              collides_with = True

     return collides_with

现在应该更改score

detect = checkCollision(frog_rect, all_things, score)
if detect:
    score = score+100

但是,如果要在checkCollision内进行更改,则必须返回值scorescore中的变量checkCollision是局部变量,它不会更改全局变量score

中的值
 def checkCollision(frog_rect,all_things, score):
     collides_with = None

     for thing_image, thing_rect in all_things:
         if frog_rect.colliderect(thing_rect):
              score = score+100
              collides_with = True

     return collides_with, score

然后您必须使用全局score

detect, score = checkCollision(frog_rect, all_things, score)