代码修改bug,添加注释等,獾的速度加快之后很难……

git地址:

https://github.com/Jailman/blowupyrcastle.git

游戏资源使用了文章中附带的下载,原版文章请看这里:

http://blog.jobbole.com/46308/

附一些基本的数学知识

如图比如以角A为例
sinA=对边:斜边=BC:AC
cosA=临边:斜边=AB:AC
tanA=对边:临边=BC:AB
cotA=临边:对边=AB:BC

#!/usr/bin/python
#coding=utf8# 1 - Import library
import cStringIO
import pygame
import random
import math
from pygame.locals import *
from os import remove# 2 - Initialize the game
pygame.init()
pygame.display.set_caption('捍卫荣誉')
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[130,240]
acc=[0,0] #[0]是击中数,[1]是发射数
arrows=[] #发射箭头列表,点击鼠标时向其中填充bullet列表
badtimer=100
badtimer1=0
badguys=[[640, random.randint(40,400)]]
healthvalue=194 #总血量
pygame.mixer.init()# 3 - Load images
start = pygame.image.load("resources/images/start.png")
grass = pygame.image.load("resources/images/bg2.png")
castle = pygame.image.load("resources/images/hq1.png")
player = pygame.image.load("resources/images/p1.1.png")
player1 = pygame.image.load("resources/images/p1.1.png")
player2 = pygame.image.load("resources/images/p1.2.png")
arrow = pygame.image.load("resources/images/bullet6.png")
badguyimg1 = pygame.image.load("resources/images/badguy1.1.png")
badguyimg2 = pygame.image.load("resources/images/badguy1.2.png")
badguyimg3 = pygame.image.load("resources/images/badguy1.3.png")
badguyimg4 = pygame.image.load("resources/images/badguy1.4.png")
badguyimgs = [badguyimg1, badguyimg2, badguyimg3, badguyimg4]
# badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover2.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
begin = pygame.mixer.Sound("resources/audio/start.wav")
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
win = pygame.mixer.Sound("resources/audio/win.wav")
lost = pygame.mixer.Sound("resources/audio/lost.wav")
bgm = 'resources/audio/cowBGM.wav'
hit_castle = pygame.mixer.Sound("resources/audio/explode2.wav")
begin.set_volume(0.50)
hit.set_volume(0.07)
enemy.set_volume(0.20)
shoot.set_volume(0.07)
win.set_volume(0.25)
hit_castle.set_volume(0.18)
pygame.mixer.music.load(bgm)
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)#开局画面
running = 1
while running:screen.fill(0)screen.blit(start, (0,0))#提示按键开始font = pygame.font.Font(None, 30)text1 = font.render("Press [SPACE] to start", True, (255,0,0))screen.blit(text1, (230,450)) #调整显示文字位置for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key==K_SPACE:begin.play()running = 0if event.type == pygame.QUIT:pygame.quit()exit(0)pygame.display.flip()# 按下确定键后的透明渐变效果
from PIL import Image
def addTransparency(img, factor):  img = img.convert('RGBA')img_blender = Image.new('RGBA', img.size, (0,0,0,0))  img = Image.blend(img_blender, img, factor)  return img
img = Image.open("resources/images/start.png")
tran = 1
while tran > 0.8:img = addTransparency(img, factor = tran)imgBuf = cStringIO.StringIO(img.tobytes())imgx = pygame.image.frombuffer(imgBuf.getvalue(), (640,480), "RGBA")screen.blit(imgx, (0,0))tran -= 0.001for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()exit(0)pygame.display.flip()# 4 - keep looping through
running = 1
exitcode = 0
n = 0
while running:badtimer-=1# 5 - clear the screen before drawing it againscreen.fill(0)# 6 - draw the screen elementsfor 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(grass, (0,0))screen.blit(castle,(0,30))screen.blit(castle,(0,135))screen.blit(castle,(0,240))screen.blit(castle,(0,345 ))# 6.1 - Set player position and rotationposition = pygame.mouse.get_pos()angle = math.atan2(position[1]-(playerpos[1]+player.get_height()/2),position[0]-(playerpos[0]+player.get_width()/2))# print angle# playerrot = pygame.transform.rotate(player, 360-angle*57.29)playerrot = pygame.transform.rotate(player, 360-180*angle/math.pi) #180*angle/math.pi为偏转角度playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)screen.blit(playerrot, playerpos1)# 6.2 - Draw arrowsfor bullet in arrows: #arrow中的bullet列表是在按鼠标发射时追加的,bullet[0]是atan(y,x)# print bulletindex=0velx=math.cos(bullet[0])*10 #乘数调整子弹横向速度# print math.cos(bullet[0])vely=math.sin(bullet[0])*10 #乘数调整子弹竖向速度# print math.sin(bullet[0])bullet[1]+=velxbullet[2]+=velyif bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:arrows.pop(index)index+=1for projectile in arrows:arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)screen.blit(arrow1, (projectile[1], projectile[2]))# 6.3 - Draw badgersif badtimer==0:badguys.append([640, random.randint(50,430)])badtimer=100-(badtimer1*2)if badtimer1>=35:badtimer1=35else:badtimer1+=5index=0for badguy in badguys:if badguy[0]<-64:badguys.pop(index)badguy[0]-=1 #调整獾的移动速度# 6.3.1 - Attack castlebadrect=pygame.Rect(badguyimg1.get_rect())badrect.top=badguy[1]badrect.left=badguy[0]if badrect.left<64:# hit.play()hit_castle.play()healthvalue -= random.randint(5,20) #敌人碰撞城堡掉血badguys.pop(index)#hit playerplayerrect = pygame.Rect(player.get_rect())playerrect.left = playerpos[0] - 32 #增减一些值使触碰画面看上去更贴合playerrect.top = playerpos[1] - 10  #增减一些值使触碰画面看上去更贴合# print playerrectif  badrect.colliderect(playerrect):hit.play()healthvalue -= random.randint(3,12) #玩家碰撞敌人掉血badguys.pop(index)#6.3.2 - Check for collisionsindex1=0for bullet in arrows:bullrect=pygame.Rect(arrow.get_rect())bullrect.left=bullet[1]bullrect.top=bullet[2]if badrect.colliderect(bullrect):enemy.play()acc[0]+=1badguys.pop(index)arrows.pop(index1)index1+=1# 6.3.3 - Next bad guyindex+=1for badguy in badguys:# screen.blit(badguyimg, badguy)n = n + 1if n > (len(badguyimgs)) * 10-1:n = 0screen.blit(badguyimgs[int(n/10)], badguy)# 6.4 - Draw clockfont = 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)# 6.5 - Draw health barscreen.blit(healthbar, (5,5))for health1 in range(healthvalue):screen.blit(health, (health1+8,8))#在健康值上方显示文字hfont = pygame.font.Font(None, 20)htext = hfont.render("Health", True, (255,0,0))screen.blit(htext, (50,8)) #调整显示文字位置,覆盖在健康值上方# 7 - update the screenpygame.display.flip()# 8 - loop through the eventsfor event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key==K_w:keys[0]=Trueelif event.key==K_a:keys[1]=Trueelif event.key==K_s:keys[2]=Trueelif event.key==K_d:keys[3]=Trueif event.type == pygame.KEYUP:if event.key==pygame.K_w:keys[0]=Falseelif event.key==pygame.K_a:keys[1]=Falseelif event.key==pygame.K_s:keys[2]=Falseelif event.key==pygame.K_d:keys[3]=False# check if the event is the X button if event.type==pygame.QUIT:# if it is quit the gamepygame.quit() exit(0)if event.type==pygame.MOUSEBUTTONDOWN:shoot.play()player = player2position=pygame.mouse.get_pos()acc[1]+=1arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])if event.type==pygame.MOUSEBUTTONUP:    player = player1# 9 - Move playerif keys[0]:if not playerpos[1] < 0:playerpos[1]-=3elif keys[2]:if not playerpos[1] > height:playerpos[1]+=3if keys[1]:if not playerpos[0] < 100:playerpos[0]-=3elif keys[3]:if not playerpos[0] > width:playerpos[0]+=3#10 - Win/Lose checkif pygame.time.get_ticks()>=90000:running=0exitcode=1if healthvalue<=0:running=0exitcode=0if acc[1]!=0:accuracy=acc[0]*1.0/acc[1]*100else: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().centerxtextRect.centery = screen.get_rect().centery+24pygame.mixer.music.set_volume(0)lost.play()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().centerxtextRect.centery = screen.get_rect().centery+24screen.blit(youwin, (0,0))pygame.mixer.music.set_volume(0)win.play()screen.blit(text, textRect)
ticksstart = pygame.time.get_ticks()# 作为延时开启背景音乐
while 1:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()exit(0)ticksend = pygame.time.get_ticks()ticksdiff = ticksend - ticksstart #计算延时if ticksdiff == 3500: #开启背景音乐pygame.mixer.music.set_volume(0.25)pygame.display.flip()

炸掉你的城堡!(pygame獾兔大战)相关推荐

  1. Python游戏之Pygame——太空飞机大战(三)

    上一篇(Python游戏之Pygame--太空飞机大战(二))完成了敌机类以及敌机坠毁时释放包裹类,这一篇将给出英雄战机类和处理.由于英雄战机是由游戏者操控的,所以要处理操控事件,比如往那个方向飞,发 ...

  2. Python游戏之Pygame——太空飞机大战(四)

    上一篇(Python游戏之Pygame--太空飞机大战(三))完成了英雄战机和星空,那么基本上飞机大战的主要元素都已经完成,该是总结成功玩自己游戏的时候了. 哦,差点忘了,Bullet类对于普通子弹和 ...

  3. Python游戏之Pygame——太空飞机大战(二)

    上一篇(Python游戏之Pygame--太空飞机大战(一))文章简单对游戏进行了说明,给出了部分配置文件以及子弹类.下面给出敌机类和方法. 大家直到,飞机必须能非,最好能非直线飞行.因此必须有X_s ...

  4. 学习 Python 之 Pygame 开发坦克大战(四)

    学习 Python 之 Pygame 开发坦克大战(四) 坦克大战添加音效 1. 初始化音效 2. 加入游戏开始音效和坦克移动音效 3. 添加坦克开火音效 4. 添加装甲削减音效 5. 添加坦克爆炸音 ...

  5. pygame实现飞机大战游戏

    标题:pygame实现飞机大战游戏 源码链接:我的github地址 一.具体演示 1.怪兽分为小怪,和大怪:大怪可以发射子弹 2.英雄飞机共有10个生命值 3.英雄飞机可以上下左右移动 4.显示了英雄 ...

  6. 学习 Python 之 Pygame 开发坦克大战(五)

    学习 Python 之 Pygame 开发坦克大战(五) 坦克大战完善地图 1. 创建砖墙 2. 给砖墙增加子弹击中的碰撞效果 3. 给砖墙添加坦克不能通过的碰撞效果 4. 添加石墙 5. 添加玩家基 ...

  7. 体感游戏 | 手势识别玩飞机大战游戏(一) 用pygame实现飞机大战小游戏

    Color Space OpenCV与AI深度学习 后面将分四篇文章来介绍实现手势识别控制飞机大战游戏的功能,它们分别是: 使用Pygame实现简易飞机大战小游戏 使用Python+OpenCV实现简 ...

  8. python飞机大战源码素材包_python(pygame)滑稽大战(类似飞机大战) 教程

    成品已录制视频投稿B站(本文目前实现了基础的游戏功能),点击观看 本帖曾在百度贴吧直播,但由于人气低反响差已停更. 项目稽忽悠不(github)地址(目前只上传了素材,代码还在整理中): https: ...

  9. Python实验,用pygame做飞机大战游戏设计

    飞机大战游戏设计 摘 要:根据课程要求,以及面向对象程序设计的编程思想,在Windows操作系统环境下,运用PyCharm编译程序,以Python语言为开发语言,最终实现飞机大战游戏相应的游戏操作功能 ...

最新文章

  1. .net和java互操作
  2. 当当架构部张亮:从码农到大牛,技术与心境的双重提升
  3. 想知道深度学习卷积在GPU上如何优化吗?“大神”赵开勇带你深入浅出
  4. java异步框架feed,Java:IO流里面的BuffeedReader
  5. vue 禁止显示本网页由、、_【VUE/JS】vue和js禁止浏览器页面后退
  6. BEA-141281 unable to get file lock, will retry ...
  7. replace 替换字符串
  8. MyBatis课程5
  9. Avro从入门到入土
  10. windows API 菜鸟学习之路(二)
  11. linux读取 dev tty0,linux命令: ls命令
  12. 《作业指导书》的发布管理问题与解决办法
  13. python学习笔记之初识Python
  14. 微型计算机原理 备课,微机原理备课教案要点.ppt
  15. matlab的s变换,MATLAB - Transforms
  16. 微信开放平台Android常见问题
  17. 黄卫龙 谈“太极起势”的练法
  18. JS变量、数据类型及运算符
  19. Mongodb 监控安装配置
  20. 【拼多多】新手卖家的启蒙贴 ,如何快乐的做图,快乐的开店

热门文章

  1. Java输出一个*号十字架
  2. Android 11.0 12.0系统默认授予读写权限给第三方app
  3. android 进程被回收,Android开发进阶:Activity和进程的回收和状态恢复
  4. Excel设置自动恢复功能以及数据恢复教程
  5. VUE项目中优雅使用EasyPlayer实时播放摄像头多种格式视频
  6. Bootstrap 下拉菜单和按钮
  7. Consumer消息拉取和消费流程分析
  8. c8051f310烧录_C8051F烧录器-C8051F系列烧录工具下载v1.0.0.1 官方最新版-西西软件下载...
  9. 文档在线查看功能的实现
  10. Windows 10 中的存储空间