Как бы я обнаружил столкновение между движущимся изображением в нижней части экрана и падающими объектами без использования спрайтов? - PullRequest
1 голос
/ 15 апреля 2019

Я кодировал этот код, когда с верхней части экрана падают различные объекты, а лягушка внизу должна попытаться поймать их.Кажется, я не могу выполнить обнаружение столкновений с лягушкой и падающими объектами, следуя каким-либо учебным пособиям, так как я не использую спрайты и по какой-то причине прямоугольные функции тоже не работают.Я понятия не имею, как это сделать, поскольку учебник не работает.Любая помощь приветствуется!

import pygame, sys, time, random
from pygame.locals import *

fx1=random.randrange(0,300)
fx2=random.randrange(350,650)
fx3=random.randrange(700,950)
fy1=-50
fy2=-100
fy3=--200
fy1a=-300
fy2a=-400
fy3a=-500
#### fruits######
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',]
thing1=pygame.image.load(thingylist[(random.randrange(0,12))])
thing1.set_colorkey(pink)
thing1_rect=thing1.get_rect()
thing1_rect.centerx=(fx1)
thing1_rect.centery=(fy1)
thing2=pygame.image.load(thingylist[(random.randrange(0,12))])
thing2.set_colorkey(pink)
thing2_rect=thing2.get_rect()
thing2_rect.centerx=(fx2)
thing2_rect.centery=(fy2)
thing3=pygame.image.load(thingylist[(random.randrange(0,12))])
thing3.set_colorkey(pink)
thing3_rect=thing3.get_rect()
thing3_rect.centerx=(fx3)
thing3_rect.centery=(fy3)

fx1a=random.randrange(0,300)
fx2a=random.randrange(350,650)
fx3a=random.randrange(700,950)
thing4=pygame.image.load(thingylist[(random.randrange(0,12))])
thing4.set_colorkey(pink)
thing4_rect=thing4.get_rect()
thing4_rect.centerx=(fx1a)
thing4_rect.centery=(fy1a)
thing5=pygame.image.load(thingylist[(random.randrange(0,12))])
thing5.set_colorkey(pink)
thing5_rect=thing5.get_rect()
thing5_rect.centerx=(fx2a)
thing5_rect.centery=(fy2a)
thing6=pygame.image.load(thingylist[(random.randrange(0,12))])
thing6.set_colorkey(pink)
thing6_rect=thing6.get_rect()
thing6_rect.centerx=(fx3a)
thing6_rect.centery=(fy3a)

##thingylist=[thing1,thing2,thing3,thing4,thing5,thing6]
################collision###############






############ 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)



#########update display function###########
def update(x,y,fx1,fx2,fx3,fx1a,fx2a,fx3a,fy1,fy2,fy3,fy1a,fy2a,fy3a):
    gamedisplay.blit(bg,[0,0])
    gamedisplay.blit(frog,(x,y))
    gamedisplay.blit(thing1,(fx1,fy1))
    gamedisplay.blit(thing2,(fx2,fy2))
    gamedisplay.blit(thing3,(fx3,fy3))
    gamedisplay.blit(thing4,(fx1a,fy1a))
    gamedisplay.blit(thing5,(fx2a,fy2a))
    gamedisplay.blit(thing6,(fx3a,fy3a))
    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))
    gamedisplay.blit(thing1,(fx1,fy1))
    gamedisplay.blit(thing2,(fx2,fy2))
    gamedisplay.blit(thing3,(fx3,fy3))
    gamedisplay.blit(thing4,(fx1a,fy1a))
    gamedisplay.blit(thing5,(fx2a,fy2a))
    gamedisplay.blit(thing6,(fx3a,fy3a))
    label=font.render("score "+ str(score) ,1,textcolour)
    gamedisplay.blit(label,(750,10))
    pygame.display.flip()
    pygame.event.pump()
    key=pygame.key.get_pressed()


    ############collision detection##########
##    for t in thingylist:
##        if frog.rect.colliderect(thing_rect):
##            score=score+100
update(x,y,fx1,fx2,fx3,fx1a,fx2a,fx3a,fy1,fy2,fy3,fy1a,fy2a,fy3a)

1 Ответ

1 голос
/ 15 апреля 2019

Вам нужно получить rect каждой «вещи» и сравнить ее с frog_rect.Функция PyGame pygame.rect.colliderect() может легко это проверить.Что делает это сложным с вашим текущим кодом, так это то, что вы не знаете rect для каждой вещи, только (x,y).

Поскольку вы не хотите использовать спрайты, я скромно предлагаю вам-работать код для хранения каждой «вещи» в скромной структуре данных, такой как список вещей, где каждая вещь представляет собой пару [ image, rect ].Это позволяет коду просто циклически проходить по списку «вещей» и выполнять над ними операции.

# Create some things
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( 10 ):
    new_thing_image  = thingylist[(random.randrange(0,12))]
    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 ] )

Этот список вещей позволяет коду сказать, что цикл проходит по списку, проверяя наличие коллизий:

def checkCollision( frog_rect, things ):
    """ Find the first thing that collides with frog.
        Return the thing (removing it from the list), or None """
    collides_with = None
    for i in range( len( things) ):
        thing_rect = things[i][1]
        if ( frog_rect.colliderect( thing_rect ) ):
            collides_with = things.pop( i )
    return collides_with

Позволяет коду сказать:

thing_hit = checkCollision( frog_rect, all_things )
if ( thing_hit != None ):
    # We hit something!
    pass # TODO

Также для таких операций, как рисование всех вещей:

def drawThings( things ):
    for item in things:
        thing_image, thing_rect = item
        gamedisplay.blit( thing_image, ( thing_rect.x, thing_rect.y ) )

Что гораздо проще, чем отслеживать всеэти отдельные координаты.

...