python--pygame入门--03--游戏框架搭建

python–pygame入门–03–游戏框架搭建


目标

  • 明确主程序职责
  • 实现主程序类
  • 准备游戏精灵组

1、明确主程序职责

  • 一个游戏主程序的 职责 可以分为两个部分:
    • 游戏初始化
    • 游戏循环
  • 根据明确的职责,设计 PlaneGame 类如下:

在这里插入图片描述

  • 根据 职责 封装私有方法,避免某一个方法的代码写得太过冗长

1.1、游戏初始化—— __init__() 会调用以下方法

方法职责
__create_sprites(self)创建所有精灵和精灵组

1.2、游戏循环—— start_game() 会调用以下方法

方法职责
__event_handler(self)事件监听
__check_collide(self)碰撞检测 —— 子弹销毁敌机、敌机撞毁英雄
__update_sprites(self)精灵组更新和绘制
__game_over()游戏结束

2、实现飞机大战主游戏类

2.1、明确文件职责

在这里插入图片描述

  • plane_main
    1. 封装 主游戏类
    2. 创建 游戏对象
    3. 启动游戏
  • plane_sprites
    • 封装游戏中 所有 需要使用的 精灵子类
    • 提供游戏的 相关工具

2.2、代码实现

2.2.1、主程序

  • 新建 plane_main.py 文件
  • 编写 基础代码
import pygame
from plane_sprites import *


class PlaneGame(object):
    """飞机大战主游戏"""

    def __init__(self):
        print("游戏初始化")

    def start_game(self):
        print("开始游戏...")


if __name__ == '__main__':
    # 创建游戏对象
    game = PlaneGame()

    # 开始游戏
    game.start_game()

2.2.2、游戏初始化部分

  • 完成 __init__() 代码如下:
def __init__(self):
    print("游戏初始化")
    
    # 1. 创建游戏的窗口
    self.screen = pygame.display.set_mode((480, 700))
    # 2. 创建游戏的时钟
    self.clock = pygame.time.Clock()
    # 3. 调用私有方法,精灵和精灵组的创建
    self.__create_sprites()

def __create_sprites(self):
    pass

2.2.3、使用 常量 代替固定的数值

  • 常量 —— 不变化的量
  • 变量 —— 可以变化的量

应用场景

  • 在开发时,可能会需要使用 固定的数值,例如 屏幕的高度700
  • 这个时候,建议 不要 直接使用固定数值,而应该使用 常量
  • 在开发时,为了保证代码的可维护性,尽量不要使用 魔法数字

常量的定义

  • 定义 常量 和 定义 变量 的语法完全一样,都是使用 赋值语句
  • 常量命名 应该 所有字母都使用大写单词与单词之间使用下划线连接

常量的好处

  • 阅读代码时,通过 常量名 见名之意,不需要猜测数字的含义
  • 如果需要 调整值,只需要 修改常量定义 就可以实现 统一修改

提示:Python 中并没有真正意义的常量,只是通过命名的约定 —— 所有字母都是大写的就是常量,开发时不要轻易的修改!

代码调整

  • plane_sprites.py 中增加常量定义
import pygame

# 游戏屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
  • 修改 plane_main.py 中的窗口大小
self.screen = pygame.display.set_mode(SCREEN_RECT.size)

2.2.4、游戏循环部分

  • 完成 start_game() 基础代码如下:
def start_game(self):
    """开始游戏"""
    
    print("开始游戏...")
       
    while True:
    
        # 1. 设置刷新帧率
        self.clock.tick(60)
        
        # 2. 事件监听
        self.__event_handler()
        
        # 3. 碰撞检测
        self.__check_collide()
        
        # 4. 更新精灵组
        self.__update_sprites()
        
        # 5. 更新屏幕显示
        pygame.display.update()

def __event_handler(self):
    """事件监听"""
    
    for event in pygame.event.get():
    
        if event.type == pygame.QUIT:
            PlaneGame.__game_over()

def __check_collide(self):
    """碰撞检测"""
    pass

def __update_sprites(self):
    """更新精灵组"""
    pass
    
@staticmethod
def __game_over():
   """游戏结束"""

   print("游戏结束")
   pygame.quit()
   exit()

2.2.5、整体代码

plane_main.py
import pygame
from plane_sprites import *


class PlaneGame(object):
    """飞机大战主游戏"""

    def __init__(self):
        print("游戏初始化")
        # 1. 创建游戏的窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 2. 创建游戏的时钟
        self.clock = pygame.time.Clock()
        # 3. 调用私有方法,精灵和精灵组的创建
        self.__create_sprites()

    def start_game(self):

        print("开始游戏...")

        while True:
            # 1. 设置刷新帧率
            self.clock.tick(60)

            # 2. 事件监听
            self.__event_handler()

            # 3. 碰撞检测
            self.__check_collide()

            # 4. 更新精灵组
            self.__update_sprites()

            # 5. 更新屏幕显示
            pygame.display.update()

    def __create_sprites(self):
        """精灵和精灵组的创建"""
        pass

    def __event_handler(self):
        """事件监听"""

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                PlaneGame.__game_over()

    def __check_collide(self):
        """碰撞检测"""
        pass

    def __update_sprites(self):
        """更新精灵组"""
        pass

    @staticmethod
    def __game_over():
        """游戏结束"""
        print("游戏结束")
        pygame.quit()
        exit()


if __name__ == '__main__':
    # 创建游戏对象
    game = PlaneGame()

    # 开始游戏
    game.start_game()

plane_sprites.py
# 导入pygame模块
import pygame

# 游戏屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
class GameSprite(pygame.sprite.Sprite):
    """
    游戏精灵基类
    """

    def __init__(self, image_name, speed=1):
        # 调用父类的初始化方法
        super().__init__()

        # 加载图像
        self.image = pygame.image.load(image_name)
        # 设置尺寸
        self.rect = self.image.get_rect()
        # 记录速度
        self.speed = speed

    def update(self, *args):
        # 默认在垂直方向移动
        self.rect.y += self.speed

在这里插入图片描述

3、准备游戏精灵组

3.1、确定精灵组

在这里插入图片描述

3.2、代码实现

3.2.1、创建精灵组方法

def __create_sprites(self):
    """创建精灵组"""
    
    # 背景组
    self.back_group = pygame.sprite.Group()
    # 敌机组
    self.enemy_group = pygame.sprite.Group()
    # 英雄组
    self.hero_group = pygame.sprite.Group()

3.2.2、更新精灵组方法

def __update_sprites(self):
    """更新精灵组"""
    
    for group in [self.back_group, self.enemy_group, self.hero_group]:
    
        group.update()
        group.draw(self.screen)
import matplotlib.pylab as plt import numpy as np import random from scipy.linalg import norm import PIL.Image class Rbm: def __init__(self,n_visul, n_hidden, max_epoch = 50, batch_size = 110, penalty = 2e-4, anneal = False, w = None, v_bias = None, h_bias = None): self.n_visible = n_visul self.n_hidden = n_hidden self.max_epoch = max_epoch self.batch_size = batch_size self.penalty = penalty self.anneal = anneal if w is None: self.w = np.random.random((self.n_visible, self.n_hidden)) * 0.1 if v_bias is None: self.v_bias = np.zeros((1, self.n_visible)) if h_bias is None: self.h_bias = np.zeros((1, self.n_hidden)) def sigmod(self, z): return 1.0 / (1.0 + np.exp( -z )) def forward(self, vis): #if(len(vis.shape) == 1): #vis = np.array([vis]) #vis = vis.transpose() #if(vis.shape[1] != self.w.shape[0]): vis = vis.transpose() pre_sigmod_input = np.dot(vis, self.w) + self.h_bias return self.sigmod(pre_sigmod_input) def backward(self, vis): #if(len(vis.shape) == 1): #vis = np.array([vis]) #vis = vis.transpose() #if(vis.shape[0] != self.w.shape[1]): back_sigmod_input = np.dot(vis, self.w.transpose()) + self.v_bias return self.sigmod(back_sigmod_input) def batch(self): eta = 0.1 momentum = 0.5 d, N = self.x.shape num_batchs = int(round(N / self.batch_size)) + 1 groups = np.ravel(np.repeat([range(0, num_batchs)], self.batch_size, axis = 0)) groups = groups[0 : N] perm = range(0, N) random.shuffle(perm) groups = groups[perm] batch_data = [] for i in range(0, num_batchs): index = groups == i batch_data.append(self.x[:, index]) return batch_data def rbmBB(self, x): self.x = x eta = 0.1 momentum = 0.5 W = self.w b = self.h_bias c = self.v_bias Wavg = W bavg = b cavg = c Winc = np.zeros((self.n_visible, self.n_hidden)) binc = np.zeros(self.n_hidden) cinc = np.zeros(self.n_visible) avgstart = self.max_epoch - 5; batch_data = self.batch() num_batch = len(batch_data) oldpenalty= self.penalty t = 1 errors = [] for epoch in range(0, self.max_epoch): err_sum = 0.0 if(self.anneal): penalty = oldpenalty - 0.9 * epoch / self.max_epoch * oldpenalty for batch in range(0, num_batch): num_dims, num_cases = batch_data[batch].shape data = batch_data[batch] #forward ph = self.forward(data) ph_states = np.zeros((num_cases, self.n_hidden)) ph_states[ph > np.random.random((num_cases, self.n_hidden))] = 1 #backward nh_states = ph_states neg_data = self.backward(nh_states) neg_data_states = np.zeros((num_cases, num_dims)) neg_data_states[neg_data > np.random.random((num_cases, num_dims))] = 1 #forward one more time neg_data_states = neg_data_states.transpose() nh = self.forward(neg_data_states) nh_states = np.zeros((num_cases, self.n_hidden)) nh_states[nh > np.random.random((num_cases, self.n_hidden))] = 1 #update weight and biases dW = np.dot(data, ph) - np.dot(neg_data_states, nh) dc = np.sum(data, axis = 1) - np.sum(neg_data_states, axis = 1) db = np.sum(ph, axis = 0) - np.sum(nh, axis = 0) Winc = momentum * Winc + eta * (dW / num_cases - self.penalty * W) binc = momentum * binc + eta * (db / num_cases); cinc = momentum * cinc + eta * (dc / num_cases); W = W + Winc b = b + binc c = c + cinc self.w = W self.h_bais = b self.v_bias = c if(epoch > avgstart): Wavg -= (1.0 / t) * (Wavg - W) cavg -= (1.0 / t) * (cavg - c) bavg -= (1.0 / t) * (bavg - b) t += 1 else: Wavg = W bavg = b cavg = c #accumulate reconstruction error err = norm(data - neg_data.transpose()) err_sum += err print epoch, err_sum errors.append(err_sum) self.errors = errors self.hiden_value = self.forward(self.x) h_row, h_col = self.hiden_value.shape hiden_states = np.zeros((h_row, h_col)) hiden_states[self.hiden_value > np.random.random((h_row, h_col))] = 1 self.rebuild_value = self.backward(hiden_states) self.w = Wavg self.h_bais = b self.v_bias = c def visualize(self, X): D, N = X.shape s = int(np.sqrt(D)) if s == int(np.floor(s)): num = int(np.ceil(np.sqrt(N))) a = np.zeros((num*s + num + 1, num * s + num + 1)) - 1.0 x = 0 y = 0 for i in range(0, N): z = X[:,i] z = z.reshape(s,s,order='F') z = z.transpose() a[x*s+1+x - 1:x*s+s+x , y*s+1+y - 1:y*s+s+y ] = z x = x + 1 if(x >= num): x = 0 y = y + 1 d = True else: a = X return a def readData(path): data = [] for line in open(path, 'r'): ele = line.split(' ') tmp = [] for e in ele: if e != '': tmp.append(float(e.strip(' '))) data.append(tmp) return data if __name__ == '__main__': data = readData('data.txt') data = np.array(data) data = data.transpose() rbm = Rbm(784, 100,max_epoch = 50) rbm.rbmBB(data) a = rbm.visualize(data) fig = plt.figure(1) ax = fig.add_subplot(111) ax.imshow(a) plt.title('original data') rebuild_value = rbm.rebuild_value.transpose() b = rbm.visualize(rebuild_value) fig = plt.figure(2) ax = fig.add_subplot(111) ax.imshow(b) plt.title('rebuild data') hidden_value = rbm.hiden_value.transpose() c = rbm.visualize(hidden_value) fig = plt.figure(3) ax = fig.add_subplot(111) ax.imshow(c) plt.title('hidden data') w_value = rbm.w d = rbm.visualize(w_value) fig = plt.figure(4) ax = fig.add_subplot(111) ax.imshow(d) plt.title('weight value(w)') plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值