background_image_filename = '素材fly_img_name = '素材
\\fugu.png'
from
abc import
abcmeta,
abstractmethod
import
pygame
# 匯入pygame庫
from
pygame.locals import
*# 匯入一些常用的函式和常量
from
sys import
exit
import
time
# 向sys模組借乙個exit函式用來退出程式
pygame.init()
# 初始化pygame,為使用硬體做準備
class
character:
__metaclass__
= abcmeta
@abstractmethod
def
move_ctrl
(self
, event):
""" 自機操作
示例if event[k_down]:
self.y -= 5
注意邊界條件,此處暫不舉例
"""pass
@abstractmethod
def
show
(self
, screen):
# 自機顯示方法
pass
@abstractmethod
def
mask
(self
): # 遮罩影象
pass
@abstractmethod
def
bullet
(self
, b):
assert
issubclass
(b,
bullet),
"引數必須是bullet的子類!"
class
charactersprite(character,
pygame.sprite.sprite):
def
__init__
(self
, img_name):
pygame.sprite.sprite.__init__
(self
) self
.x,
self
.y = 0, 0
self
.img = img_name
self
.cursor = pygame.image.load(self
.img).convert_alpha()
def
move_ctrl
(self
, keys_dict):
""" 自機操作
示例if event[k_down]:
self.y -= 5
注意邊界條件,此處暫不舉例
"""if
keys_dict[k_down]:
self
.y += 1
if keys_dict[k_up]:
self
.y -= 1
if keys_dict[k_left]:
self
.x -= 1
if keys_dict[k_right]:
self
.x += 1
def
show
(self
, screen):
# 自機顯示方法
screen.blit(self
.cursor,
(self
.x,
self
.y))
def
mask
(self
): # 遮罩影象
pass
def
bullet
(self
, bullet_cls):
# 對每一顆子彈建立乙個例項
# bullet_cls(self.x, self.y)
pass
class
bullet:
"""介面"""
__metaclass__
= abcmeta
@abstractmethod
def
move
(self
): # 子彈移動行為
pass
@abstractmethod
def
style
(self
): # 子彈樣式
pass
@abstractmethod
def
show
(self
): # 顯示方法
pass
@abstractmethod
def
mask
(self
): # 遮罩影象
pass
class
bulletsprite(bullet,
pygame.sprite.sprite):
# 子彈
def
__init__
(self
, fly_x: int
, fly_y: int
): pygame.sprite.sprite.__init__
(self
) # 初始化時的飛機座標
self
.coordinate = (fly_x,
fly_y)
# 子彈初始座標
self
.x,
self
.y = self
.coordinate
def
move
(self
): pass
def
style
(self
): # 子彈樣式
pass
def
show
(self
): # 顯示方法
pass
def
mask
(self
): # 遮罩影象
pass
if __name__ == '__main__'
: screen = pygame.display.set_mode((720
, 640
), fullscreen|noframe, 32)
# 建立了乙個視窗
pygame.display.set_caption("hello, world!"
) # 設定視窗標題
background = pygame.image.load(background_image_filename).convert()
character = charactersprite(fly_img_name)
while true
: # 遊戲主迴圈
time.sleep(0.004
) for
event in
pygame.event.get():
if event.type == quit:
# 接收到退出事件後退出程式
exit()
keys = pygame.key.get_pressed()
if keys[k_escape]:
exit()
character.move_ctrl(keys)
screen.blit(background,
(0, 0))
# 將背景圖畫上去
character.show(screen)
pygame.display.update()
# 重新整理一下畫面
pygame模組學習
python m pip install user pygame 1.9.2 cp35 cp35m win amd64.whl 模組pygame包含開發遊戲所需功能。模組sys用來退出遊戲。pygame中,顏色是以rgb值指定的。由紅 綠 藍色組成。每個值的取值範圍都是0 255。顏色值 255,0...
pygame基礎操作練習
import pygame import sys import pygame.freetype pygame.init 對pygame的內容初始化 fclock pygame.time.clock 創造乙個clock物件,用於操作時間 vinfo pygame.display.info 獲取螢幕資訊...
pygame中event模組方法詳解
目錄 pygame.event.pump pygame.event.get pygame.event.poll pygame.event.wait pygame.event.peek pygame.event.clear pygame.event.event name pygame.event.se...