1. 程式人生 > >運動的小球遊戲

運動的小球遊戲

# -*- coding:utf-8 -*-
import sys #匯入系統模組
import pygame  #匯入Pygame模組

pygame.init() #初始化pygame
size = width,height = 640,480  #設定視窗大小
screen = pygame.display.set_mode(size)  #顯示視窗
color = (0,0,0)  #設定顏色

ball = pygame.image.load("ball.png")  #載入圖片
ballrect = ball.get_rect()  #獲取矩形區域

speed = [5,5]  #設定移動的x,y軸的距離
clock = pygame.time.Clock()  #設定時鐘
#執行死迴圈,確保視窗一直開著
while True:
    clock.tick(60) #每秒執行60次
    #檢查事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:     #如果單擊關閉視窗,則退出
            sys.exit()
    ballrect = ballrect.move(speed)   #移動小球
    #碰到邊緣
    if ballrect.left < 0 or ballrect.right >width:
        speed[0] = -speed[0]
    #碰到上下邊緣
    if ballrect.top <0 or ballrect.bottom >height:
        speed[1] = -speed[1]

    screen.fill(color)   #填充顏色
    screen.blit(ball,ballrect)  #將圖片畫到視窗上
    pygame.display.flip()    #更新全部顯示

pygame.quit()  # 退出pygame