Pygame的簡(jiǎn)單應(yīng)用
import pygame # 導(dǎo)入pygame庫(kù)
from pygame.locals import * # 導(dǎo)入pygame庫(kù)中的一些常量
from sys import exit # 導(dǎo)入sys庫(kù)中的exit函數(shù)
# 定義窗口的分辨率
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 640
# 計(jì)數(shù)ticks == new add ==
ticks = 0
# 計(jì)數(shù)ticks == new add ==
# 初始化游戲
pygame.init() # 初始化pygame
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # 初始化窗口
pygame.display.set_caption('This is my first pygame-program') # 設(shè)置窗口標(biāo)題
# 載入背景圖
background = pygame.image.load('resources/image/background.png')
# 載入資源圖片 == new add ==
shoot_img = pygame.image.load('resources/image/shoot.png')
# 用subsurface剪切讀入的圖片
hero1_rect = pygame.Rect(0, 99, 102, 126)
hero2_rect = pygame.Rect(165, 360, 102, 126)
hero1 = shoot_img.subsurface(hero1_rect)
hero2 = shoot_img.subsurface(hero2_rect)
hero_pos = [200, 500]
# 載入資源圖片 == new add ==
# 事件循環(huán)(main loop)
while True:
# 繪制背景
screen.blit(background, (0, 0))
# 繪制飛機(jī) == new add ==
if ticks % 50 < 25:
screen.blit(hero1, hero_pos)
else:
screen.blit(hero2, hero_pos)
ticks += 1
# 繪制飛機(jī) == new add ==
# 更新屏幕
pygame.display.update()
# 處理游戲退出
# 從消息隊(duì)列中循環(huán)取
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
游戲的設(shè)計(jì)思想就是一種在主循環(huán)之中敦间,并且每次循環(huán)都獲取在這次循環(huán)之中產(chǎn)生的事件吞瞪,然后循環(huán)讀取事件然后匹配解決方案直到quit烦磁。且在每次循環(huán)結(jié)束都要刷新屏幕以更新情況,希望獲得一個(gè)動(dòng)態(tài)的游戲交互效果坯癣,并且以幀數(shù)仿制動(dòng)圖瓶盛,雖然這本來(lái)就是動(dòng)圖的原理。