【Python个人学习笔记】---《Python游戏编程入门》第二章小结挑战习题(三)

问题:绘制矩形示列是一个围绕屏幕移动形状的示列,任何时候,矩形碰到屏幕边界时,矩形都会改变颜色。


把 每次碰撞时改变的颜色用列表来归纳并计算反弹次数作为索引是个不错的思路。
代码如下:

import sys
import pygame
from pygame.locals import *

# 初始化
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Rectingles")
# 帧率
FPS = 60
fpsClock = pygame.time.Clock()

# 矩形位置参数及移动速度
pos_x = 300
pos_y = 250
vel_x = 2
vex_y = 1

# 颜色代码
white = 255, 255, 255
blue = 0, 0, 200
green = 0, 200, 0
red = 200, 0, 0
yellow = 200, 200, 0
purple = 200, 0, 200
aoi = 0, 200, 200
gray = 200, 200, 200
black = 0, 0, 0
color = [blue, green, red, yellow, purple, aoi, gray, black]
count = 0  # 计算颜色
word = 0  # 计算反弹次数

# 主循环
while True:
    # 键鼠事件
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN):
            sys.exit()
    # 绘制屏幕颜色
    screen.fill(white)
    # 移动矩形
    pos_x += vel_x
    pos_y += vex_y
    # 使矩形不移出屏幕外,并计数碰撞回弹次数
    if pos_x > 500 or pos_x < 0:
        vel_x = -vel_x
        count += 1
        word += 1
    if pos_y > 400 or pos_y < 0:
        vex_y = -vex_y
        count += 1
        word += 1
    if count > 7:
        count = 0
    # 绘制矩形
    width = 0
    pos = pos_x, pos_y, 100, 100
    pygame.draw.rect(screen, color[count], pos, width)
    # 更新屏幕显示
    pygame.display.update()
    fpsClock.tick(FPS)

补充:在网上查资料看到更简单的写法,用random库来写,这里记录一下。

import sys
import time
import random
import pygame
from pygame.locals import *

# 初始化
pygame.init()
# 创建窗口
pygame.display.set_caption("Drawing Moving Rect")
screen = pygame.display.set_mode((600, 500))
# 帧率
FPS = 60
fpsClock = pygame.time.Clock()

# 矩形位置、移动速度、颜色
pos_x = 300
pos_y = 250

vel_x = 2
vex_y = 1

color = 0, 255, 0

# 主循环
while True:
    # 绘制屏幕颜色
    # 放循环外会导致矩形相邻的绘制会连成一条矩形宽度的线
    screen.fill((0, 0, 0))
    # 键鼠事件
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN):
            sys.exit()
    # 移动矩形
    pos_x += vel_x
    pos_y += vex_y
    position = pos_x, pos_y, 100, 100
    # 颜色的变化
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    # 碰到边界改变矩形移动,使其保持在窗口内
    # 每一次碰撞窗口边界,改变颜色
    if 500 < pos_x or pos_x < 0:
        vel_x = -vel_x
        color = r, g, b
    if 400 < pos_y or pos_y < 0:
        vex_y = -vex_y
        color = r, g, b

    # 绘制矩形
    pygame.draw.rect(screen, color, position, 0)
    # 更新屏幕显示
    pygame.display.update()
    fpsClock.tick(FPS)
    time.sleep(0.01)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章