Python學習筆記——遊戲開發pygame入門

一、找到官網:

https://www.pygame.org

二、安裝(可以使用谷歌翻譯)

安裝pygame (使用python3命令安裝報錯,可以嘗試使用python命令

python -m pip install -U pygame --user

 測試安裝是否成功

python -m pygame.examples.aliens

安裝過程截圖 

 三、查看幫助文檔

https://www.pygame.org/docs/ 

 

四、入門案例

import sys, pygame
pygame.init()

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("intro_ball.gif")
ballrect = ball.get_rect()

while 1:
    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(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

一個遊戲循環(也可以稱爲主循環)就做下面這三件事:

  1. 處理事件
  2. 更新遊戲狀態
  3. 繪製遊戲狀態到屏幕上

代碼解釋:

1.pygame.display.set_mode(size)#返回的是Surface對象,也可以當作 screen 的意思

2.ball.get_rect() #返回的是Rect對象,圖片轉換成矩形對象。

3.ballrect.move(speed)#speed是座標,列表表示。ballrect當前的座標是原點座標,移到speed的座標。

Pygame的座標原點(0,0)點位於左上角,X軸自左向右,Y軸自上向下,單位爲像素。

 

 

 

 

 

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