pygame讓小方塊在屏幕中反彈

import pygame
from pygame import *
from sys import exit

"""
讓一個小方塊在屏幕裏反彈
"""

WIDTH, HEIGHT = 700, 500
FPS = 60
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# 矩形的起始位置
rect_x = 50
rect_y = 50

# 矩形的方向和速度
rect_change_x = 5
rect_change_y = 5
while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                exit()

    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50])
    rect_x += rect_change_x
    rect_y += rect_change_y
    """
    爲什麼檢查rect_y是不是450? 如果屏幕是500像素高,那麼檢查500才應該是更加看似合理的猜想。
    但請記得矩形是從左上角 開始畫的。如果起始位置是500, 那麼它會從500畫到550, 在反彈之前已經超出屏幕了。
    所以把矩形是50像素高考慮進去的話,正確的反彈的位置是:
    500 -50
    """
    if rect_y > 450 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 650 or rect_x < 0:
        rect_change_x = rect_change_x * -1
    pygame.display.update()

 

效果展示:

 

原文鏈接:http://programarcadegames.com/index.php?chapter=introduction_to_animation&lang=cn#section_8

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章