Python趣味挑战之pygame实现无敌好看的百叶窗动态效果

一、案例知识点概述

(一)使用到的python库

使用pygame库、random库和os、sys等系统库。

其中:
pygame库实现主体功能,提供窗口界面显示、动态效果展示等
random库实现随机数的生成,通过随机数实现动态百叶窗的上下左右选择、百叶窗的数量选择等功能。 os库实现图片资源的装载和读取。
sys库实现退出操作等。

(二) 整体实现逻辑

通过WIDTH = 600HEIGHT = 600设置窗口的高度和宽度
通过runimagenextimage 设置当前显示的图像和下一张要显示的图像
通过num_part = random.randint(3,8)来设置要显示的百叶窗的数量
通过num_list = []保存当前runimage拆分出来的百叶窗的surface资源,用于在百叶窗动态效果过程中显示。
通过choose来设置是上下运动还是左右运动。

二、准备工作

(一)实现pygame的主窗口

import pygame,sys

pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('大小框展示')
fcclock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT or event.type == pygame.K_F1:
            pygame.quit()
            sys.exit()
    fcclock.tick(60)
    pygame.display.flip()  # 刷新窗口

黑黑的框,不截图了。大家都懂。

(二)贴个图显示得好看点

import pygame,sys

pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('大小框展示')
fcclock = pygame.time.Clock()
img = pygame.image.load('./image/aerial-alpine-ceresole-reale-desktop-backgrounds-1562.jpg').convert_alpha()
img = pygame.transform.scale(img, (500, 500))
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT or event.type == pygame.K_F1:
            pygame.quit()
            sys.exit()
    screen.blit(img,(0,0))
    fcclock.tick(60)
    pygame.display.flip()  # 刷新窗口

(三)图片从哪里来

这里建议直接通过网络上下载免费的、好看的图片,并保存在指定的文件夹,用于过程中展现。

我认为有三种方法:

其一:使用爬虫技术从网上下载图片,可以开一个子线程负责采集网上图片,然后加载到list列表中;
其二:可以直接对电脑中所有的盘进行自动检索,然后加载到list列表中; 其三:指定目录,然后加载到list列表中;
我这里偷个懒,选择第三种方法实现。

具体实现代码如下:

  path = './image/'
    files = []
    dirs = os.listdir(path)
    for diretion in dirs:
        files.append(path + diretion)

(四)图片装载

我为什么在初始化的时候就进行装载呢?

原因是:解决效率问题,无需每次使用时重复加载,而且在初始化的时候就适配屏幕大小进行图片缩放。

因此,我把这个过程打包成一个函数,方便后续调用,而且参数传递为:屏幕的大小。然后返回bglist对象。

for file in files:
    picture = pygame.transform.scale(pygame.image.load(file), (1440, 900))
    dSurface = picture
    # dSurface = pygame.image.load(file).convert()
    bglist.append(dSurface)

OK,图片有了,窗口有了,那么就开始实现我们的业务逻辑吧。

三、核心功能模块

(一)实现init_image函数初始化加载图片到surface对象

def init_image():
    path = './image/'
    files = []
    dirs = os.listdir(path)
    for diretion in dirs:
        files.append(path + diretion)

    for file in files:
        picture = pygame.transform.scale(pygame.image.load(file), (WIDTH, HEIGHT))
        dSurface = picture
        # dSurface = pygame.image.load(file).convert()
        bglist.append(dSurface)

(二)初始化相关变量

runimage = None
nextimage = None
flag = False   # FALSE没有切屏 TRUE 切屏
flag2 = False
choose = 6

num_part = random.randint(3,8)  # 记录分成多少块矩形框
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse<=num_part:
    inc = -inc
    num_list.append(inc)
    num_increse += 1

这里,建议大家思考一下为什么要引入变量flag和flag2

(三)每次百叶窗切换完之后重置

def reset():
    global flag,runimage,nextimage,flag2,i,j,choose,num_part,num_list
    flag = False  # FALSE没有切屏 TRUE 切屏
    flag2 = False
    choose = random.randint(6,7)
    if nextimage is None:
        nextimage = random.choice(bglist)
    if runimage is None:
        runimage = random.choice(bglist)
    else:
        runimage = nextimage
        nextimage = random.choice(bglist)

    num_part = random.randint(3,8)  # 记录分成多少块矩形框
    num_list = []
    num_increse = 1
    inc = random.choice([-1,1])
    while num_increse <= num_part:
        inc = -inc
        num_list.append(inc)
        num_increse += 1

(四)实现百叶窗动态切换的run函数

def run():
    global flag,runimage,flag2,nextimage,i,j,choose,num_part,num_list
    reset()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or event.type == pygame.K_F1:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_SPACE:
                    if flag is False:# FALSE没有切屏 TRUE 切屏
                        flag = True
                        flag2 = False
        screen.fill((255, 255, 255))  # 设置背景为白色
        if flag:
            if choose==6:
                select_rect = []
                kk = 0
                while kk < num_part:
                    tmp_rect = pygame.Rect(kk * WIDTH/num_part,0,WIDTH/num_part,HEIGHT)
                    select_rect.append(runimage.subsurface(tmp_rect).copy())
                    kk += 1
                screen.blit(nextimage, (0, 0))
                mm = 0
                for each in zip(select_rect,num_list):
                    if each[1]==1:
                        screen.blit(each[0], (i+mm*WIDTH/num_part, -j))
                    else:
                        screen.blit(each[0], (i+mm*WIDTH/num_part, j))
                    mm += 1
                j += step
                if j >= HEIGHT:
                    flag2 = True
            elif choose==7:
                select_rect = []
                kk = 0
                while kk < num_part:
                    tmp_rect = pygame.Rect(0,kk * HEIGHT/num_part,WIDTH,HEIGHT/num_part)
                    select_rect.append(runimage.subsurface(tmp_rect).copy())
                    kk += 1
                screen.blit(nextimage, (0, 0))
                mm = 0
                for each in zip(select_rect,num_list):
                    if each[1]==1:
                        screen.blit(each[0], (-i, j+mm*HEIGHT/num_part))
                    else:
                        screen.blit(each[0], (i, j+mm*HEIGHT/num_part))
                    mm += 1
                i += step
                if i >= WIDTH:
                    flag2 = True
        else:
            screen.blit(nextimage, (0, 0))
            screen.blit(runimage, (0, 0))
        if flag2:
            reset()
        fcclock.tick(fps)
        pygame.display.flip()  # 刷新窗口

(五)主函数

if __name__ == '__main__':
    init_image()
    run()

四、完整代码

import sys, pygame
import os
import random

pygame.init()  # 初始化pygame类
WIDTH = 600
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))  # 设置窗口大小
pygame.display.set_caption('美丽的屏保')  # 设置窗口标题
tick = pygame.time.Clock()
fps = 60  # 设置刷新率,数字越大刷新率越高
fcclock = pygame.time.Clock()
runimage = None
nextimage = None
flag = False   # FALSE没有切屏 TRUE 切屏
flag2 = False
choose = 6

num_part = random.randint(3,8)  # 记录分成多少块矩形框
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse<=num_part:
    inc = -inc
    num_list.append(inc)
    num_increse += 1

def init_image():
    path = './image/'
    files = []
    dirs = os.listdir(path)
    for diretion in dirs:
        files.append(path + diretion)

    for file in files:
        picture = pygame.transform.scale(pygame.image.load(file), (WIDTH, HEIGHT))
        dSurface = picture
        bglist.append(dSurface)

def reset():
    global flag,runimage,nextimage,flag2,i,j,choose,num_part,num_list
    flag = False  # FALSE没有切屏 TRUE 切屏
    flag2 = False
    i = 0
    j = 0
    choose = random.randint(6,7)
    if nextimage is None:
        nextimage = random.choice(bglist)
    if runimage is None:
        runimage = random.choice(bglist)
    else:
        runimage = nextimage
        nextimage = random.choice(bglist)

    num_part = random.randint(3,8)  # 记录分成多少块矩形框
    num_list = []
    num_increse = 1
    inc = random.choice([-1,1])
    while num_increse <= num_part:
        inc = -inc
        num_list.append(inc)
        num_increse += 1

def run():
    global flag,runimage,flag2,nextimage,i,j,choose,num_part,num_list
    reset()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or event.type == pygame.K_F1:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_SPACE:
                    if flag is False:# FALSE没有切屏 TRUE 切屏
                        flag = True
                        flag2 = False
        screen.fill((255, 255, 255))  # 设置背景为白色
        if flag:
            if choose==6:
                select_rect = []
                kk = 0
                while kk < num_part:
                    tmp_rect = pygame.Rect(kk * WIDTH/num_part,0,WIDTH/num_part,HEIGHT)
                    select_rect.append(runimage.subsurface(tmp_rect).copy())
                    kk += 1
                screen.blit(nextimage, (0, 0))
                mm = 0
                for each in zip(select_rect,num_list):
                    if each[1]==1:
                        screen.blit(each[0], (i+mm*WIDTH/num_part, -j))
                    else:
                        screen.blit(each[0], (i+mm*WIDTH/num_part, j))
                    mm += 1
                j += step
                if j >= HEIGHT:
                    flag2 = True
            elif choose==7:
                select_rect = []
                kk = 0
                while kk < num_part:
                    tmp_rect = pygame.Rect(0,kk * HEIGHT/num_part,WIDTH,HEIGHT/num_part)
                    select_rect.append(runimage.subsurface(tmp_rect).copy())
                    kk += 1
                screen.blit(nextimage, (0, 0))
                mm = 0
                for each in zip(select_rect,num_list):
                    if each[1]==1:
                        screen.blit(each[0], (-i, j+mm*HEIGHT/num_part))
                    else:
                        screen.blit(each[0], (i, j+mm*HEIGHT/num_part))
                    mm += 1
                i += step
                if i >= WIDTH:
                    flag2 = True
        else:
            screen.blit(nextimage, (0, 0))
            screen.blit(runimage, (0, 0))
        if flag2:
            reset()
        fcclock.tick(fps)
        pygame.display.flip()  # 刷新窗口

if __name__ == '__main__':
    init_image()
    run()

五、运行效果

OK,写完,其实还是蛮有趣的,大家可以自动动手敲敲,也许比我写的更好。

到此这篇关于Python趣味挑战之pygame实现无敌好看的百叶窗动态效果的文章就介绍到这了,更多相关pygame实现百叶窗动态效果内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python实现五子棋游戏(pygame版)

    本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 目录 简介 实现过程 结语 简介 使用python实现pygame版的五子棋游戏: 环境:Windows系统+python3.8.0 游戏规则: 1.分两位棋手对战,默认黑棋先下:当在棋盘点击左键,即在该位置绘制黑棋: 2.自动切换到白棋,当在棋盘点击左键,即在该位置绘制白棋: 3.轮流切换棋手下棋,当那方先形成5子连线者获胜(横.竖.斜.反斜四个方向都可以). 游戏运行效果如下: 实现过程 1.新建文件settin

  • python基于pygame实现飞机大作战小游戏

    基于pygame的飞机大作战小游戏,适合新手,不能直接运行,只能在命令行进入当前游戏目录,输入python game.py才能够运行,尚不知道是什么原因. 游戏截图如下,我们用黄色的圆圈代表敌机: 代码如下 import pygame,sys,time,random,math def init(): pygame.init() size = width, height =600,600 screen =pygame.display.set_mode(size) plx=270 ply=528 b

  • python pygame实现2048游戏

    实现2048相对来说比较简单,用4*4的二维数组保存地图,pygame.key.get_pressed()获取键盘操作,详见代码. 效果图 代码 # -*- coding: utf-8 -*- #!/usr/bin/python ''' Created on May 31, 2014 @author: yuanzi ''' import random import sys import pygame from pygame.locals import * PIXEL = 150 SCORE_PI

  • 使用Python第三方库pygame写个贪吃蛇小游戏

    今天看到几个关于pygame模块的博客和视频,感觉非常有趣,这里照猫画虎写了一个贪吃蛇小游戏,目前还有待完善,但是基本游戏功能已经实现,下面是代码: # 导入模块 import pygame import random # 初始化 pygame.init() w = 720 #窗口宽度 h = 600 #窗口高度 ROW = 30 #行数 COL = 36 #列数 #将所有的坐标看作是一个个点,定义点类 class Point: row = 0 col = 0 def __init__(self

  • python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)

    python+pygame实现坦克大战小游戏-可以自定义子弹速度: 运行环境–python3.7.pycharm: 源码需要请:点赞留言邮箱: 正常版子弹速度: 普通速度版 加速版子弹速度: 子弹加速版 另外还有多种道具,支持两人一起玩.main()方法如下: def main(): pygame.init() pygame.mixer.init() resolution = 630, 630 screen = pygame.display.set_mode(resolution) pygame

  • python pygame模块编写飞机大战

    本文实例为大家分享了python pygame模块编写飞机大战的具体代码,供大家参考,具体内容如下 该程序没有使用精灵组,而是用列表存储对象来替代精灵组的动画效果.用矩形对象的重叠来判断相撞事件.该程序可以流畅运行,注释较为详细,希望可以帮助大家. import pygame from pygame.locals import * from sys import exit import time import random # 创建子弹类,把子弹的图片转化为图像对象,设定固定的移动速度 clas

  • python pygame实现球球大作战

    本文实例为大家分享了python pygame球球大作战的具体代码,供大家参考,具体内容如下 球球大作战:(大球吃小球,代码如下:) from random import randint,randrange import pygame from math import sqrt,pi class Ball(object): def __init__(self, center, color, radius, sx, sy): self._center = center self._color =

  • Python趣味挑战之用pygame实现简单的金币旋转效果

    一.实现逻辑 step1.保存图像到list列表. step2.在主窗口每次显示一张list列表中的对象. 呵呵,好像就这么简单.所以,主要还是要有图片. 这里也分享一下图片给大家. 二.核心逻辑代码解析 (一)加载图像到list列表 def init_image(): path = './score/' files = [] dirs = os.listdir(path) for diretion in dirs: files.append(path + diretion) for file

  • Python 中的pygame安装与配置教程详解

    安装软件环境及版本说明 OS: Win10 x 64 专业版 Python: 2.7 IDE: PyCharm Community 2018 1. 安装python 1)下载并安装python python官网下载需要的版本,并安装(安装过程很简单,步骤略) https://www.python.org/downloads/windows/ 这里下载的是python2.7 2)配置环境变量 如果安装python时,没有勾选添加python到环境变量PATH,则需要手动添加 3)验证是否安装+配置

  • 使用python和pygame制作挡板弹球游戏

    python是个很有趣的语言,可以在cmd命令窗口运行,还有很多的功能强大的模块. 学了一天pygame,用python和pygame写一个简单的挡板弹球游戏. 2018年6月21日 00:15:21 GitHub: EasyBaffleBallGame # -*- coding:utf-8 -*- from sys import exit import pygame from pygame.locals import * pygame.init() # 创建窗口 ScreenWidth = 5

随机推荐