一个Pygame小练习

2019-02-24  本文已影响0人  cooooooooodeway

Pygame是什么?

Pygame是一个基于SDL的Python多媒体应用开源库,常用于游戏开发等场景。Pygame支持多平台,适应多种操作系统。

Pygame的模块

Pygame包含了很多用于多媒体应用开发的模块,常用的模块包括:Color, display, draw, event, font, image, key, locals, mixer, mouse, Rect, Surface, time, music 以及总包pygame本身,也支持更高级的应用,如cursors, joystick, mask, sprite, transform, BufferProxy, freetype, gfxdraw, midi, Overlay, PixelArray, pixelcopy, sndarray, surfarray, math等, 也包括camera, cdrom,scrap, tests,version,examples 等辅助模块。

Pygame程序的基本结构

跟一般的UI程序一样,Pygame程序主体是一个循环,程序每隔一定时间响应用户输入,更新显示内容。

在显示部分,所有元素通过pygame.display对象进行显示。Pygame将显示对象包装为Surface对象,并用blit({surface},{rect})方法贴在屏幕上。粘贴的前后顺序决定显示的图层,约晚贴上去,图层越高。粘贴完之后通过pygame.display.update()或pygame.display.flip()刷新显示。

基于Pygame的小游戏

这是一个猴子接苹果的游戏。要求可以利用方向键控制猴子左右移动,向上键跳动。苹果从上方落下。随着时间的增加苹果下落速度也越来越快。如果苹果碰到屏幕下边缘游戏结束。统计接到的苹果数量显示在屏幕上。代码及说明如下(运行环境为Python3.5+):

阅读代码

import pygame
from pygame.locals import *  
from sys import exit
from random import *

SCREEN_SIZE=(640,480)

class Monkey(pygame.sprite.Sprite):
    def __init__(self, initial_position, speed=5):
        pygame.sprite.Sprite.__init__(self)
        #将图片对象转化为Surface对象的方法包括convert和convert_alpha,区别在于:
        #convert:将图像数据转化为Surface对象,必须有
        #convert_alpha:同Convert且保留Alpha通道信息
        image = pygame.image.load("res/monkey.png").convert_alpha()
        #对图片进行平滑缩放,以适应显示要求
        #也可对图片进行剪裁
        # #图片剪裁
        # rect=pygame.Rect(0,0,40,40) #LEFT,TOP,WIDTH,HEIGHT
        # image=image.subsurface(rect)
        self.image = pygame.transform.smoothscale(image,(40,40))
        
        self.rect=self.image.get_rect()
        self.rect.bottomright=initial_position
        self.speed=speed
        self.jumpspeed = 10*speed
        self.injump=False
        

    def moveleft(self):
        self.rect.left=self.rect.left - self.speed
        if self.rect.left<0:
            self.rect.left=0
    
    def moveright(self):
        self.rect.right = self.rect.right + self.speed
        if self.rect.right>SCREEN_SIZE[0]:
            self.rect.right = SCREEN_SIZE[0]

    def jumpup(self):
        self.injump=True
    
    def jumpmove(self):
        if self.injump:
            self.rect.bottom = self.rect.bottom - self.jumpspeed
            self.jumpspeed -= self.speed
            if self.rect.bottom > SCREEN_SIZE[1]:
                self.rect.bottom = SCREEN_SIZE[1]
                self.injump=False
                self.jumpspeed = 10* self.speed


class Apple(pygame.sprite.Sprite):
    def __init__(self, initial_position, acc=0.1, speed=0):
        pygame.sprite.Sprite.__init__(self)
        image = pygame.image.load("res/apple.png").convert_alpha()
        self.image = pygame.transform.smoothscale(image,(20,20))
        self.rect=self.image.get_rect()
        self.rect.bottomright=initial_position
        self.acc=acc
        self.speed=speed

    def move(self):
        self.rect.bottom = self.rect.bottom + self.speed
        self.speed += self.acc
    

def main():
    pygame.init() 
    screen=pygame.display.set_mode(SCREEN_SIZE,0,32) 
    pygame.display.set_caption("猴子接苹果") 

    screen.fill((255,255,255))
    background_path="res/background.jpg"
    background=pygame.image.load(background_path).convert()
    screen.blit(background,(0,0))
    score =0

    font=pygame.font.SysFont('arial',16)
    text=font.render("Score: %s"%score, True, (0,0,0), (255,255,255)) 
    textrect = text.get_rect(centerx = 50, centery=10)
    screen.blit(text, textrect)

    clock=pygame.time.Clock()

    monkey=Monkey([SCREEN_SIZE[0]/2, SCREEN_SIZE[1]])
    apple = Apple([randint(0, SCREEN_SIZE[0]), 0])

    while True:
        screen.blit(background,(0,0))
        #获取事件的方法:
        #pygame.event.get;pygame.event.wait;pygame.event.epoll();
        for event in pygame.event.get():
            #事件类型:
            # 窗口:QUIT,ATiVEEVENT,VIDEORESIZE,VIDEOEXPOSE; 
            # 用户:USEREVENT;
            # 键盘:KEYDOWN,KEYUP;
            # 鼠标:MOUSEMOTION,MOUSEBUTTONDOWN,MOUSEBUTTONUP;
            # 手柄:JOYAXISMOTION,JOYBALLMOTION,JOYHATMOTION,JOYBUTTONDOWN,JOYBUTTONUP
            if event.type==QUIT:
                exit()
            #KEYDOWN事件的参数:
            #KEY(key,mod,unicode) 
            #key=K_{键名,如:a,space,enter,return等}, 
            #mod“组合键信息”={用位运算获取mod&KMOD_CTRL,mod&KMOD_SHIFT,mod&KMOD_ALT},             #unicode键值
            if event.type==pygame.KEYDOWN:
            #键的按下效果通过pygame.key.get_pressed()实现,在游戏中用键的按下事件操控不够顺滑
            #     if event.key==pygame.K_LEFT:
            #         monkey.moveleft()
            #     if event.key==pygame.K_RIGHT:
            #         monkey.moveright()
                if event.key==pygame.K_UP:
                    if not monkey.injump:
                        monkey.jumpup()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_LEFT]:
            monkey.moveleft()
        if key_pressed[pygame.K_RIGHT]:
            monkey.moveright()

        if monkey.injump:
            monkey.jumpmove()
        screen.blit(monkey.image,monkey.rect)
        
        oldrect = apple.rect
        apple.move()
        newrect = apple.rect
        if pygame.Rect.colliderect(monkey.rect, pygame.Rect(oldrect.left,oldrect.top, newrect.width,newrect.top+newrect.height-oldrect.top)):
            score+=1
            text=font.render("Score: %s"%score, True, (0,0,0), (255,255,255))  
            apple = Apple([randint(0, SCREEN_SIZE[0]), 0])
        if apple.rect.bottom > SCREEN_SIZE[1]:
            text = font.render("Game Over! Total Score:%s"% score, True, (0,0,0), (255,255,255))
            screen.blit(text, text.get_rect(centerx = 320, centery=240))
            pygame.display.update()
            pygame.time.delay(5000)
            exit()

        # print(apple.rect.bottom)
        screen.blit(apple.image, apple.rect)

        screen.blit(text, textrect)

        pygame.display.update()
        clock.tick(60)
            
if __name__=="__main__":
    main()

运行效果如图:


猴子接苹果

阅读原文

上一篇下一篇

猜你喜欢

热点阅读