pygame squirrel

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

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

FPS = 30
winx = 640
winy = 480
halfx = winx/2
halfy = winy/2

grasscolor = (24,255,0)
white = (255,255,255)
red = (255,0,0)

startsize = 25
left = 'left'
right = 'right'
squirrelnum = 30
minspeed = 3
maxspeed = 7
directfreq = 2
maxhealth = 3
intime = 2
numgrass = 80
cameraslack = 90
bouncerate = 6
bounceheight = 30
moverate = 9
winsize = 300
gameovertime = 4


def main():
    global fpsclock,disp,basicfont,limg,rimg,grassimg
    
    pygame.init()
    fpsclock = pygame.time.Clock()
    pygame.display.set_icon(pygame.image.load('gameicon.png'))
    disp = pygame.display.set_mode((winx,winy))
    pygame.display.set_caption('squirrel')
    basicfont = pygame.font.Font('freesansbold.ttf',32)

    limg = pygame.image.load('squirrel.png')
    rimg = pygame.transform.flip(limg,True,False)
    grassimg = []
    for i in range(1,5):
        grassimg.append(pygame.image.load('grass%s.png'%i))
    while True:
        rungame()
        
def rungame():
    invulnerablemode = False
    invulnerablestarttime = 0
    gameovermode = False
    gameoverstarttime = 0
    winmode = False

    gameoversurf = basicfont.render('Game Over',True,white)
    gameoverrect = gameoversurf.get_rect()
    gameoverrect.center = (halfx,halfy)

    winsurf = basicfont.render('you have achieved omega squirrel.',True,white)
    winrect = winsurf.get_rect()
    winrect.center = (halfx,halfy)

    winsurf2 = basicfont.render('Press r to restart.',True,white)
    winrect2 = winsurf2.get_rect()
    winrect2.center = (halfx,halfy + 30)

    camerax = 0
    cameray = 0
    
    grassobj = []
    squirrelobj = []

    playerobj = {'surface': pygame.transform.scale(limg,(startsize,startsize)),
                 'facing':left,
                 'size':startsize,
                 'x': halfx,
                 'y': halfy,
                 'bounce':0,
                 'health':maxhealth}

    moveleft = False
    moveright = False
    moveup = False
    movedown = False

    for i in range(10):
        grassobj.append(makenewgrass(camerax,cameray))
        grassobj[i]['x'] = random.randint(0,winx)
        grassobj[i]['y'] = random.randint(0,winy)
    
    while True:
        if invulnerablemode and time.time()-invulnerablestarttime>intime:
            invulnerablemode = False

        for sobj in squirrelobj:
            sobj['x'] += sobj['movex']
            sobj['y'] +=sobj['movey']
            sobj['bounce'] +=1
            if sobj['bounce'] >sobj['bouncerate']:
                sobj['bounce'] = 0

            if random.randint(0,99)<directfreq:
                sobj['movex'] = getrandomvelocity()
                sobj['movey'] = getrandomvelocity()
                if sobj['movex'] > 0:
                    sobj['surface'] = pygame.transform.scale(rimg,(sobj['width'],sobj['height']))
                else:
                    sobj['surface'] = pygame.transform.scale(limg,(sobj['width'],sobj['height']))

        for i in range(len(grassobj)-1,-1,-1):
            if outsidearea(camerax,cameray,grassobj[i]):
                del grassobj[i]
        for i in range(len(squirrelobj)-1,-1,-1):
            if outsidearea(camerax,cameray,squirrelobj[i]):
                del squirrelobj[i]

        while len(grassobj)<numgrass:
            grassobj.append(makenewgrass(camerax,cameray))
        while len(squirrelobj)<squirrelnum:
            squirrelobj.append(makenewsquirrel(camerax,cameray))

        playercenterx = playerobj['x']+int(playerobj['size']/2)
        playercentery = playerobj['y']+int(playerobj['size']/2)

        if (camerax+halfx) - playercenterx >cameraslack:
            camerax = playercenterx + cameraslack - halfx
        elif playercenterx - (camerax + halfx)>cameraslack:
            camerax = playercenterx - cameraslack - halfx
        if (cameray+halfy)-playercentery > cameraslack:
            cameray = playercentery + cameraslack-halfy
        elif playercentery-(cameray+halfy)>cameraslack:
            cameray = playercentery-cameraslack-halfy

        disp.fill(grasscolor)

        for gobj in grassobj:
            grect = pygame.Rect((gobj['x']-camerax,
                                 gobj['y']-cameray,
                                 gobj['width'],
                                 gobj['height']))
            disp.blit(grassimg[gobj['grassimage']],grect)

        for sobj in squirrelobj:
            sobj['rect'] = pygame.Rect((sobj['x']-camerax,
                                 sobj['y']-cameray-getbounceamount(sobj['bounce'], sobj['bouncerate'], sobj['bounceheight']),
                                 sobj['width'],
                                 sobj['height']))
            disp.blit(sobj['surface'],sobj['rect'])

        flashison = round(time.time(),1)*10%2 == 1
        if not gameovermode and not (invulnerablemode and flashison):
            playerobj['rect'] = pygame.Rect((playerobj['x']-camerax,
                                 playerobj['y']-cameray-getbounceamount(playerobj['bounce'], bouncerate, bounceheight),
                                 playerobj['size'],
                                 playerobj['size']))
            disp.blit(playerobj['surface'],playerobj['rect'])
            
        drawhealth(playerobj['health'])

        for event in pygame.event.get():
            if event.type == QUIT:
                terminal()

            elif event.type ==KEYDOWN:
                if event.key in (K_UP,K_w):
                    movedown = False
                    moveup = True
                elif event.key in (K_DOWN,K_s):
                    moveup = False
                    movedown = True
                elif event.key in (K_LEFT,K_a):
                    moveright = False
                    moveleft = True
                    if playerobj['facing'] !=right:
                        playerobj['surface'] = pygame.transform.scale(limg,(playerobj['size'],playerobj['size']))
                    playerobj['facing'] = left                    
                elif event.key in (K_RIGHT,K_d):
                    moveleft = False
                    moveright = True
                    if playerobj['facing'] !=right:
                        playerobj['surface'] = pygame.transform.scale(rimg,(playerobj['size'],playerobj['size']))
                    playerobj['facing'] = left
                elif winmode and event.key ==K_r:
                    return
            elif event.type ==KEYUP:
                if event.key in (K_LEFT,K_a):
                    moveleft = False
                elif event.key in (K_DOWN,K_s):
                    movedown = False       
                elif event.key in (K_UP,K_w):
                    moveup = False
                elif event.key in (K_RIGHT,K_d):
                    moveright = False
                elif event.key == K_ESCAPE:
                    terminal()
        if not gameovermode:
            if moveleft:
                playerobj['x'] -=moverate
            if moveright:
                playerobj['x'] +=moverate
            if moveup:
                playerobj['y'] -=moverate
            if movedown:
                playerobj['y'] +=moverate

            if (moveleft or moveright or moveup or movedown) or playerobj['bounce']!=0:
                playerobj['bounce'] +=1
            if playerobj['bounce'] >bouncerate:
                playerobj['bounce'] = 0

            for i in range(len(squirrelobj)-1,-1,-1):
                sqobj = squirrelobj[i]
                if 'rect' in sqobj and playerobj['rect'].colliderect(sqobj['rect']):
                    
                    if sqobj['width']*sqobj['height']<=playerobj['size']**2:
                        playerobj['size'] +=int((sqobj['width']*sqobj['height'])**0.2)+1
                        del squirrelobj[i]

                        if playerobj['facing']==left:
                            playerobj['surface'] = pygame.transform.scale(limg,(playerobj['size'],playerobj['size']))
                        if playerobj['facing']==right:
                            playerobj['surface'] = pygame.transform.scale(rimg,(playerobj['size'],playerobj['size']))      
                        if playerobj['size']>winsize:
                            winmode = True
                            
                    elif not invulnerablemode:
                        invulnerablemode = True
                        invulnerablestarttime = time.time()
                        playerobj['health'] -= 1
                        if playerobj['health'] == 0:
                            gameovermode = True
                            gameoverstarttime = time.time()
        else:
            disp.blit(gameoversurf,gameoverrect)
            if time.time()-gameoverstarttime>gameovertime:
                return


        if winmode:
            disp.blit(winsurf,winrect)
            disp.blit(winsurf2,winrect2)
        pygame.display.update()
        fpsclock.tick(FPS)
            
def drawhealth(currenthealth):
    for i in range(currenthealth):
        pygame.draw.rect(disp,red,(15,5+(10*maxhealth)-i*10,20,10))
    for i in range(maxhealth):
        pygame.draw.rect(disp,white,(15,5+(10*maxhealth)-i*10,20,10),1)
        
def terminal():
    pygame.quit()
    sys.exit()

def getbounceamount(currentbounce,bouncerate,bounceheight):
    return int(math.sin((math.pi/float(bouncerate))*currentbounce)*bounceheight)

def getrandompos(camerax,cameray,objwidth,objheight):
    camerarect = pygame.Rect(camerax,cameray,winx,winy)
    while True:
        x = random.randint(camerax - winx,camerax + 2*winx)
        y = random.randint(cameray - winy,cameray + 2*winy)

        objrect = pygame.Rect(x,y,objwidth,objheight)
        if not objrect.colliderect(camerarect):
            return x,y
        
def makenewgrass(camerax,cameray):
    gr = {}
    gr['grassimage'] = random.randint(0,len(grassimg)-1)
    gr['width'] = grassimg[0].get_width()
    gr['height'] = grassimg[0].get_height()
    gr['x'],gr['y'] = getrandompos(camerax,cameray,gr['width'],gr['height'])
    gr['rect'] = pygame.Rect((gr['x'],gr['y'],gr['width'],gr['height']))
    return gr

def getrandomvelocity():
    speed = random.randint(minspeed,maxspeed)
    if random.randint(0,1)== 0:
        return speed
    else:
        return -speed
    
def makenewsquirrel(camerax,cameray):
    sq = {}
    generalsize = random.randint(5,25)
    multiplier = random.randint(1,3)
    sq['width'] = (generalsize +random.randint(0,10))*multiplier
    sq['height'] = (generalsize +random.randint(0,10))*multiplier
    sq['x'],sq['y'] = getrandompos(camerax,cameray,sq['width'],sq['height'])
    sq['movex'] = getrandomvelocity()
    sq['movey'] = getrandomvelocity()
    if sq['movex']<0:
        sq['surface'] = pygame.transform.scale(limg,(sq['width'],sq['height']))
    else:
        sq['surface'] = pygame.transform.scale(rimg,(sq['width'],sq['height']))
    sq['bounce'] = 0
    sq['bouncerate'] = random.randint(10,18)
    sq['bounceheight'] = random.randint(10,50)
    return sq
def outsidearea(camerax,cameray,obj):
    leftedge = camerax - winx
    rightedge = cameray - winy
    boundrect = pygame.Rect(leftedge,rightedge,winx*3,winy*3)
    objrect = pygame.Rect(obj['x'],obj['y'],obj['width'],obj['height'])
    return not boundrect.colliderect(objrect)

if __name__ =='__main__':
    main()