Python制作的射击游戏
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygame
>>>
运行文件里的Python代码
添加游戏资源
第一步:你好,兔子
# 1 - Import library
import pygame
from pygame.locals import * # 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height)) # 3 - Load images
player = pygame.image.load("resources/images/dude.png") # 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
- 导入pygame库,这一步能让你使用库里提供的功能
- 初始化pygame,设置展示窗口
- 加载作为兔子的图片
- 不停地循环执行接下来的部分
- 在给屏幕画任何东西之前用黑色进行填充
- 在屏幕的(100,100)坐标出添加你加载的兔子图片
- 更新屏幕
- 检查一些新的事件,如果有退出命令,则终止程序的执行。
第二步:添加背景
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
for x in range(width/grass.get_width()+1):
for y in range(height/grass.get_height()+1):
screen.blit(grass,(x*100,y*100))
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345 ))
第三步:让兔子能够移动
keys = [False, False, False, False]
playerpos=[100,100]
screen.blit(player, (100,100))
改成:
screen.blit(player, playerpos)
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
第四步:让兔子转向
import math
然后,把#6部分的最后一行用一下代码替换:
# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1)
第五步:射吧!兔子
acc=[0,0]
arrows=[]
arrow = pygame.image.load("resources/images/bullet.png")
现在,当玩家点击鼠标,就需要射出一支箭头。在#8部分加上以下代码:
if event.type==pygame.MOUSEBUTTONDOWN:
position=pygame.mouse.get_pos()
acc[1]+=1
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 6.2 - Draw arrows
for bullet in arrows:
index=0
velx=math.cos(bullet[0])*10
vely=math.sin(bullet[0])*10
bullet[1]+=velx
bullet[2]+=vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
index+=1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
第六部:獾,拿上武器!
- 添加一个坏蛋的列表
- 更新坏蛋的信息,并且检查它们是否超出屏幕范围
- 展示这些坏蛋
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg=badguyimg1
# 6.3 - Draw badgers
if badtimer==0:
badguys.append([640, random.randint(50,430)])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
import random
最后,把一行代码添加到#4部分的while表达式后面:
badtimer-=1
# 6.3.1 - Attack castle
badrect=pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64:
healthvalue -= random.randint(5,20)
badguys.pop(index)
# 6.3.3 - Next bad guy
第七部:獾与箭头的碰撞
#6.3.2 - Check for collisions
index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
acc[0]+=1
badguys.pop(index)
arrows.pop(index1)
index1+=1
第八步:添加健康值和时间的显示
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
上面的代码使用了PyGame默认的大小为24的字体。这个字体用来显示时间信息。
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
接下来添加代码到#6.4部分后面:
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
第九步:赢或输
- 停止运行游戏
- l设置游戏的输出
- 停止运行游戏
- l设置游戏的输出
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 4 - keep looping through
while 1:
badtimer-=1
改成:
# 4 - keep looping through
running = 1
exitcode = 0
while running:
badtimer-=1
<ignore_js_op>
第十步:免费的音乐和声音效果
pygame.mixer.init()
然后在#3部分加载声音然后设置声音:
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# section 6.3.1 after if badrect.left<64:
hit.play()
# section 6.3.2 after if badrect.colliderect(bullrect):
enemy.play()
# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
那接下来呢?
Python制作的射击游戏的更多相关文章
- 使用python制作趣味小游戏—投骰子
1.模拟真实环境掷骰子 从Python标准库中调用模块:random——random中包含以各种方式生成随机数的函数 从random中引用randint这一函数——骰子都是有固定面数 from ran ...
- Unity3D--学习太空射击游戏制作(二)
步骤三:创建主角 游戏的主角是一艘太空飞船,我们将使用一个飞船模型作为游戏的主角,并赋予他一个脚本,控制他的运动,游戏体的组件必须依赖于脚本才能运行. 01:在Project窗口找到Player.fb ...
- 少儿编程Scratch第四讲:射击游戏的制作,克隆的奥秘
上周的宇宙大战射击游戏中,我们只完成了宇宙飞船发射子弹的部分.还未制作敌对方.这周制作了敌方-飞龙,飞龙随机在屏幕上方出现,如果被子弹打中,则得分,飞龙和子弹都消失. 敌方:飞龙:计分. 目的 目的: ...
- Unity3D--学习太空射击游戏制作(一)
近期买了本书在学习一些Unity3D的东西,在了解了Unity3D工具的基本面板后开始学习一个太空射击游戏的开发过程. 首先下载一个关于本游戏的资源文件,(百度云下载地址:http://pan.bai ...
- 教你用Python自制拼图小游戏,一起来制作吧
摘要: 本文主要为大家详细介绍了python实现拼图小游戏,文中还有示例代码介绍,感兴趣的小伙伴们可以参考一下. 开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Pyt ...
- 练手项目:利用pygame库编写射击游戏
本项目使用pygame模块编写了射击游戏,目的在于训练自己的Python基本功.了解中小型程序框架以及学习代码重构等.游戏具有一定的可玩性,感兴趣的可以试一下. 项目说明:出自<Python编程 ...
- Pygame制作答题类游戏的实现
代码地址如下:http://www.demodashi.com/demo/13495.html 概述 个人比较喜欢玩这些答题类的游戏,在这类的游戏中其实存在着一些冷知识在里面.练习pygame的过程中 ...
- 使用Cocos2dx-JS开发一个飞行射击游戏
一.前言 笔者闲来无事,某天github闲逛,看到了游戏引擎的专题,引起了自己的兴趣,于是就自己捣腾了一下Cocos2dx-JS.由于是学习,所谓纸上得来终觉浅,只是看文档看sample看demo,并 ...
- Unreal Engine 4 系列教程 Part 10:制作简单FPS游戏
.katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...
随机推荐
- babylon 初试
出于对web端3D技术的对比,以及WebGL的发展现状和WebGPU的发展前景,我觉得有必要涉猎一下babylon.js了. 可以参考一下下列文章: 1⃣️下一代web端图形接口现状与前景:https ...
- Array.prototype.filter()
1. filter() 方法:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 ——filter() 不会对空数组进行检测 ——filter() 不会改变原始数组 2. 语法: ...
- Tensorflow 用训练好的模型预测
本节涉及点: 从命令行参数读取需要预测的数据 从文件中读取数据进行预测 从任意字符串中读取数据进行预测 一.从命令行参数读取需要预测的数据 训练神经网络是让神经网络具备可用性,真正使用神经网络时,需要 ...
- 日志备份shell脚本
脚本注释已经很清楚了,就不再啰嗦了. 算了,还是多说一句吧,脚本设计完成之后,就可以加入计划任务,让电脑帮你打工了. 注:关于计划任务crontab,我会专门写一篇笔记. 最最最后一句, find $ ...
- 无监督异常检测之卷积AE和卷积VAE
尝试用卷积AE和卷积VAE做无监督检测,思路如下: 1.先用正常样本训练AE或VAE 2.输入测试集给AE或VAE,获得重构的测试集数据. 3.计算重构的数据和原始数据的误差,如果误差大于某一个阈值, ...
- 【并行计算-CUDA开发】关于共享内存(shared memory)和存储体(bank)的事实和疑惑
关于共享内存(shared memory)和存储体(bank)的事实和疑惑 主要是在研究访问共享内存会产生bank conflict时,自己产生的疑惑.对于这点疑惑,网上都没有相关描述, 不管是国内还 ...
- PHP学习(9)——错误和异常处理
1.Exception类 这个类是PHP为异常处理提供的内置类.构造函数的两个参数分别是错误消息和错误代码. 除了构造函数之外,该类还提供了如下的内置方法: · getCode() 返回传递给构造函数 ...
- merge效率
测试merge效率 测试说明: MERGE是oracle提供的一种特殊的sql语法,非常适用于数据同步场景,即: (把A表数据插到B表,如果B表存在相同主键的记录则使用A表数据对B表进行更新) 数 ...
- [bzoj1775][Usaco2009 Dec]Vidgame 电视游戏问题_背包dp
1775: [Usaco2009 Dec]Vidgame 电视游戏问题 题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1775 题解: 发 ...
- MFC使用ado连接SQLserver
https://blog.csdn.net/GK_2014/article/details/50530103