python飞机大战游戏素材_python实现飞机大战小游戏

本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下

初学Python,写了一个简单的Python小游戏。

师出bilibili某前辈

pycharm自带了第三方库pygame,安装一下就好了,很方便。

虽然很多大佬已经给出了步骤,我这里还是啰嗦一下,也为了自己巩固一下。

上图:

2019118130800487.jpg

2019118131256140.jpg

这里再给出代码的逻辑架构

2019118130848366.jpg

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.__creat_sprites()

#4.设置定时器事件-1s敌机出现

pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)

pygame.time.set_timer(HERO_FIRE_EVENT, 500)

def __creat_sprites(self):

# 创建精灵

bg1 = Background()

bg2 = Background(True)

# 创建精灵组

self.back_group = pygame.sprite.Group(bg1,bg2)

#创建敌机的精灵组

self.enemy_group=pygame.sprite.Group()

#创建英雄的精灵和精灵组

self.hero=Hero()

self.hero_group=pygame.sprite.Group(self.hero)

self.enemy_hit_group=pygame.sprite.Group();

def start_game(self):

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

while True:

#1.设置刷新帧率

self.clock.tick(FRAME_PER_SEC)

#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()

elif event.type==CREATE_ENEMY_EVENT:

print("敌机出场")

#创建敌机精灵

enemy=Enemy()

#将敌机精灵添加到敌机精灵组

self.enemy_group.add(enemy)

elif event.type==HERO_FIRE_EVENT:

self.hero.fire()

#elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:

#print("向右移动....")

#使用键盘模块

keys_pressed=pygame.key.get_pressed()

#判断元组中对应的按键索引值

if keys_pressed[pygame.K_RIGHT]:

self.hero.speed=3

elif keys_pressed[pygame.K_LEFT]:

self.hero.speed = -3

else:

self.hero.speed = 0

def __check_collide(self):

#1.子弹摧毁敌机

enemy_hit = pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

#2.敌机撞毁英雄

enemies=pygame.sprite.spritecollide(self.hero,self.enemy_group,True)

if len(enemies)>0:

#让英雄牺牲

# self.hero.explode()

self.hero.kill()

#结束游戏

PlaneGame.__game_over()

def __update_sprites(self):

self.back_group.update()

self.back_group.draw(self.screen)

self.enemy_group.update()

self.enemy_group.draw(self.screen)

self.hero_group.update()

self.hero_group.draw(self.screen)

self.hero.bullets.update()

self.hero.bullets.draw(self.screen)

@staticmethod

def __game_over():

print("游戏结束")

pygame.quit()

exit()

if __name__ == '__main__':

#创建游戏对象

game=PlaneGame()

#启动游戏

game.start_game()

plane_sprites.py

import random

import pygame

#屏幕大小常量

SCREEN_RECT=pygame.Rect(0,0,480,700)

#刷新帧率

FRAME_PER_SEC=60

explode_index=0

#创建定时器常量

CREATE_ENEMY_EVENT=pygame.USEREVENT

#创建发射子弹事件

HERO_FIRE_EVENT=pygame.USEREVENT+1

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):

#在屏幕的垂直方向运动

self.rect.y+=self.speed

class Background(GameSprite):

"""游戏背景精灵"""

def __init__(self,is_alt=False):

#1.调用父类方法,实现精灵创建(image/rect/speed)

super().__init__("./images/background.png")

#2.判断是否是交替图像

if is_alt:

self.rect.y = -self.rect.height

def update(self):

#1.调用父类方法实现

super().update()

#2.判断图像是否移除屏幕,若移除,则设置到屏幕上面

if self.rect.y>=SCREEN_RECT.height:

self.rect.y= -self.rect.height

class Enemy(GameSprite):

"""敌机精灵"""

def __init__(self):

#1.调用父类方法,创建敌机精灵,指定敌机图片

super().__init__("./images/enemy1.png")

#2.指定敌机的初始随机速度1-3

self.speed=random.randint(1,3)

#3.指定敌机的初始随机位置

self.rect.bottom=0

max_x=SCREEN_RECT.width-self.rect.width

self.rect.x=random.randint(0,max_x)

self.explode_index=0

def update(self):

#1.调用父类方法,保持垂直方向飞行

super().update()

#2.判断是否飞出屏幕,如果是,则删除精灵

if self.rect.y>=SCREEN_RECT.height:

#kill方法可以将精灵从精灵组中移出,精灵就会被自动销毁,然后调用下面方法

self.kill()

#if self.explode_index==5:

#return

if self.explode_index!=0:

new_rect=self.rect

super.__init__("./images/enemy1_down1.png")

self.explode_index=self.explode_index+1

self.rect=new_rect

def __del__(self):

# print("敌机挂了%s"% self.rect)

pass

class Hero(GameSprite):

"""英雄精灵"""

def __init__(self):

#1.调用父类方法

super().__init__("./images/me1.png",0)

#2.设置英雄的初始位置

self.rect.centerx=SCREEN_RECT.centerx

self.rect.bottom=SCREEN_RECT.bottom-120

#创建子弹精灵组

self.bullets=pygame.sprite.Group()

def update(self):

self.rect.x+=self.speed

if self.rect.x<0:

self.rect.x=0

elif self.rect.right>SCREEN_RECT.right:

self.rect.right=SCREEN_RECT.right

def fire(self):

print("发射子弹...")

for i in (0,1,2):

#1.创建精灵组

bullet=Bullet()

#2.设置精灵位置

bullet.rect.bottom=self.rect.y-i*20

bullet.rect.centerx=self.rect.centerx

#3.添加到精灵组

self.bullets.add(bullet)

def explode(self,screen):

new_rect=self.rect

for i in (1,2,3,4):

super.__init__("./images/me_destroy_2.png")

self.rect.centerx=new_rect.centerx

self.rect.centery=new_rect.centery

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

pygame.display.update()

class Bullet(GameSprite):

"""子弹精灵"""

def __init__(self):

#调用父类方法,设置子弹图片,设置初始速度

super().__init__("./images/bullet1.png",-2)

def update(self):

#让子弹垂直运行

super().update()

if self.rect.bottom<0:

self.kill()

def __del__(self):

print("子弹被销毁")

运行结果:

2019118131028372.jpg

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: python实现飞机大战小游戏

本文地址: http://www.cppcns.com/jiaoben/python/285094.html

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、付费专栏及课程。

余额充值