day19.pygame 和多线程

一个网站的图片一会用
https://new.qq.com/omn/20190117/20190117A0P6J0.html?pgv_ref=aio2015&ptlang=2052

"""author = drh"""

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):
        self.x = x
        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 = self.width / 2 - w / 2 + self.x
        y = self.height / 2 - h / 2 + self.y
        window.blit(text, (x, y))

    def is_cliecked(self, pos):
        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 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()

"""author = drh"""

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()

"""author =drh"""

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()

"""author = drh"""

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

"""
默认情况下,一个进程有且只有一个线程,这个线程叫主线程

threading模块中的Thread类就是线程类,这个类的对象就是线程对象,一个线程对象对应一个子线程。
(需要一个子线程就创建一个Thread类的对象)

"""


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()

"""author = drh"""

import threading
import time as time1
from datetime import time

"""
可以通过写一个类继承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())
        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()

"""author = drh"""

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()

"""author = drh"""

单独封装了一个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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,688评论 0 10
  • 8月22日-----字符串相关 2-3 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消...
    future_d180阅读 923评论 0 1
  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 5,770评论 2 16
  • 孙丽 焦点网络初级十期 息县坚持分享第86天 孩子一天天长大, 但无论怎样长他们在父母眼中永远都是孩子。 我们总觉...
    孙丽_cdb3阅读 208评论 0 0
  • 暑假第23天 今天继续无力,药是按时吃了,可饭没吃好,实在没有力气做饭,一天都是糊弄过去的,连累呵呵跟着我也没吃好...
    子夜_2018阅读 140评论 0 1