微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我已经开始在Pygame中编写《飞扬的小鸟》游戏,但我卡住了如何显示《小鸟与竹子之间的碰撞》?

如何解决我已经开始在Pygame中编写《飞扬的小鸟》游戏,但我卡住了如何显示《小鸟与竹子之间的碰撞》?

所以我对Pygame还是很陌生,我一直在研究如何在柔和的鸟类游戏中显示鸟类与竹子之间的碰撞,以及如何在未与竹子发生碰撞的情况下继续运行它。 我还没有编写完整的代码,所以请告诉我该如何显示碰撞(带有步骤,为什么要使用它?在pygame中使用)以及碰撞后屏幕上显示GAME OVER的源代码。(可选) ) (提前感谢:)

import pygame
pygame.init()

WINDOWWIDTH = 820
WINDOWHEIGHT = 480
win = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
pygame.display.set_caption("The Flappy Bird Game")

birdload = [pygame.image.load('C:/Users/Vinod/Desktop/Flappy Bird/flapbird.png')]

bgimg = pygame.image.load('C:/Users/Vinod/Desktop/Flappy Bird/bg.jpg')

clock=pygame.time.Clock()

UP = 'up'
DOWN ='down'
LEFT ='left'
RIGHT = 'right'

WHITE =(255,255,255)
BLACK = (0,0)
RED = (255,0)
GREEN = (0,0)
DARKGREEN = (0,155,0)
DARKGRAY = (40,40,40)
YELLOW = (255,0)
ORANGE = (255,165,0)
BGCOLOR = BLACK
broWN = (90,39,41)

score = 0



def showstartscreen():
    global BASICFONT,FPS
    FPS = 15
    BASICFONT = pygame.font.Font('freesansbold.ttf',18)
    titleFont = pygame.font.Font('freesansbold.ttf',100)
    titleSurf1 = titleFont.render('The Flappy Bird!',True,WHITE,YELLOW)
    titleSurf2 = titleFont.render('The Flappy Bird!',ORANGE)
    degrees1 = 0
    degrees2 = 0
    while True:
        win.fill(BGCOLOR)
        rotatedSurf1= pygame.transform.rotate(titleSurf1,degrees1)
        rotatedRect1 = rotatedSurf1.get_rect()
        rotatedRect1.center= (WINDOWWIDTH / 2,WINDOWHEIGHT / 2)
        win.blit(rotatedSurf1,rotatedRect1)
        
        rotatedSurf2 = pygame.transform.rotate(titleSurf2,degrees2)
        rotatedRect2 = rotatedSurf2.get_rect()
        rotatedRect2.center = (WINDOWWIDTH / 2,WINDOWHEIGHT / 2)
        win.blit(rotatedSurf2,rotatedRect2)
        
        drawPressKeyMsg()
        
        pygame.display.update()
        clock.tick(FPS)
        degrees1 += 3 #rotate 3 degrees each frame
        degrees2 += 7 #rotate by 7 degrees per frame
        
def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.',DARKGRAY)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (WINDOWWIDTH - 200,WINDOWHEIGHT - 30)
    win.blit(pressKeySurf,pressKeyRect)
    

def terminate():
    pygame.quit()
    
class bird(object):
    def __init__(self,x,y,width,height,end):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.end = end
        self.path = [self.x,self.end]
        self.flyCount = 0
        self.vel = 3
        self.hitBox = (self.x + 17,self.y + 2,31,57)
        self.visible = True
        
    def draw(self,win):
        if self.flyCount + 1 >= 27:
            self.flyCount = 0

        if not(self.standing):
            win.blit(birdload[self.flyCount//3],(self.x,self.y))
            self.flyCount +=1
        else:
            win.blit(birdload[0],self.y))
        self.hitBox = (self.x + 17,self.y + 11,29,52)
        #pygame.draw.rect(win,(255,0),self.hitBox,2)
        
    def hit(self):
        self.isJump = False
        self.jumpCount = 10
        self.x = 100
        self.y = 410
        self.flyCount = 0
        font1 = pygame.font.SysFont('comicsans',100)
        text = font1.render('-5',1,0))
        win.blit(text,(250 - (text.get_width()/2),200))
        pygame.display.update()
        i = 0
        while i < 200:
            pygame.time.delay(10)
            i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    i = 201
                    pygame.quit()
                    
    def fly(self):
        if self.vel > 0:
            if self.x + self.vel < self.path[1]:
                self.x += self.vel
            else:
                self.vel = self.vel * -1
                self.flyCount = 0
        else:
            if self.x - self.vel > self.path[0]:
                self.x += self.vel
            else:
                self.vel = self.vel * -1
                self.flyCount = 0
                    
    
def bamboo():
    bamb0 = pygame.draw.rect(win,broWN,(310,28,140))#left,top,height
    pygame.display.flip()
    bamb1 = pygame.draw.rect(win,230,250))
    pygame.display.flip()
    bamb2 = pygame.draw.rect(win,(410,100))#left,height
    pygame.display.flip()
    bamb3 = pygame.draw.rect(win,160,320))#left,height
    pygame.display.flip()
    bamb4 = pygame.draw.rect(win,(510,110))#left,height
    pygame.display.flip()
    bamb5 = pygame.draw.rect(win,180,300))#left,height
    pygame.display.flip()
    bamb6 = pygame.draw.rect(win,(600,240))#left,height
    pygame.display.flip()
    bamb7 = pygame.draw.rect(win,320,160))#left,height
    pygame.display.flip()
    bamb8 = pygame.draw.rect(win,(700,120))#left,height
    pygame.display.flip()
    bamb9 = pygame.draw.rect(win,200,280))#left,height
    pygame.display.flip()
    bamb10 = pygame.draw.rect(win,(770,190))#left,height
    pygame.display.flip()
    bamb11 = pygame.draw.rect(win,250,230))#left,height
    pygame.display.flip()
    
    
class sticks(object):
    bamboo()
    
    
    def collision():
        if bird.x == sticks.x and bird.y == sticks.y:
            print("Game Over")
            gameover()
            while True:
                if checkForKeyPress():
                    pygame.event.get() # clear event queue
                    return
        else:
            True()

请最后参考“类杆”中的“ def碰撞”,我知道我添加代码可能是错误的...请仅为此部分回答... 问候, 西田塔库尔。

解决方法

设计对象时,通常是针对单个对象,所以说“树”而不是“森林”,因为森林是一组树。 sticks类已经朝着正确的方向发展,但是随后使用名为bamboo()的函数来知道它们的位置并绘制所有它们。

使您的代码更易于使用的方法是将这两个代码结合在一起,从而使单个对象负责每根竹子的位置,绘制和碰撞。多个对象被分组在一起,以便在Python“容器”数据结构(如列表)中轻松访问。

首先让我们新建一个Bamboo

class Bamboo:

    def __init__( self,x,y,width,height ):
        self.image  = pygame.Surface( ( width,height ) )
        self.rect   = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        # currently the image is a brown rectangle
        self.image.fill( BROWN )
        
    def draw( self,surface ):
        surface.blit( self.image,self.rect )
        
    def move( self,dx,dy ):
        self.rect.move_ip( dx,dy )
        
    def collidesWith( self,other_rect ):
        result = self.rect.colliderect( other_rect )
        return result

关于Bamboo实体的所有内容都包含在Bamboo对象中。由于此对象了解有关自身的所有知识(而无其他知识),因此很容易实现collidesWith()函数,图形等。

但是我们如何创建所有这些竹签-循环填充列表。

### Create the list of Bamboo            
all_bamboo = []     # list to hold the final objects

# List of initial locations and sizes
initial_locs = [ (310,28,140),(310,230,250),(410,100),160,320),(510,110),180,300),(600,240),320,160),(700,120),200,280),(770,190),250,230) ]
                 
# loop through the locations,making Bamboo,appending to list                 
for location in initial_locs:
    x,height = location                  # unpack location
    new_bamboo = Bamboo( x,height )      # create a Bamboo
    all_bamboo.append( new_bamboo )                 # move to list

因此,现在您已经创建了所有Bamboo对象,并将其移至名为all_bamboo的列表中。列表中的所有内容使绘制,移动和检查碰撞变得轻而易举。

您不会在问题中显示主循环函数,所以我自己做:

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            pass   # TODO - handle mouse-clicks
        elif ( event.type == pygame.KEYUP ):
            pass   # TODO - handle player-input

    ### Update the window
    window.fill( WHITE )         # fill the background

    # draw the sprites
    player_bird.draw( window )   # draw player

    for bamboo in all_bamboo:    # draw all bamboo
        bamboo.draw( screen )

    pygame.display.flip()        # send the updates to the screen

    ### Check for collisions & move bamboo
    bird_rect = pygame.Rect( bird.hitbox )        # location of bird
    for bamboo in all_bamboo:                     # for each stick of bamboo
        if ( bamboo.collidesWith( bird_rect ) ):  # does it collide?
            # Bird hit bamboo,now what?
            bird.hit()                            # ouch!
        
        # move the bamboo 1 pixel left
        # so it looks like the bird moves forward
        bamboo.move( -1,0 )

    clock.tick(60)

pygame.quit()

每当您发现自己需要一组项目时,(可能是乌云密布)就会想到代表单个实体的单个对象,然后是容器数据结构来容纳它们。

因此,当您发现自己向对象的核心部分中不添加代码时,例如说:在collidesWith()函数中添加“ game over”子句,您可以问自己“正在绘制图形”游戏结束画面真的是竹棍的责任吗?!”这些想法可以保持一个好的设计。这有助于防止在不相关的位置放置逻辑位置不佳的意大利面条代码。

注意:上面未测试,已调试代码。错误和遗漏应该是可以预期的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。