【Python入门基础】Pygame实例

Pygame程序实例源自小甲鱼python教学视频,如有需要教学视频可在评论区留下邮箱

Pygame实现移动动画

import pygame
import sys

# 初始化Pygame
pygame.init()

size = width,height=1200,820
speed=[-2,1]
bg=(255,255,255) # RGB

# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption('mermer')
# 加载图片
turtle = pygame.image.load('1.jpg')
# 获得图形的位置矩形
position = turtle.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    # 移动图像
    position = position.move(speed)

    if position.left<0 or position.right>width:
        # 翻转图形
        turtle=pygame.transform.flip(turtle,True,False)
        # 反方向移动
        speed[0] = -speed[0]

    if position.top<0 or position.bottom>height:
        speed[1] = -speed[1]
    # 填充背景
    screen.fill(bg)
    # 更新图形
    screen.blit(turtle,position)
    # 更新界面
    pygame.display.flip()

实现文本渲染展示

import pygame
import sys

# 初始化Pygame
pygame.init()

size = width,height=1200,820

# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption('mermer')

font = pygame.font.Font(None,20)
line_height = font.get_linesize()
position = 0

screen.fill((0,0,0))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # 渲染文本,消除锯齿以及颜色设置;文本位置x轴从左侧开始,即0,y轴需要知道文本的高度
        screen.blit(font.render(str(event),True,(0,255,0)),(0,position))
        position += line_height

        if position >height:
            position = 0
            screen.fill((0,0,0))
    pygame.display.flip()

【Python入门基础】Pygame实例_第1张图片
事件响应
【Python入门基础】Pygame实例_第2张图片

实现方向键操控

import pygame
import sys
from pygame.locals import *

# 初始化Pygame
pygame.init()

size = width,height=1200,820
speed=[-2,1]
bg=(255,255,255) # RGB

# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption('mermer')
# 加载图片
turtle = pygame.image.load('1.jpg')
# 获得图形的位置矩形
position = turtle.get_rect()

# 方向键控制图形转向
l_head = turtle
r_head = pygame.transform.flip(turtle,True,False)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                turtle = l_head
                speed = [-1,0]
            if event.key == K_RIGHT:
                turtle = r_head
                speed = [1,0]
            if event.key == K_UP:
                speed = [0,-1]
            if event.key == K_DOWN:
                speed = [0,1]

    # 移动图像
    position = position.move(speed)

    if position.left<0 or position.right>width:
        # 翻转图形
        turtle=pygame.transform.flip(turtle,True,False)
        # 反方向移动
        speed[0] = -speed[0]

    if position.top<0 or position.bottom>height:
        speed[1] = -speed[1]
    # 填充背景
    screen.fill(bg)
    # 更新图形
    screen.blit(turtle,position)
    # 更新界面
    pygame.display.flip()

【Python入门基础】Pygame实例_第3张图片

简单实现放缩、全屏、调整窗口等

import pygame
import sys
from pygame.locals import *

# 初始化Pygame
pygame.init()

size = width, height = 1200, 820
speed = [-2, 1]
bg = (255, 255, 255)  # RGB

# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size, RESIZABLE)
# 设置窗口标题
pygame.display.set_caption('mermer')
# 实现图形的方法缩小
oturtle = pygame.image.load('1.jpg')
turtle = oturtle
# 获得图形的位置矩形
oturtle_rect = oturtle.get_rect()
position = turtle_rect = oturtle_rect
# 设置放缩比率
ratio = 1.0

# 方向键控制图形转向
l_head = turtle
r_head = pygame.transform.flip(turtle, True, False)

# 全屏
fullscreen = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                turtle = l_head
                speed = [-1, 0]
            if event.key == K_RIGHT:
                turtle = r_head
                speed = [1, 0]
            if event.key == K_UP:
                speed = [0, -1]
            if event.key == K_DOWN:
                speed = [0, 1]
            # 全屏F11
            if event.key == K_F11:
                fullscreen = not fullscreen
                if fullscreen:
                    # 开启全屏和硬件加速
                    screen = pygame.display.set_mode(pygame.display.list_modes()[0], FULLSCREEN | HWSURFACE)
                    width, height = pygame.display.list_modes()[0]
                else:
                    screen = pygame.display.set_mode(size)
                    width, height = size
            # 放大(=)、缩小(-)、恢复(空格)
            if event.key == K_EQUALS or event.key == K_MINUS or event.key == K_SPACE:
                # 最多放大一倍,缩小50%
                if event.key == K_EQUALS and ratio < 2:
                    ratio += 0.1
                if event.key == K_MINUS and ratio > 0.5:
                    ratio -= 0.1
                if event.key == K_SPACE:
                    ratio = 1.0
                turtle = pygame.transform.smoothscale(oturtle,
                                                      (int(oturtle_rect.width * ratio),
                                                       int(oturtle_rect.height * ratio)))
        # 用户调整窗口尺寸
        if event.type == VIDEORESIZE:
            size = event.size
            width, height = size
            screen = pygame.display.set_mode(size, RESIZABLE)

    # 移动图像
    position = position.move(speed)

    if position.left < 0 or position.right > width:
        # 翻转图形
        turtle = pygame.transform.flip(turtle, True, False)
        # 反方向移动
        speed[0] = -speed[0]

    if position.top < 0 or position.bottom > height:
        speed[1] = -speed[1]
    # 填充背景
    screen.fill(bg)
    # 更新图形
    screen.blit(turtle, position)
    # 更新界面
    pygame.display.flip()

贴边飞行

import pygame
import sys
from pygame.locals import *

# 初始化Pygame
pygame.init()

size = width, height = 1200, 820
speed = [5, 0]
bg = (255, 255, 255)  # RGB

# 创建指定大小的窗口 Surface
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption('mermer')
# 实现图形的方法缩小
turtle = pygame.image.load('1.jpg')
# 获得图形的位置矩形
position = turtle.get_rect()

turtle_right = pygame.transform.rotate(turtle,90)
turtle_top = pygame.transform.rotate(turtle,180)
turtle_left = pygame.transform.rotate(turtle,270)
turtle_bottom = turtle
turtle = turtle_top


# 全屏
fullscreen = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # 移动图像
    position = position.move(speed)

    if position.right > width:
        turtle = turtle_right
        position = turtle_rect = turtle.get_rect()
        position.left = width - turtle_rect.width
        speed = [0,5]

    if position.bottom > height:
        turtle = turtle_bottom
        position = turtle_rect = turtle.get_rect()
        position.left = width - turtle_rect.width
        position.top = height-turtle_rect.height
        speed = [-5,0]

    if position.left < 0:
        turtle = turtle_left
        position = turtle_rect = turtle.get_rect()
        position.top = height-turtle_rect.height
        speed = [0,-5]

    if position.top < 0:
        turtle = turtle_top
        position = turtle_rect = turtle.get_rect()
        speed = [5,0]

    # 填充背景
    screen.fill(bg)
    # 更新图形
    screen.blit(turtle, position)
    # 更新界面
    pygame.display.flip()

基本图形绘制

import pygame
import sys
from pygame.locals import *
import math

pygame.init()

size = width,height = 640,480
bg = (0,0,0)
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)

clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)

pygame.display.set_caption('Demo')
points = [(200,75),(300,25),(400,75),(450,25),(450,125),(400,75),(300,125)]

position = size[0]//2,size[1]//2
moving = False

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                moving = True
        if event.type == MOUSEBUTTONUP:
            if event.button == 1:
                moving = False
    if moving :
        position = pygame.mouse.get_pos()

    screen.fill(WHITE)
    # 矩形(绘制区域,绘制颜色,矩形大小(确定起点和长宽),0表示填充,非0则用颜色绘制边框)
    pygame.draw.rect(screen,BLACK,(50,50,150,50),1)
    # 多边形
    pygame.draw.polygon(screen,GREEN,points,0)
    # 圆
    pygame.draw.circle(screen,RED,position,125,1)
    # 椭圆
    pygame.draw.ellipse(screen,BLACK,(100,100,440,200),1)
    # 弧线,取椭圆的一部分,需要起点和终点角度
    pygame.draw.arc(screen,BLUE,(100,300,400,200),0,math.pi,1)
    # 直线
    pygame.draw.line(screen,GREEN,(200,200),(400,400),1)
    # 第三个参数表示线段是否闭合
    pygame.draw.lines(screen,BLACK,1,points,1)
    # 查看锯齿
    pygame.draw.aaline(screen,BLACK,(200,400),(400,200),0)

    pygame.display.flip()
    # 设置帧率
    clock.tick(120)

【Python入门基础】Pygame实例_第4张图片

动画精灵

【Python入门基础】Pygame实例_第5张图片
【Python入门基础】Pygame实例_第6张图片

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


class Ball(pygame.sprite.Sprite):  # 继承动画精灵基类
    def __init__(self, imgae, position, speed, bg_size):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load(imgae).convert_alpha()
        self.rect = self.image.get_rect()  # 获得球的尺寸
        self.rect.left, self.rect.top = position  # 将出现的位置赋给球
        self.speed = speed  # 设置速度
        self.width, self.height = bg_size[0], bg_size[1]  # 获得活动边界,就是背景的边界
        self.radius = self.rect.width / 2

    def move(self):
        self.rect = self.rect.move(self.speed)  # 根据自身的速度进行移动

        if self.rect.right < 0:  # 图片的右边已经超出边界的左边,即整个球已经出界
            self.rect.left = self.width  # 让他从右边界回来
        if self.rect.bottom < 0:  # 图片的底已经超出边界的上面
            self.rect.top = self.height  # 让他从底部回来
        if self.rect.left > self.width:  # 图片的左边已经超出边界的右边
            self.rect.right = 0  # 让他从左边回来
        if self.rect.top > self.height:  # 如果图片的顶部已经超出边界的底部
            self.rect.bottom = 0  # 让他从顶部回来


def main():
    pygame.init()

    bg_image = "background.png"
    ball_image = "ball.png"

    running = True  # 为了以后而已有多种方法退出程序

    bg_size = width, height = 1024, 681  # 背景大小
    screen = pygame.display.set_mode(bg_size)  # 设置背景大小
    background = pygame.image.load(bg_image).convert_alpha()  # 画背景

    balls = []
    group = pygame.sprite.Group()  # 因为使用自带的函数需要使用自己带的组,所以这里我们创建一个

    # 创建五个小球
    BALL_NUM = 5

    for i in range(BALL_NUM):  # 生成5个球
        position = randint(0, width - 100), randint(0, height - 100)  # 要减去100是因为球图片尺寸的大小为100,随机生成位置
        speed = [randint(-10, 10), randint(-10, 10)]
        ball = Ball(ball_image, position, speed, bg_size)  # 生成球的对象
        while pygame.sprite.spritecollide(ball, group, False,
                                          pygame.sprite.collide_circle):  # 如果生成的小球和之前的球发生碰撞,那么重新生成小球
            ball.rect.left, ball.rect.top = randint(0, width - 100), randint(0, height - 100)
        balls.append(ball)  # 将所有的球对象添加到类表中,方便管理
        group.add(ball)  # 组有add()和remove()方法

    clock = pygame.time.Clock()  # 生成刷新帧率控制器

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()

        screen.blit(background, (0, 0))  # 将背景aaa画到screen上

        for each in balls:  # 每个球进行移动并重新绘制
            each.move()
            screen.blit(each.image, each.rect)

        for each in group:  # 循环5个小球,分别判断这个小球有没有和另外四个小球发生碰撞
            group.remove(each)  # 因为是判断和其他四个小球,所以需要先将这个小球取出

            if pygame.sprite.spritecollide(each, group, False,
                                           pygame.sprite.collide_circle):  # 调用碰撞检测的函数,如果结果为真,也就是有发生碰撞的小球
                each.speed[0] = - each.speed[0]  # 碰撞后向反方向运动
                each.speed[1] = - each.speed[1]
            group.add(each)  # 最后不要忘记把这个小球放回原位

        pygame.display.flip()
        clock.tick(30)


if __name__ == "__main__":
    main()

Pygame:播放声音和音效
Pygame:摩擦摩擦
Pygame:游戏胜利
Pygame:飞机大战1
Pygame:飞机大战2
Pygame:飞机大战3
Pygame:飞机大战4
Pygame:飞机大战5
Pygame:飞机大战6

你可能感兴趣的:(Python学习,python,pygame,游戏,tkinter,数学)