python-pygame实现飞机大战-3-发射子弹以及击中敌机

该博客介绍了在Python Pygame中如何实现飞机大战游戏的子弹发射和敌机碰撞功能。作者分享了具体实现逻辑,包括子弹的循环运动以模拟连续发射效果,以及游戏中的碰撞检测和处理。文章提供了相关代码和资源链接供读者参考学习。
摘要由CSDN通过智能技术生成

承接上两步:
1.python-pygame实现飞机大战-添加背景以及飞机运动
2.python-pygame实现飞机大战-2-添加敌机以及碰撞爆炸

在完成玩家飞机运动,生成敌机飞机以及两者碰撞爆炸后,这一步只要就是增加一下敌机发射子弹、子弹击中敌机的功能:先上图
在这里插入图片描述
先准备资源,网络上也可以下载到,我这里直接用的教程的资源,为什么呢(确实好看,自己找的惨不忍睹),整个项目的包我已经放上去了,包括源码以及资源,注释能加的基本上都加了,可自行下载查看:https://download.csdn.net/download/weixin_38778769/19126067。或者直接下载下方的图片(这一步要用到的)

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

这次有一说一,这个发射子弹的逻辑给我整的不轻,具体的实现逻辑就是四颗子弹不断循环,从而达到一种不断发射子弹的效果,但实际上只有四颗子弹来回运动
先放main.py,在上一步代码上添加了发射子弹、渲染子弹、子弹碰撞处理的模块
子弹逻辑如下图,最后四颗子弹不断循环
在这里插入图片描述


```python
import pygame
import sys
import traceback
from pygame.locals import *
from random import *
import myplane
import enemy
import bullet


# 初始化
pygame.init()
# 设置窗口大小
bg_size = width, height = 400, 700  # 实际上是元组
screen = pygame.display.set_mode(bg_size)  # 设置窗口
pygame.display.set_caption("飞机大战")  # 窗口标题
# 加载背景图片,对于普通图像的显示效果有没有convert都是一样的,但是 使用 convert 可以转换格式,提高 blit 的速度
background = pygame.image.load("images/background.png").convert()

# 设置黑、绿、红、百几种颜色对应值,后面会用到
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)

# 生成敌方小型飞机
def add_small_enemy(small_enemies, enemiesGroup, num):
    for i in range(num):
        smallenemy = enemy.SmallEnemy(bg_size)
        # 精灵组来实现多个图像,很适合处理精灵列表,有添加,移除,绘制,更新等方法
        # Group.sprites 精灵组
        # Group.copy 复制
        # Group.add 添加
        # Group.remove 移除
        # Group.has 判断精灵组成员
        # Group.update 更新
        # Group.draw 位块显示
        # Group.clear - 绘制背景
        # Group.empty 清空
        # 将这一组敌机都添加上小型飞机属性,相当于统一处理,统一赋值
        small_enemies.add(smallenemy)
        enemiesGroup.add(smallenemy)

def main():
    # 创建时钟对象(可以控制游戏循环频率)
    clock = pygame.time.Clock()

    # 生成玩家飞机
    me = myplane.MyPlane(bg_size)

    # 存放所有
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()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值