Day_19-pygame和多线程

一、pygame

游戏事件
1.鼠标事件:
MOUSEBUTTONDOWN - 鼠标按下
MOUSEBUTTONUP - 鼠标弹起
MOUSEMOTION - 鼠标移动

重点:事件发生的位置: event.pos
方法:event.pos
含义:鼠标的坐标
返回值:元祖(坐标x, y)

2.键盘事件
KEYDOWN - 键盘按下
KEYUP - 键盘弹起

重点:按了哪个键
方法:event.key
返回值:按键对应的字符的编码值

# 模块的导入
import pygame
from color import Color
from random import randint

pygame.init()
window = pygame.display.set_mode((400, 600))
pygame.display.set_caption('事件')
window.fill(Color.white)

pygame.display.flip()
is_move = False
while True:

    # 不断检测是否有事件产生,如果有事件产生才会进入for循环
    for event in pygame.event.get():
        # 这儿的event是事件对象,我们可以通过事件对象的type值来判断事件的类型
        #==================鼠标事件===================
        if event.type == pygame.QUIT:
            exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 鼠标按下要做什么,就将代码写这个if语句中
            print('鼠标按下', event.pos)
            # pygame.draw.circle(window, Color.random_color(), event.pos, randint(10, 20))
            # pygame.display.update()
            is_move = True
        elif event.type == pygame.MOUSEBUTTONUP:
            # 鼠标弹起要做什么,就将代码写这个if语句中
            print('鼠标弹起')
            is_move = False
        elif event.type == pygame.MOUSEMOTION:
            # 鼠标移动要做什么, 就将代码写这个if语句中
            if is_move:
                pygame.draw.circle(window, Color.random_color(), event.pos, 20)
                pygame.display.update()
                print('鼠标移动')

        # ================键盘事件=================
        if event.type == pygame.KEYDOWN:
            print('按键被按下')
            print(event.key, chr(event.key))
        elif event.type == pygame.KEYUP:
            print('按键弹起!')

颜色脚本:color模块

from random import randint


class Color:
    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    green = (0, 255, 255)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    gray = (155, 155, 155)

    @staticmethod
    def random_color():
        return randint(0, 255), randint(0, 255), randint(0, 255)

按钮:

import pygame
from color import Color
from random import randint


class Button:
    """声明一个按钮类"""
    def __init__(self, x, y, width, height, text='', background_color=Color.red, text_color=Color.white):
        # 按钮的x坐标
        self.x = x
        # 按钮的y坐标
        self.y = y
        # 按钮的宽度
        self.width = width
        # 按钮的长度
        self.height = height
        # 按钮的显示内容
        self.text = text
        # 按钮的背景颜色
        self.background_color = background_color
        # 显示内容的颜色
        self.text_color = text_color
        # 按钮的字体大小
        self.font_size = 30

    def show(self, window):
        """将按钮显示在屏幕上"""
        # 画一个矩形,然后显示在屏幕上
        pygame.draw.rect(window, self.background_color, (self.x, self.y, self.width, self.height))
        # 创建一个字体对象
        font = pygame.font.SysFont('Times', self.font_size)
        # 根据字体创建一个文字对象
        text = font.render(self.text, True, self.text_color)
        # 获取文字对象的大小
        w, h = text.get_size()
        # 获取显示在屏幕上的x坐标
        x = self.width / 2 - w / 2 + self.x
        # 获取显示在屏幕上的y坐标
        y = self.height / 2 - h / 2 + self.y
        # 将文字显示在屏幕上
        window.blit(text, (x, y))

    def is_cliecked(self, pos):
        """根据传入的坐标判断是否在范围内"""
        # 获取传入坐标的x,y值
        x, y = pos
        # 返回点击鼠标的位置,是否反应
        return (self.x <= x <= self.x + self.width) and (self.y <= y <= self.y + self.height)


def main():
    # 初始化窗口
    pygame.init()
    # 创建一个窗口
    window = pygame.display.set_mode((400, 600))
    # 设置窗口标题
    pygame.display.set_caption('事件')
    # 设置窗口的背景颜色
    window.fill(Color.white)

    # add_btn(window)
    # 创建一个按钮对象
    add_btn = Button(100, 100, 100, 50, 'del')
    # 将对象显示在屏幕上
    add_btn.show(window)
    # 创建第二个按钮对象
    btn2 = Button(100, 250, 100, 60, 'Score', background_color=Color.yellow, text_color=Color.black)
    # 将第二个对象显示在屏幕上
    btn2.show(window)
    # 将修改过的内容有效显示
    pygame.display.flip()
    is_move = False
    while True:
        # 不断检测事件的发生,有事件就进入for循环
        for event in pygame.event.get():
            # 将窗口关闭
            if event.type == pygame.QUIT:
                exit()
            # 鼠标按下要做的事情
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 鼠标点击的坐标
                mx, my = event.pos
                # 如果点击的坐标在按钮范围内,要发生的事情
                if add_btn.is_cliecked(event.pos):
                    print('删除!')
                    # 继续下一次事件的判断
                    continue
                # 如果点击的坐标在第二个按钮的范围内,要发生的事情
                if btn2.is_cliecked(event.pos):
                    # print('hello')
                    # 更改按钮要显示的内容
                    btn2.text = str(randint(0, 100))
                    # 重新展示在屏幕上
                    btn2.show(window)
                    # 在屏幕上更新修改的内容
                    pygame.display.update()
                    # 继续下一次事件的判断
                    continue



if __name__ == '__main__':
    main()

小球的移动控制:


import pygame
from color import Color
from random import randint

window_width = 400
window_height = 600

class Direction:
    """方向类"""
    UP = 273
    DOWN = 274
    RIGHT = 275
    LEFT = 276


class Ball:
    def __init__(self, center_x, center_y, radius, bg_color=Color.random_color()):
        self.center_x = center_x
        self.center_y = center_y
        self.radius = radius
        self.bg_color = bg_color
        self.is_move = True   # 是否移动
        self.move_direction = Direction.DOWN
        self.speed = 5

    def disappear(self, window):
        """
        球从指定界面消失
        :param window:
        :return:
        """
        pygame.draw.circle(window, Color.white, (self.center_x, self.center_y), self.radius)

    def show(self, window):
        """
        小球显示
        :param window:
        :return:
        """
        pygame.draw.circle(window, self.bg_color, (self.center_x, self.center_y), self.radius)

    def move(self, window):
        """
        小球移动
        :param window:
        :return:
        """
        # 让移动前的球消失
        self.disappear(window)
        if self.move_direction == Direction.DOWN:
            self.center_y += self.speed
        elif self.move_direction == Direction.UP:
            self.center_y -= self.speed
        elif self.move_direction == Direction.LEFT:
            self.center_x -= self.speed
        else:
            self.center_x += self.speed

        # 移动后重新显示球
        self.show(window)

    @classmethod
    def creat_enemy_ball(cls):
        r = randint(10, 25)
        x = randint(r, int(window_width - r))
        y = randint(r, int(window_height - r))
        enemy = cls(x, y, r, Color.random_color())
        enemy.is_move = False
        return enemy


def main():
    pygame.init()
    window = pygame.display.set_mode((window_width, window_height))
    pygame.display.set_caption('事件')
    window.fill(Color.white)

    # 先显示一个的球
    ball = Ball(100, 100, 30)
    ball.show(window)

    pygame.display.flip()
    # 计时
    time = 0
    # 所有被吃的球
    all_enemy = []
    while True:
        time += 1

        # 每隔100个运行单位移动一次
        if time % 100 == 0:
            if ball.is_move:
                # 让球动起来
                ball.move(window)
                pygame.display.update()

        if time == 10000:
            time = 0
            enemy = Ball.creat_enemy_ball()
            all_enemy.append(enemy)
            enemy.show(window)


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == Direction.DOWN or event.key == Direction.UP or event.key == Direction.LEFT or event.key == Direction.RIGHT:
                    # ball.is_move = True
                    ball.move_direction = event.key
            elif event.type == pygame.KEYUP:
                if event.key == Direction.DOWN or event.key == Direction.UP or event.key == Direction.LEFT or event.key == Direction.RIGHT:
                    # ball.is_move = False
                    pass



if __name__ == '__main__':
    main()    

小球游戏:

import pygame
from color import Color
from random import randint

window_height = 600
window_width = 400


class Ball:
    def __init__(self, center_x, center_y, radius, bg_color=Color.random_color()):
        self.center_x = center_x
        self.center_y = center_y
        self.radius = radius
        self.bg_color = bg_color
        self.is_move = True
        self.y_speed = 6

    def move(self, window):
        self.disapper(window)
        new_y = self.center_y + self.y_speed
        if new_y >= window_height - self.radius:
            new_y = window_height - self.radius
            self.y_speed *= -1

        if new_y <= self.radius:
            new_y = self.radius
            self.y_speed *= -1

        self.center_y = new_y

        self.show(window)


    def disapper(self, window):
        pygame.draw.circle(window, Color.white, (self.center_x, self.center_y), self.radius)

    def show(self, window):
        pygame.draw.circle(window, self.bg_color, (self.center_x, self.center_y), self.radius)


def main():

    pygame.init()
    window = pygame.display.set_mode((window_width, window_height))
    pygame.display.set_caption('事件')
    window.fill(Color.white)

    ball = Ball(100, 100, 20)
    ball.show(window)
    pygame.display.flip()
    time = 0
    while True:
        time += 1
        if time % 1000 ==0:
            if ball.is_move:
                ball.move(window)
                pygame.display.update()

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


if __name__ == '__main__':
    main()

二、多线程技术

进程:一个正在运行的应用程序
主线程:在默认情况下,一个进程有且只有一个线程
一个进程中允许有多个线程同时对不同任务进行处理
应用场景:耗时操作

python内置标准库:threading
Thread:threading中的线程类
如何提供一个子线程
直接创建一个线程对象
(需要一个子线程就创建一个Thread类的对象)

方法一、通过Thread类直接创建子线程

import time
from datetime import datetime
# python多线程技术对应的模块
import threading

def download(file):
    print('%s开始下载' % file, datetime.now())
    # sleep(时间)  - 程序执行到这个位置等待指定的时候再接着往后面执行
    time.sleep(10)
    print('%s下载结束' % file, datetime.now())


def main():
    print('程序开始')
    # print(datetime.now())
    # 1.在主线程中下载三个电影 (总耗时30s)
    # download('枪王之王.mp4')
    # download('开国大典')
    # download('黄金国.mp4')

    # 2.在三个子线程中同时下载三个电影
    """
    Thread(target,args)   -  创建子线程对象
    说明:
    target - Function,需要传一个函数(这个函数中的内容会在子线程中执行)
    args - 元祖,target对应的函数的参数
    当通过创建好的子线程对象调用start方法的时候,会自动在子线程中调用target对应的函数, 并且将args中值作为实参
    """
    # 创建线程对象
    t1 = threading.Thread(target=download, args=('枪王之王.mp4',))
    t2 = threading.Thread(target=download, args=('开国大典.mp4',))
    t3 = threading.Thread(target=download, args=('黄金国.mp4',))

    # 开始执行t1对应的子线程中的任务(实质就是在子线程中调用target对应的函数)
    t1.start()
    t2.start()
    t3.start()

    print('=============')


if __name__ == '__main__':
    main()

方法二、创建一个子类继承Thread线程类,从而实现自己的线程类

创建子类的步骤
1.声明类继承Thread
2.重写run方法。
目的:任务就是需要在子线程中执行的任务
3.需要线程对象的时候,创建当前声明的类的对象
4.通过线程对象.start方法在子线程中去执行run方法中的任务

import threading
import time as time1
from datetime import time

class DownloadThread(threading.Thread):
    """下载类"""
    def __init__(self, file):
        super().__init__()
        self.file = file

    def run(self):
        print('开始下载:'+self.file)
        print('run:', threading.current_thread())
        time1.sleep(10)
        print('%s下载结束' % self.file)


def main():
    # 获取当前线程
    print(threading.current_thread())

    t1 = DownloadThread('沉默的羔羊.mp4')
    t2 = DownloadThread('恐怖游轮.mp4')
    # 调用start的时候会自动在子线程中调用run方法
    t1.start()
    t2.start()
    # 注意:如果直接用对象调用run方法,run方法中的任务会在主线程执行
    # t1.run()


if __name__ == '__main__':
    main()
from threading import Thread
import requests
import re
import time
from random import randint


class DownloadThread2(Thread):
    """下载类"""
    def __init__(self, file, time):
        super().__init__()
        self.file = file
        self.time = time

    def run(self):
        print('开始下载:'+self.file)
        # t = randint(5, 10)
        time.sleep(self.time)
        print('%s下载结束, 总共耗时:%ds' % (self.file, self.time))


class DownloadImageThread(Thread):
    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        # 开始下载
        file_name = re.split(r'/', self.url)[-1]
        print(file_name)
        print('%s开始下载' % file_name)
        response = requests.get(self.url)
        content = response.content

        with open('images/'+file_name, 'bw') as f:
            f.write(content)

        print('%s下载结束' % file_name)


def creat_thread():
    t1 = DownloadThread2('电影1', 6)
    t2 = DownloadThread2('电影2', 4)
    t1.start()
    t2.start()
    # 线程对象调用join方法,会导致join后的代码会在线程中的任务结束后才执行
    t1.join()
    t2.join()
    print('电影下载结束!')


def main():
    # t1 = DownloadImageThread('https://image.haha.mx/2015/12/04/middle/2082175_c5c3cc05eb73e4023149e663475d3ab4_1449192201.gif')
    # t1.start()
    #
    # t2 = DownloadImageThread('http://img4.imgtn.bdimg.com/it/u=534897622,845095650&fm=26&gp=0.jpg')
    # t2.start()

    t0 = Thread(target=creat_thread)
    t0.start()

    print('========')
    for x in range(100):
        time.sleep(1)
        print(x)


if __name__ == '__main__':
    main()

你可能感兴趣的:(Day_19-pygame和多线程)