1.安裝pygame
下載點擊這裏
選擇pygame-1.9.6-cp37-cp37m-win_amd64.wh
下載之後我們把這個後綴爲whl的文件放到python的pip文件目錄下
shift 加上鼠標右鍵 打開powershell窗口 導入pygame模塊就顯示安裝完畢 打開idle 輸入import pygame驗證是否安裝成功
動手寫一個小遊戲
import pygame
import sys
#初始化pygame
pygame.init()
size = width,height =600,400
speed = [-2,1]
bg=(255,255,255)
#創建指定大小的窗口 surface
screen =pygame.display.set_mode(size)
#設置窗口標題
pygame.display.set_caption("第一個遊戲")
#加載圖片
turtle=pygame.image.load("timg.png")
#獲得圖像的位置矩陣
position = turtle.get_rect()
while True:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
sys.exit
#移動圖像
position = position.move(speed)
if position.left<0 or position.right>width:
turtle=pygame.transform.flip(turtle,True,False)
speed[0]=-speed[0]
if position.top<0 or position.bottom>height:
speed[1] = -speed[1]
#填充背景
screen.fill(bg)
#更新圖像
screen.blit(turtle,position)
#更新界面
pygame.display.flip()
pygame.time.delay(10)
效果爲下圖
看見小老虎在不停的移動,其實本質是一個死循環
據瞭解pygame是由c語言來開發的,效率還不錯,接下來開始學習編寫真正像遊戲的遊戲
其中還可以爲其設置幀率clock.tick()