2018-07-30 day11 Pygame進階

pygame模塊補充

import pygame
from random import randint as rdi

def randcol():
    return (rdi(0, 255), rdi(0, 255), rdi(0, 255))

def main():
    pygame.init()
    # 設(shè)置標題
    pygame.display.set_caption('event')
    screen = pygame.display.set_mode((700, 350))
    screen.fill((255, 255, 255))
    pygame.display.flip()
    '''
    QUIT:關(guān)閉按鈕被點擊事件
    MOUSEBUTTONDOWN:鼠標按下事件
    MOUSEBUTTONUP:鼠標彈起事件
    MOUSEMOTION:鼠標移動事件
    KEYDOWN:鍵盤按下
    KEYUP:鍵盤彈起
    '''
    while True:
        # 每次循環(huán)檢測有沒有事件發(fā)生
        clo = (rdi(0, 255), rdi(0, 255), rdi(0, 255))
        for evt in pygame.event.get():
            # 不同類型的事件對應(yīng)得type值不一樣
            if evt.type == pygame.QUIT:
                exit()
            if evt.type == pygame.MOUSEBUTTONDOWN:
                screen.fill(clo)
                pygame.display.flip()
            if evt.type == pygame.MOUSEBUTTONUP:
                print('mouseup')
            if evt.type == pygame.MOUSEMOTION:
                pass
                # print(evt.pos)
            # 鍵盤相關(guān)事件
            # key屬性,被按的按鍵對應(yīng)的ASCII碼
            if evt.type == pygame.KEYDOWN:
                print('keydown', evt.key)
            if evt.type == pygame.KEYUP:
                print('keyup', chr(evt.key))


if __name__ == '__main__':
    main()

鼠標應(yīng)用事件1

import pygame
from random import randint as rdi


def randcol():
    return (rdi(0, 255), rdi(0, 255), rdi(0, 255))


def drawCircle(screen, pos):
    pygame.draw.circle(screen, randcol(), pos, rdi(10, 50))
    pygame.display.update()


def isInRect(point, rect):
    x, y = point
    rx, ry, width, height = rect
    if rx <= x <= rx + width and ry <= y <= ry + height:
        return True
    return False


# 畫個按鈕
def drawButton(screen, btnColor, titleColor, text1):
    pygame.draw.rect(screen, btnColor, (100, 100, 80, 50))
    font = pygame.font.SysFont('華文楷體', 20)
    title = font.render(text1, True, titleColor)
    screen.blit(title, (120, 110))
    pygame.display.update()


def main():
    pygame.init()
    screen = pygame.display.set_caption('鼠標點擊事件')
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))

    drawButton(screen, (85, 58, 85), (25, 52, 25), '流批')
    pygame.display.flip()
    while True:
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                exit()
            if evt.type == pygame.MOUSEBUTTONDOWN:
                # 指定坐標畫圓
                # drawCircle(screen, evt.pos)
                if isInRect(evt.pos, (100, 100, 80, 50)):
                    drawButton(screen, (200, 58, 201), (45, 54, 25), '流批')
            if evt.type == pygame.MOUSEBUTTONUP:
                # 指定坐標畫圓
                # drawCircle(screen, evt.pos)
                if isInRect(evt.pos, (100, 100, 80, 50)):
                    drawButton(screen, (33, 33, 33), (123, 12, 32), '流批')
            if evt.type == pygame.MOUSEMOTION:
                screen.fill((255, 255, 255))
                drawButton(screen, (33, 33, 33), (123, 12, 32), '流批')
                drawCircle(screen, evt.pos)
                pygame.display.update()


if __name__ == '__main__':
    main()

鼠標應(yīng)用事件2

# 屏幕顯示圖片 鼠標按下拖動圖片,鼠標彈起就不動
import pygame


def isInImg(point, rect):
    x, y = point
    rx, ry, width, height = rect
    if rx <= x <= rx + width and ry <= y <= ry + height:
        return True
    return False


def imgMove(img, sc, point):
    sc.blit(img, point)


def main():
    pygame.init()
    sc = pygame.display.set_caption('mouse2')
    sc = pygame.display.set_mode((600, 400))
    sc.fill((255, 255, 255))
    img = pygame.image.load('./day11/img/xin.jpeg')
    img = pygame.transform.scale(img, (50, 50))
    imgX, imgY = 50, 50
    sc.blit(img, (imgX, imgY))
    pygame.display.flip()
    canMove = False
    w, h = img.get_size()
    while True:
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                exit()
            if evt.type == pygame.MOUSEMOTION:
                if canMove:
                    sc.fill((255, 255, 255))
                    x, y = evt.pos
                    imgX = x - w / 2
                    imgY = y - h / 2
                    imgMove(img, sc, (imgX, imgY))
                    pygame.display.update()
            if evt.type == pygame.MOUSEBUTTONDOWN:
                if isInImg(evt.pos, (imgX, imgY, 50, 50)):
                    canMove = True
            if evt.type == pygame.MOUSEBUTTONUP:
                canMove = False
                pygame.display.update()


if __name__ == '__main__':
    main()

動畫效果

import pygame
from random import randint as ri


def randcol():
    return (ri(0, 255), ri(0, 255), ri(0, 255))


def staticPage(sc):
    font = pygame.font.SysFont('華文行楷', 40)
    title = font.render('流批', True, (0, 0, 0))
    sc.blit(title, (200, 200))


def animatePage(sc):
    font = pygame.font.SysFont('黑體', 40)
    title = font.render('PY', True, randcol())
    sc.blit(title, (100, 100))


def main():
    '''
    原理:不斷刷新界面的內(nèi)容
    '''
    pygame.init()
    screen = pygame.display.set_caption('動畫效果')
    screen = pygame.display.set_mode((900, 400))
    screen.fill((255, 255, 255))
    pygame.display.flip()
    staticPage(screen)
    while True:
        # for循環(huán)里面的代碼只有事件發(fā)生后才會執(zhí)行
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                exit()
        # 線程在此阻塞的時間單位毫秒
        pygame.time.delay(200)
        # 寫自動變化顯示的內(nèi)容
        # 開始之前清空屏幕的內(nèi)容
        screen.fill((255, 255, 255))
        staticPage(screen)
        animatePage(screen)
        # 把展示的內(nèi)容顯示出來
        pygame.display.update()


if __name__ == '__main__':
    main()

小游戲1

'''
 @Author: Kris Shin
 @Date: 2018-07-30 15:39:45
 @Last Modified by: Kris Shin
 @Last Modified time: 2018-07-30 15:39:45
'''
import pygame
import time  # 導(dǎo)入時間函數(shù)

# 保存按鍵的ASCII碼
UP = 273
DOWN = 274
RIGHT = 275
LEFT = 276


# 封裝畫圓函數(shù)
def drawBall(sc, clr, point):
    pygame.draw.circle(sc, clr, point, 15)


def main():
    pygame.init()
    screen = pygame.display.set_caption('ball')
    screen = pygame.display.set_mode((800, 600))
    screen.fill((255, 255, 255))
    # save position
    ballX = 100
    ballY = 100
    speed = 2  # 初始速度
    x = 1  # 設(shè)置默認方向
    y = 0
    pygame.display.flip()
    stTime = time.time()  # 獲取當前時間作為開始時間
    while True:
        edTime = time.time()  # 獲取當前時間節(jié)點
        if edTime - stTime > 3:  # 每3秒速度+1
            speed += 1
            stTime = edTime  # 更新開始時間
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:  # 退出按鈕
                exit()
            if evt.type == pygame.KEYDOWN:  # 鍵盤上下左右按鍵事件
                if evt.key == UP:
                    x = 0  # 控制只能延x/y軸運行,否則控制很困難
                    y = -1
                elif evt.key == DOWN:
                    x = 0
                    y = 1
                elif evt.key == LEFT:
                    y = 0
                    x = -1
                elif evt.key == RIGHT:
                    y = 0
                    x = 1
        screen.fill((255, 255, 255))
        pygame.time.delay(20)  # 設(shè)置延遲,控制速度
        ballX += x * speed  # 更新速度
        ballY += y * speed
        drawBall(screen, (255, 0, 0), (ballX, ballY))
        pygame.display.update()
        if ballX + 20 > 800 or ballX - 20 < 0 or ballY - 20 < 0 or ballY + 20 > 600:  # 如果碰到邊緣則結(jié)束游戲
            screen.fill((255, 255, 255))
            font = pygame.font.SysFont('Times', 100, bold=1)
            title = font.render("Game Over", True, (255, 0, 0))
            screen.blit(title, (150, 200))
            pygame.display.update()
            time.sleep(3)
            exit()


if __name__ == '__main__':
    main()

很多小球的作業(yè)

import pygame
from random import randint as ri


def randClr():
    return (ri(0, 255), ri(0, 255), ri(0, 255))


def rand(x, y):
    z1 = ri(x, y)
    z2 = ri(x, y)
    if z1 or z2:
        rand(x, y)
    return z1, z2


def gameOver(sc):
    sc.fill((255, 255, 255))
    font = pygame.font.SysFont('華文隸書', 120)
    title = font.render('Game Over!', True, (255, 0, 0))
    sc.blit(title, (200, 220))
    pygame.display.update()


def main():
    pygame.init()
    screen = pygame.display.set_caption('Balls')
    screen = pygame.display.set_mode((900, 600))
    screen.fill((255, 255, 255))
    pygame.display.flip()
    xS, yS = rand(-3, 3)
    balls = [{
        'r': ri(8, 15),
        'pos': (ri(0, 899), ri(0, 599)),
        'color': randClr(),
        'xSpeed': xS,
        'ySpeed': yS
    }, {
        'r': ri(8, 15),
        'pos': (ri(0, 899), ri(0, 599)),
        'color': randClr(),
        'xSpeed': xS,
        'ySpeed': yS
    }]
    while True:
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                exit()
            if evt.type == pygame.MOUSEBUTTONDOWN:
                xS, yS = rand(-3, 3)
                nBall = {
                    'r': ri(8, 15),
                    'pos': evt.pos,
                    'color': randClr(),
                    'xSpeed': xS,
                    'ySpeed': yS
                }
                balls.append(nBall)
        screen.fill((255, 255, 255))
        for ballDict in balls:
            r = ballDict['r']
            if r == 0:
                del ballDict
                continue
            elif r > 300:
                gameOver(screen)
                pygame.time.delay(3000)
                exit()
            # 取出坐標和速度
            x, y = ballDict['pos']
            xSpeed = ballDict['xSpeed']
            ySpeed = ballDict['ySpeed']
            x += xSpeed
            y += ySpeed
            pygame.draw.circle(screen, ballDict['color'], (x, y),
                               ballDict['r'])
            if (x - ballDict['r']) < 0:
                x = ballDict['r']
                ballDict['xSpeed'] *= -1
            if (x + ballDict['r']) > 900:
                x = 900 - ballDict['r']
                ballDict['xSpeed'] *= -1
            if (y - ballDict['r']) < 0:
                y = ballDict['r']
                ballDict['ySpeed'] *= -1
            if (y + ballDict['r']) > 600:
                y = 600 - ballDict['r']
                ballDict['ySpeed'] *= -1
            ballDict['pos'] = x, y
            # for ballDict in balls:
            for ballDict1 in balls:
                if balls.index(ballDict) != balls.index(ballDict1):
                    if ((ballDict['pos'][0] - ballDict1['pos'][0])**2 +
                        (ballDict['pos'][1] - ballDict1['pos'][1])**2) <= (
                            ballDict['r'] + ballDict1['r'])**2:
                        if ballDict['r'] > ballDict1['r']:
                            ballDict['r'] += ballDict1['r'] // 2
                            ballDict1['r'] = 0
                        else:
                            ballDict1['r'] += ballDict['r'] // 2
                            ballDict['r'] = 0
        pygame.display.update()


if __name__ == '__main__':
    main()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容