問題:繪製矩形示列是一個圍繞螢幕移動形狀的示列,任何時候,矩形碰到螢幕邊界時,矩形都會改變顏色。


把 每次碰撞時改變的顏色用列表來歸納並計算反彈次數作為索引是個不錯的思路。
程式碼如下:

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)