You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 游戏主控区域
import os
import pygame
import random
class Game:
def __init__(self,state_dict,start_state):
self.screen = pygame.display.get_surface() # 获取屏幕图层
self.clock = pygame.time.Clock()
self.keys = pygame.key.get_pressed()
self.state_dict = state_dict
self.state = self.state_dict[start_state]
def update(self):
if self.state.finished:
game_info = self.state.game_info
next_state = self.state.next
self.state.finished = False
self.state = self.state_dict[next_state]
self.state.start(game_info)
self.state.update(self.screen, self.keys)
def run(self):
while True:
for event in pygame.event.get(): # 获取鼠标键盘事件
if event.type == pygame.QUIT:
pygame.display.quit() # 退出游戏
quit()
elif event.type == pygame.KEYDOWN: # 按键按下
self.keys = pygame.key.get_pressed() # 按键状态
elif event.type == pygame.KEYUP:
self.keys = pygame.key.get_pressed()
self.update()
pygame.display.update() # 更新屏幕
self.clock.tick(60)
def load_graphics(path,accept=(',jpg','.png','.bpm','.gis')): # 那些后缀允许读入
graphics = {} #新建空字典
for pic in os.listdir(path):
name,ext = os.path.splitext(pic) # 拆分文件名+后缀
if ext.lower() in accept: # 如果允许格式就允许使用pygame允许载入
img = pygame.image.load(os.path.join(path,pic))
if img.get_alpha():
img = img.convert_alpha()
else:
img = img.convert()
graphics[name] = img
return graphics
def get_image(sheet,x,y,width,height,colorkey,scale): #从已经加载好图片获取某部分
image = pygame.Surface((width,height))
image.blit(sheet,(0,0),(x,y,width,height)) # 00代表到哪个位置x,y,w,h表示取出区域
image.set_colorkey(colorkey)
image = pygame.transform.scale(image, (int(width*scale),int(height*scale)))
return image