美文网首页
Pygame 模块简单整理

Pygame 模块简单整理

作者: Juttachen_8e9d | 来源:发表于2018-07-07 14:11 被阅读77次

    Pygame 模块简单整理

    2018.07.07 Juttachen


    概述

    • 如何打开一个游戏窗口?
    • 如何进行鼠标键盘与窗口的互动?
    • 如何显示图片?
    • 如何显示文字?
    • 如何显示图形?
    • 如何使游戏出现动态效果?
    • 如何制作一个按钮?
    • 游戏实例

    一、如何打开一个游戏窗口?

    1.怎么导入第三方的包/库/模块

        import pygame
    

    =====标准格式=====

    每次写都必须有的格式

    1.初始化pygame

        pygame.init()
    

    2.创建窗口

        # set_mode((宽, 高)) ---> 单位是像素
        screen = pygame.display.set_mode((600, 400))
    

    3.设置填充颜色

    补充:
    颜色值(是由计算机的三原色组成-->红、绿、蓝),简称RGB。我们能使用的所有的颜色都可以通过RGB值来表示
    RGB值的表示方式:
    a. (red值, green值, blue值) 值都是数字:0-255 (255, 0, 0)->红色 (255, 255, 255)->白色
    b.十六进制的RGB值 #ff0000 -> 红色 #000000 ->黑色 #00ff00 -> 绿色

        # 设置填充颜色为红色
        screen.fill((14, 110, 109))
    

    4.将前面的内容渲染到屏幕

    一般在游戏开发时,会把这句放到最后,以节省CPU内存。

        pygame.display.flip()
    

    5. 让窗口可以一直显示在屏幕上,直到点关闭按钮

    让窗口一直显示在桌面,需要用到循环,即让游戏循环播放在桌面上。

        while True:
            # 获取事件
            for event in pygame.event.get():
                # 拿到点关闭窗口的事件 QUIT-->关闭
                if event.type == pygame.QUIT:
                    # 退出程序,遇到exit方法程序就结束
                    exit()
    

    二、如何进行鼠标键盘与窗口的互动?

    =====固定格式=====

        import pygame
        def main():
            # 初始化
            pygame.init()
            # 创建窗口
            screen = pygame.display.set_mode((600, 400))
            # 设置背景颜色
            screen.fill((255, 255, 255))
    
            pygame.display.flip()
    

    + 与键盘鼠标相关的操作

    所有与键盘鼠标相关的操作都一定要放到循环中。

            while True:
                # 获取事件
                for event in pygame.event.get():
                    # 1.点关闭按钮对应的事件
                    if event.type == pygame.QUIT:
                        exit()
    
                    # 2.鼠标按下对应的事件
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        # 获取鼠标按下的坐标
                        print(event.pos)
                        print('鼠标按下')
    
                    if event.type == pygame.MOUSEBUTTONUP:
                        # 获取鼠标按下后弹起的坐标
                        print(event.pos)
                        print('鼠标按下弹起')
    
                    if event.type == pygame.MOUSEMOTION:
                        # 鼠标移动过程中对应的点的坐标
                        # print(event.pos)
                        # print('鼠标移动')
                        pass
    
                    # 3.键盘相关的事件
                    if event.type == pygame.KEYDOWN:
                        print(chr(event.key))
                        print('键盘按钮按下')
                        if chr(event.key) == 'ē':
                            print('右')
    
                    if event.type == pygame.KEYUP:
                        print(chr(event.key))
                        print('键盘按钮按下弹起来')
    
        #这句话与模块首的main函数相对应,是用来测试这个模块是否被调用的。专业程序员一般都会写这个函数,用于对模块进行规范。
        if __name__ == '__main__':
            main()
    

    三、如何显示图片?

    =====固定格式=====

        import pygame
        # 初始化
        pygame.init()
    
        # 创建窗口
        screen = pygame.display.set_mode((600, 400))
        print(type(screen))
        screen.fill((255, 255, 255))
    

    显示图片:

    1. 创建一个图片对象(Surface)

    后面还有配套语句,必须都写

        image = pygame.image.load('./files/luffy4.jpg')
    

    对图片进行处理:

    1. 获取图片的大小

    格式:(width, height) = 图片对象.get_size()

        size = image.get_size()
        print(size)
    

    2. 对图片进行缩放

    将指定的图片,变成指定的大小,返回一个新的图片对象
    格式:pygame.transform.scale(图片对象,(宽度,高度))

        image1 = pygame.transform.scale(image, (600, 400))
    

    3. 对图片进行旋转

    格式:
    pygame.transform.rotate(图片对象, 旋转角度)
    角度:0-360的度数值

        image2 = pygame.transform.rotate(image, 180)
    

    4. 对图片进行旋转缩放

    格式:pygame.transform.rotozoom(图片对象, 旋转角度, 缩放倍数)

        image3 = pygame.transform.rotozoom(image, 0, 2)
    

    显示图片:

    2. 将图片对象添加到窗口对象中

    blit(需要添加到窗口的对象,坐标)
    坐标 ——>(x, y)
    一般图片具体操作完成就可以加上这句话来确定显示位置了

        screen.blit(image3, (0, 0))
    

    3.显示在屏幕上

        # 不再是 pygame.display.flip()
        pygame.display.update()
    

    =====固定格式=====

        # 让窗口停留
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
    

    四、如何显示文字?

    =====固定格式=====

        import pygame
        # 初始化
        pygame.init()
        # 创建窗口
        screen = pygame.display.set_mode((600, 400))
        # 设置窗口的背景颜色为白色
        screen.fill((255, 255, 255))
    

    1.创建字体对象

    两种形式:
    SysFont(系统字体名, 字体大小)
    Font(字体文件地址, 字体大小)

        font1 = pygame.font.SysFont('Times', 20)
        font2 = pygame.font.Font('../files/aa.ttf', 40)
    

    2.根据字体创建文字对象

    格式:render(文字, 是否平滑, 文字颜色)

        title = '根据字体创建文字对象'  
        text = font.render(title, True, (255, 0, 0))
    

    3.将文字对象添加到窗口上

        screen.blit(text, (100, 0))
    

    =====固定格式=====

        #4.将内容显示在屏幕上
        pygame.display.flip()
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
    

    五、 如何显示图形?

    =====固定格式=====

        import pygame
    
        # 初始化
        pygame.init()
        # 创建窗口
        screen = pygame.display.set_mode((600, 400))
        screen.fill((255, 255, 255))
    

    1.画线

    方法一:line(外观对象, 线颜色,起点, 终点, 线宽)

        pygame.draw.line(screen, (0, 0, 255), (100, 100), (200, 100))
        pygame.draw.line(screen, (0, 0, 255), (100, 100), (100, 200), 10)
    

    方法二:lines(外观对象, 线颜色, 是否闭合, 点的列表, 线宽)
    第三个参数:Flase -> 不闭合 ; True --> 闭合

        pygame.draw.lines(screen, (255, 0, 0), True, [(300, 50), (150, 180), (200, 120), (330, 200)], 3)
    

    2.画矩形

    格式:
    rect(外观对象, color, Rect, width)
    Rect: 告诉位置和大小 --> (x, y, width, height)
    width: 为0就会填充矩形

        pygame.draw.rect(screen, (0, 255, 0), (10, 10, 200, 150), 0)
    

    3.画弧线

    格式:
    arc(外观对象, 颜色, 范围, 起始角度, 终止角度, 线宽)

        from math import pi
        pygame.draw.arc(screen, (255, 255, 0), (10, 200, 200, 200), pi/2, pi, 3)
    

    =====固定格式=====

        # 将内容显示在屏幕上
        pygame.display.flip()
    
        while True:
            for event in pygame.event.get():
                # 关闭事件
                if event.type == pygame.QUIT:
                    print('退出')
                    exit()
    

    六、如何使游戏出现动态效果?

    =====固定格式=====

        import pygame
    
        def main():
            # 游戏初始化
            pygame.init()
            screen = pygame.display.set_mode((600, 400))
            screen.fill((255, 255, 255))
            pygame.display.flip()
    
    
            x = 100
            y = 100
    
            names = ['张三', '李四', '王五', '骆昊', '王海飞', '肖世荣']
            index = 0
    
            # 游戏循环
            while True:
                # 事件获取
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        exit()
    
    
                pygame.time.delay(100)
                # screen.fill((255, 255, 255))
                pygame.draw.rect(screen, (255, 255, 0),(200, 200, 100, 50))
                # 获取文字
                font = pygame.font.Font('./files/aa.ttf', 30)
                text = font.render(names[index], True, (0, 0, 0))
                screen.blit(text, (200, 200))
                pygame.display.flip()
    
                # 获取下一个文字下标
                index += 1
                if index >= len(names):
                    index = 0
    
        if __name__ == '__main__':
            main()
    

    =========小球动起来=========

        # 延迟操作
        # delay(时间) ,时间单位是毫秒
        pygame.time.delay(100)
        # 覆盖之前画的内容
        screen.fill((255, 255, 255))
        # 画圆
        pygame.draw.circle(screen, (0, 255, 0), (x, y), 50)
        x += 5
        y += 5
        pygame.display.flip()
    

    七、如何制作一个按钮?

        import pygame
    
        def creat_button(screen, bg_color, text_color):
            # 清空前面画的
            pygame.draw.rect(screen, (255, 255, 255), (100, 100, 150, 70))
            # 画矩形
            pygame.draw.rect(screen, bg_color,(100, 100, 150, 70))
    
            # 画文字
            font = pygame.font.Font('./files/aa.ttf', 30)
            text = font.render('开 始', True, text_color)
            screen.blit(text, (140, 120))
    
            pygame.display.flip()
    
        def main():
            # 游戏界面初始化
            pygame.init()
            screen = pygame.display.set_mode((600, 400))
            screen.fill((255, 255, 255))
    
            # 显示一个按钮
            creat_button(screen, (0, 255, 0), (100, 100, 100))
    
            pygame.display.flip()
    
            while True:
                # 获取事件
                for event in pygame.event.get():
                    # 1.点关闭按钮对应的事件
                    if event.type == pygame.QUIT:
                        exit()
    
                    # 2.鼠标按下对应的事件(确定反应范围)
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        x, y = event.pos
                        if 100<x<100+150 and 100<y<100+70:
                            creat_button(screen, (0, 150, 0), (255, 0, 0))
    
                    if event.type == pygame.MOUSEBUTTONUP:
                        creat_button(screen, (0, 255, 0), (100, 100, 100))
    
                    if event.type == pygame.MOUSEMOTION:
                        # 鼠标移动过程中对应的点的坐标
                        # print(event.pos)
                        # print('鼠标移动')
                        pass
    
    
        if __name__ == '__main__':
            main()
    

    八、游戏实例

    球吃球游戏

        import pygame
        import random
        from math import sqrt
    
    
        class Color:
            """颜色"""
            white = (255, 255, 255)
            black = (0, 0, 0)
            gray = (89, 89, 89)
            light_gray = (220, 220, 220)
    
            @staticmethod
            def rand_color():
                r = random.randint(0, 255)
                g = random.randint(0, 255)
                b = random.randint(0, 255)
                return r, g, b
    
    
        class Ball:
            """球"""
            # 用来存储所有的球的对象
            all_balls = []
    
            def __init__(self, x, y):
                self.color = Color.rand_color()
                self.radius = random.randint(10, 30)
                self.x = x
                self.y = y
                self.x_speed = random.randint(-10, 10)
                self.y_speed = random.randint(-10, 10)
    
    
            # 显示一个球
            def show(self, screen):
                pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
    
            # ============相撞================
            # 判断两个球是否相撞
            def crash(self, other):
                x_distance = self.x - other.x
                y_distance = self.y - other.y
                distance = sqrt(x_distance**2 + y_distance**2)
                if distance <= self.radius + other.radius:
                    self.radius += int(other.radius * 0.4)
                    # 移除被吃掉的球
                    Ball.all_balls.remove(other)
    
            @classmethod
            def find_all_ball(cls):
                # 拿第一个球
                for ball1 in cls.all_balls:
                    # 拿第二个球
                    for ball2 in cls.all_balls:
                        if ball1 == ball2:
                            continue
                        ball1.crash(ball2)
            # 动起来
            def move(self, screen):
                new_x = self.x + self.x_speed
                new_y = self.y + self.y_speed
    
                # 越界问题
                if new_x <= self.radius:
                    new_x = self.radius
                    self.x_speed *= -1
                elif new_x >= screen.get_size()[0]-self.radius:
                    new_x = screen.get_size()[0]-self.radius
                    self.x_speed *= -1
    
                if new_y <= self.radius:
                    new_y = self.radius
                    self.y_speed *= -1
                elif new_y >= screen.get_size()[1] - self.radius:
                    new_y = screen.get_size()[1] - self.radius
                    self.y_speed *= -1
    
                # 更新位置
                self.x = new_x
                self.y = new_y
    
        def main():
            # 游戏初始化
            pygame.init()
            screen = pygame.display.set_mode((600, 400))
            screen.fill(Color.white)
            pygame.display.flip()
    
            # gameLoop
            while True:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        exit()
        
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        # 创建一个球
                        ball = Ball(event.pos[0], event.pos[1])
                        # 显示一个球
                        ball.show(screen)
                        pygame.display.flip()
    
                        # 将球存起来
                        Ball.all_balls.append(ball)
    
                pygame.time.delay(100)
                # 重新填充界面
                screen.fill(Color.white)
    
                # 让所有的小球动起来
                for ball in Ball.all_balls:
                    ball.move(screen)
                    ball.show(screen)
    
                # 碰撞检测
                Ball.find_all_ball()
    
                # 刷新界面的显示
                pygame.display.flip()
    
    
        if __name__ == '__main__':
            main()
    

    相关文章

      网友评论

          本文标题:Pygame 模块简单整理

          本文链接:https://www.haomeiwen.com/subject/sgniuftx.html