pygame模組學習

2021-10-03 15:01:11 字數 1859 閱讀 2863

python -m pip install --user pygame-1.9.2-cp35-cp35m-win_amd64.whl

模組pygame包含開發遊戲所需功能。模組sys用來退出遊戲。

pygame中,顏色是以rgb值指定的。由紅、綠、藍色組成。每個值的取值範圍都是0~255。

顏色值(255,0,0)表示紅色。

顏色值(0,255,0)表示綠色。

顏色值(0,0,255)表示藍色。

su***ce是螢幕的一部分。

rect物件是su***ce中的屬性

rect中有四個屬性

left, top, width/right, height/bottom

#在每次的主迴圈中檢測事件

while

true

:for event in pygame.event.get():

if event.

type

== pygame.quit:

sys.exit(

)```elif event.

type

== pygame.keydown:

if event.key == pygame.k_right:

weisuo.rect.centerx +=

1elif event.key == pygame.k_left:

weisuo.rect.centerx -=

1建立ship類

```python

import pygame

class

ship()

:def

__init__

(self,screen)

:'''初始化飛船並設定其初始位置'''

self.screen = screen

#載入飛船影象並返回獲取乙個表示飛船的su***ce

self.image = pygame.image.load(

"images/ship.bmp"

)#獲取相應su***ce的屬性rect

self.rect = self.image.get_rect(

)#獲取表示螢幕的矩形rect

self.screen_rect = screen.get_rect(

)'''使其與螢幕下邊緣對齊並水平居中'''

#將每艘新飛船放在螢幕底部**(screen_rect.centerx:是指飛船中心的x座標)

self.rect.centerx = self.screen_rect.centerx

#(screen_rect.bottom:是指飛船下邊緣的y座標)

self.rect.bottom = self.screen_rect.bottom

defblitme

(self)

:'''在指定位置繪製飛船,位置是根據rect中設定好的屬性。'''

self.screen.blit(self.image,self.rect)

以向右為例:按下右箭頭鍵時,我們將這個標誌設定為true;而鬆開時將標誌重新設定為false

pygame.sprite.sprite就是pygame裡面用來實現精靈的乙個類,使用時,並不需要對它例項化,只需要繼承他,然後按需寫出自己的類就好了,因此非常簡單實用。

5.1 pygame.sprite.group類

精靈組管理類,用來統一管理所有的精靈,它很適合處理精靈列表,有新增,移除,繪製,更新等方法。

pygame模組練習

background image filename 素材 fly img name 素材 fugu.png from abc import abcmeta,abstractmethod import pygame 匯入pygame庫 from pygame.locals import 匯入一些常用的...

Python學習模組 Pygame寫遊戲

第乙個例項程式 建立 main game.py 一張背景 001.jpg 一張跟隨滑鼠!初始化pygame,為使用硬體做準備 pygame.init 建立乙個視窗 screen pygame.display.set mode 640,480 0,32 設定視窗標題 pygame.display.se...

pygame學習筆記

import sys import pygame pygame.init size width,height 680,480screen pygame.display.set mode size clock pygame.time.clock while true clock.tick 60 每秒6...