2019-01-18

Day19

一、 事件

import pygame
import color
import random

游戏中的事件
1、 鼠标相关的事件
鼠标事件要关注事件发生的位置:event.pos ---- 鼠标的坐标,元组
2、 键盘相关的事件
键盘事件要关注哪个键被按了:event.key --- 按键对应的字符的编码,数字


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

    pygame.display.flip()
    is_move = False
    while True:
        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.Color.rand_colore(),event.pos,random.randint(10,20))
                pygame.display.update()
                is_move = True
            elif event.type == pygame.MOUSEBUTTONUP:
                print('鼠标弹起')
                is_move = False
            elif event.type == pygame.MOUSEMOTION:
                # 鼠标移动要做什么,就将代码写在这个if语句中
                if is_move:
                    print('鼠标移动')
                pass
            # 键盘事件
            if event.type == pygame.KEYDOWN:
                print('按键被按下')
                print(event.key, chr(event.key))
            elif event.type == pygame.KEYUP:
                print('按键弹起')

if __name__ == '__main__':
    main()

二、 按钮

import pygame
import color
import random

class Button:
    def __init__(self, x, y, width,height,text,background_color,txt_color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text
        self.background_color = background_color
        self.txt_color = txt_color



    def add_btn(window):
        pygame.draw.rect(window, color.Color.gray, (100, 100, 100, 60))
        font = pygame.font.SysFont('Times', 30)
        text = font.render('add', True, color.Color.yellow)
        w, h = text.get_size()
        x = 100 / 2 - w / 2 + 100
        y = 60 / 2 - h / 2 + 100
        window.blit(text, (x, y))


def main():
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    pygame.display.set_caption('事件')
    window.fill((color.Color.white))
    add_btn(window)
    pygame.display.flip()
    is_move = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = event.pos
                if (100 <= mx <= 100 + 100) and (100 <= my <= 100 + 60):
                    print('add')


if __name__ == '__main__':
    main()

三、 移动

import pygame
import color
import random


class Direction:
    UP = 273
    DOWN = 274
    RIGHT = 275
    LEFT = 276


class Ball:
    def __init__(self, center_x, center_y, radius, bg_color=color.Color.rand_colore()):
        self.center_x = center_x
        self.center_y = center_y
        self.radius = radius
        self.bg_color = bg_color
        self.is_move = False # 是否移动
        self.move_direction = Direction.DOWN

    def disappear(self, window):
        pygame.draw.circle(window,color.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 move(self, window):
        self.disappear(window)
        if self.move_direction == Direction.DOWN:
            self.center_y += 1
        elif self.move_direction == Direction.UP:
            self.center_y -= 1
        elif self.move_direction == Direction.RIGHT:
            self.center_x += 1
        else:
            self.center_x -= 1
        self.show(window)


def main():
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    pygame.display.set_caption('事件')
    window.fill((color.Color.white))
    ball = Ball(100, 100, 30)
    ball.show(window)
    pygame.display.flip()

    while True:
        if ball.is_move:
            ball.move(window)
            pygame.display.update()
        for event in pygame.event.get():
            # 这儿的event是事件对象,通过事件对象的type值来判断事件的类型
            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.RIGHT or event.key == Direction.LEFT :
                    ball.move_direction = event.key
                    ball.is_move = True
            elif event.type == pygame.KEYUP:
                if event.key == Direction.DOWN or event.key == Direction.UP or event.key == Direction.RIGHT or event.key == Direction.LEFT :
                    ball.is_move = False




if __name__ == '__main__':
    main()

四、 线程-耗时操作

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

默认情况下,一个进程有且只有一个线程,这个线程叫主线程
threading 模块中的Thread类就是线程类,这个类的对象就是线程对象,一个线程对象对应一个子线程
需要一个子线程就创建一个Thread类的对象

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


def main():
    print('程序开始')

    print(datetime.now())
    # 1、 在主线程中下载
    download('qwerty')

    # 2、 在三个子线程中同时下载三个
    """
    hread(target, args)  ---  创建子线程对象
    targeet ---  Function,需要传一个函数
    args ---  tuple,target对应的函数的参数
    当通过创建好的子线程对象调用start方法的时候,会自动在子线程中调用target对应的函数,
    并且将args中值作为实参。
    
    """
    t1 = threading.Thread(target=download, args=('湮灭',))
    t2 = threading.Thread(target=download, args=('海王',))
    t3 = threading.Thread(target=download, args=('死侍',))
    # 开始执行t1对应的子线程中的任务(实质就是在子线程中调用target对应的函数)

    t1.start()
    t2.start()
    t3.start()

    print(datetime.now())



if __name__ == '__main__':
    main()

五、 Thread子类

import threading
import time as time1
from datetime import time
import requests

可以通过写一个类继承Thread类,来创建属于自己的线程类
1、 声明类继承Thread
2、 重写run方法。这个方法中的人任务就是需要在子线程中执行的任务
3、 需要线程对象的时候,创建当前声明的类的对象;然后通过start方法在子线程中去执行run方法中的任务

class DownloadThread(threading.Thread):
    """下载类"""
    def __init__(self, file):
        super().__init__()
        self.file = file
    def run(self):
        print('开始下载:'+ self.file)
        print('run:',threading.current_thread())
        print('run方法中的代码')


def main():
    print(threading.current_thread())


    # 注意:如果直接用对象调用run方法,run方法中的任务会在主线程执行
    #  t1.run()
    # 调用start的时候会自动在子线程中调用run方法
    t1 = DownloadThread('湮灭')
    t2 = DownloadThread('死侍')
    t1.start()
    t2.start()

if __name__ == '__main__':
    main()

六、 join方法

import threading
import time as time1
from datetime import time
import requests


class DownloadThread(threading.Thread):
    """下载类"""

    def __init__(self, file):
        super().__init__()
        self.file = file

    def run(self):
        print('开始下载:' + self.file)
        print('run:', threading.current_thread())
        print('run方法中的代码')

class Credit_thread:
    t1 = DownloadThread('湮灭')
    t2 = DownloadThread('死侍')
    t1.start()
    t2.start()
    # 线程对象调用join方法,会导致join后的代码会在线程中的任务结束后才执行
    t1.join()
    t1.join()
    print('下载结束')

def main():
    t0 = threading


if __name__ == '__main__':
    main()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,175评论 1 32
  • 进程和线程 进程 所有运行中的任务通常对应一个进程,当一个程序进入内存运行时,即变成一个进程.进程是处于运行过程中...
    胜浩_ae28阅读 5,189评论 0 23
  • 这是一篇对Run Loop开发文档《Threading Program Guide:Run Loops》的翻译,来...
    鸿雁长飞光不度阅读 3,730评论 3 29
  • 进程和线程 进程 所有运行中的任务通常对应一个进程,当一个程序进入内存运行时,即变成一个进程.进程是处于运行过程中...
    小徐andorid阅读 2,883评论 3 53
  • 基本上我已经把全书翻得七七八八了。总体来说,这本书读起来并不轻松,不光是托着它读手臂有些累,而且读的过程中还需要时...
    陆海华阅读 451评论 0 2