飞机大战源代码

合集下载

python实例:利用pygame实现小游戏“飞机大战”

python实例:利用pygame实现小游戏“飞机大战”

python实例:利⽤pygame实现⼩游戏“飞机⼤战”0、程序代码代码1:1import random2import pygame34# 屏幕⼤⼩的常量5 SCREEN_RECT = pygame.Rect(0, 0, 480, 700)6# 刷新的帧率7 FRAME_PER_SEC = 608# 创建敌机的定时器常量9 CREATE_ENEMY_EVENT = EREVENT10# 英雄发射⼦弹事件11 HERO_FIRE_EVENT = EREVENT+112#⼦弹速度13 BULLET_SPEED = -2.5141516class GameSprite(pygame.sprite.Sprite):17""""飞机⼤战游戏精灵"""1819def__init__(self, image_name, speed = 1):20# 调⽤⽗亲的初始化⽅法21 super().__init__()22# 定义对象的属性23 self.image = pygame.image.load(image_name)24 self.rect = self.image.get_rect()25 self.speed = speed2627def update(self):28#在屏幕的垂直⽅向上移动29 self.rect.y += self.speed303132class Background(GameSprite):33""""游戏背景精灵"""3435def__init__(self, is_alt = False):36# 1.调⽤⽗类构造⽅法37 super().__init__("./images/background.png")38# 2.判断是否与前图像循环重合,若否,则需重新设置初始位置39if is_alt:40 self.rect.y = -self.rect.height414243def update(self):44# 1.调⽤⽗类的⽅法,,,注意super后⾯要加括号!!!45 super().update()46# 2.判断是否移出屏幕47if self.rect.y >= SCREEN_RECT.height:48 self.rect.y = -self.rect.height495051class Enemy(GameSprite):52""""敌机精灵"""5354def__init__(self):55# 1.调⽤⽗类⽅法,创建敌机精灵56 super().__init__("./images/enemy1.png")57# 2. 指定敌机的初始随机速度 1-2-358 self.speed = random.randint(1,3)59# 3.指定敌机的初始随机位置60 self.rect.bottom = 06162 max_x = SCREEN_RECT.width - self.rect.width63 self.rect.x = random.randint(0, max_x)646566def update(self):6768# 1.调⽤⽗类⽅法,保持垂直⽅向的飞⾏69 super().update()70# 2.判断是否⾮出屏幕,如果是,需要从精灵组删除敌机71if self.rect.y >= SCREEN_RECT.height:72#print("飞出屏幕,需要从精灵组删除...")73# kill⽅法可以将精灵从精灵组中移除74 self.kill()7576def__del__(self):77#print("敌机挂了%s" %self.rect)78pass798081class Hero(GameSprite):82"""英雄精灵"""8384def__init__(self):85# 1.调⽤⽗类⽅法,设置image和speed86 super().__init__("./images/me1.png", speed = 0)87 self.speed1 = 088# 2.设置英雄的初始位置89 self.rect.centerx = SCREEN_RECT.centerx90 self.rect.bottom = SCREEN_RECT.bottom - 10091# 3.创建⼦弹精灵组92 self.bullets = pygame.sprite.Group()9394def update(self):95#(错误的判断句,会导致⼀旦出界就很难再恢复回来)if 0 <= self.rect.x <= SCREEN_RECT.width - self.rect.width: 96 self.rect.x += self.speed97if self.rect.x < 0:98 self.rect.x = 099elif self.rect.right > SCREEN_RECT.width:100 self.rect.right = SCREEN_RECT.width101102 self.rect.y += self.speed1103if self.rect.y < 0:104 self.rect.y = 0105elif self.rect.bottom > SCREEN_RECT.height:106 self.rect.bottom = SCREEN_RECT.height107108109def fire(self):110#print("发射⼦弹")111# 1.创建⼦弹精灵112 bullet = Bullet()113# 2.设置精灵位置114 bullet.rect.bottom = self.rect.y115 bullet.rect.centerx = self.rect.centerx116# 3.将精灵添加到精灵组117 self.bullets.add(bullet)118119120class Bullet(GameSprite):121""""⼦弹精灵"""122123def__init__(self):124# 调⽤⽗类⽅法125 super().__init__("./images/bullet1.png", BULLET_SPEED)126127def update(self):128 super().update()129if self.rect.bottom < 0:130 self.kill()131132def__del__(self):133#print("⼦弹被销毁")134passView Code代码2:1from plane_sprites import *2# 游戏主程序34class PlaneGame(object):5""""飞机⼤战主游戏"""67def__init__(self):8print("游戏初始化")910# 1.创建游戏的窗⼝11 self.screen = pygame.display.set_mode(SCREEN_RECT.size)12# 2.创建游戏的时钟13 self.clock = pygame.time.Clock()14# 3.调⽤私有⽅法,精灵和精灵组的创建15 self.__create_sprites()16# 4.设置定时器事件——创建敌机 1s17 pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)18 pygame.time.set_timer(HERO_FIRE_EVENT, 300)1920def__create_sprites(self):21# 创建背景精灵和精灵组22 bg1 = Background()23 bg2 = Background(True)24 self.back_group = pygame.sprite.Group(bg1, bg2)25# 创建敌机精灵26 self.enemy_group = pygame.sprite.Group()27# 创建英雄精灵28 self.hero = Hero()29 self.hero_group = pygame.sprite.Group(self.hero)303132def start_game(self):33print("游戏开始...")3435while True:36# 1.设置刷新帧率37 self.clock.tick(FRAME_PER_SEC)38# 2.事件监听39 self.__event_handler()40# 3.碰撞检测41 self.__check_collide()42# 4.更新/绘制精灵组43 self.__update_sprites()44# 5.更新显⽰45 pygame.display.update()464748def__event_handler(self):49for event in pygame.event.get():50#判断是否退出游戏51if event.type == pygame.QUIT:52 PlaneGame.__game_over()53elif event.type == CREATE_ENEMY_EVENT:54#print("敌机出现。

python版飞机大战代码分享

python版飞机大战代码分享

python版飞机⼤战代码分享利⽤pygame实现了简易版飞机⼤战。

源代码如下:# -*- coding:utf-8 -*-import pygameimport sysfrom pygame.locals import *from pygame.font import *import timeimport randomclass Hero(object):#玩家英雄类def __init__(self, screen_temp):self.x = 210self.y = 700self.life = 21# self.life = 100self.image = pygame.image.load("./feiji/hero1.png")self.screen = screen_tempself.bullet_list = []#⽤来存储⼦弹对象的引⽤#爆炸效果⽤的如下属性self.hit = False #表⽰是否要爆炸self.bomb_list = [] #⽤来存储爆炸时需要的图⽚self.__create_images() #调⽤这个⽅法向bomb_list中添加图⽚self.image_num = 0 #⽤来记录while True的次数,当次数达到⼀定值时才显⽰⼀张爆炸的图,然后清空,,当这个次数再次达到时,再显⽰下⼀个爆炸效果的图⽚ self.image_index = 0#⽤来记录当前要显⽰的爆炸效果的图⽚的序号def __create_images(self):#添加爆炸图⽚self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n1.png"))self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n2.png"))self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n3.png"))self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n4.png"))def display(self):#显⽰玩家的飞机#如果被击中,就显⽰爆炸效果,否则显⽰普通的飞机效果if self.hit == True:self.screen.blit(self.bomb_list[self.image_index], (self.x, self.y))#(self.x, self.y)是指当前英雄的位置#blit⽅法(⼀个对象,左上⾓位置)self.image_num += 1print(self.image_num)if self.image_num == 7:self.image_num = 0self.image_index += 1print(self.image_index) #这⾥⼦弹打住英雄时没有被清除掉,所以打⼀下,就死了if self.image_index > 3:time.sleep(1)exit()#调⽤exit让游戏退出#self.image_index = 0else:if self.x< 0: #控制英雄,不让它跑出界⾯self.x = 0elif self.x > 382:self.x = 382if self.y < 0:self.y = 0elif self.y > 750:self.y = 750self.screen.blit(self.image,(self.x, self.y))#z这⾥是只要没有被打中,就⼀直是刚开始的样⼦#不管玩家飞机是否被击中,都要显⽰发射出去的⼦弹for bullet in self.bullet_list:bullet.display()bullet.move()def move(self, move_x,move_y):self.x += move_xself.y += move_ydef fire(self):#通过创建⼀个⼦弹对象,完成发射⼦弹bullet = Bullet(self.screen, self.x, self.y)#创建⼀个⼦弹对象self.bullet_list.append(bullet)def bomb(self):self.hit = Truedef judge(self):global lifeif life <= 0:self.bomb()class Bullet(object):#玩家⼦弹类def __init__(self, screen_temp, x_temp, y_temp):self.x = x_temp + 40self.y = y_temp - 20self.image = pygame.image.load("./feiji/bullet.png")self.screen = screen_tempdef display(self):self.screen.blit(self.image, (self.x, self.y))def move(self):self.y -= 10class Bullet_Enemy(object):#敌机⼦弹类def __init__(self, screen_temp, x_temp, y_temp):self.x = x_temp + 25self.y = y_temp + 30self.image = pygame.image.load("./feiji/bullet1.png")self.screen = screen_tempdef display(self):self.screen.blit(self.image,(self.x,self.y))def move(self, hero):self.y += 10global lifeif (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): #if self.y in range(hero.y, hero.y + 40) and self.x in range(hero.x, hero.x + 40):life -= 10#self.bullet_list.remove()print("---judge_enemy---")return Trueif life<=0:hero.bomb()return Falseclass Bullet_Boss(object):#boss⼦弹类1def __init__(self, screen_temp, x_temp, y_temp):self.x = x_temp + 80self.y = y_temp + 230self.image = pygame.image.load("./feiji/bullet2.png")self.screen = screen_tempdef display(self):self.screen.blit(self.image, (self.x, self.y))def move(self, hero):self.y += 6self.x += 2global lifeif (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): #if self.y in range(hero.y, hero.y + 40) and self.x in range(hero.x, hero.x + 40):life -= 20#self.bullet_list.remove()print("---judge_boss---")return Trueif life<=0:hero.bomb()return Falseclass Bullet_Boss1(object):#boss⼦弹类2def __init__(self, screen_temp, x_temp, y_temp):self.x = x_temp + 80self.y = y_temp + 230self.image = pygame.image.load("./feiji/bullet2.png")self.screen = screen_tempdef display(self):self.screen.blit(self.image, (self.x, self.y))def move(self, hero):self.y += 6self.x -= 2global lifeif (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): #if self.y in range(hero.y, hero.y + 40) and self.x in range(hero.x, hero.x + 40):life -= 20#self.bullet_list.remove()print("---judge_boss---")return Trueif life<=0:hero.bomb()return Falseclass Bullet_Boss2(object):#boss⼦弹类3def __init__(self, screen_temp, x_temp, y_temp):self.x = x_temp + 80self.y = y_temp + 230self.image = pygame.image.load("./feiji/bullet2.png")self.screen = screen_tempdef display(self):self.screen.blit(self.image, (self.x, self.y))def move(self, hero):self.y += 6global lifeif (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): #if self.y in range(hero.y, hero.y + 40) and self.x in range(hero.x, hero.x + 40):life -= 20#self.bullet_list.remove()print("---judge_boss---")return Trueif life<=0:hero.bomb()return Falseclass Base(object):#基类类似于抽象类def __init__(self, screen_temp, x, y, image_name):self.x = xself.y = yself.screen = screen_tempself.image = pygame.image.load(image_name)self.alive = Truedef display(self):if self.alive == True:self.screen.blit(self.image, (self.x, self.y))def move(self):self.y += 5class bomb_bullet(Base):#炸弹类def __init__(self, screen_temp):Base.__init__(self, screen_temp, random.randint(45, 400), 0, "./feiji/bomb.png")def judge(self, hero):if (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): self.alive = Falsehero.bomb()if self.y >= 850:#self.alive = Falseself.y = 0self.x = random.randint(45, 400)#print("bomb.y = %d"%self.y)class supply(Base):#补给类def __init__(self, screen_temp):Base.__init__(self, screen_temp, random.randint(45, 400), -300, "./feiji/bomb-1.gif")def judge(self, hero):global lifeif (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): self.alive = Falselife += 10if self.y >= 1500:self.y = 0self.x = random.randint(45, 400)self.alive = Trueclass clear_bullet(Base):def __init__(self, screen_temp):Base.__init__(self, screen_temp, random.randint(45, 400), 0, "./feiji/bomb-2.gif")self.alive = Falsedef judge(self, hero, enemies):global qq += 1#self.move()if q == 20:#self.move()self.alive = Trueq = 0if (hero.y <= self.y and self.y <= hero.y + 40) and (hero.x <= self.x and self.x <= hero.x + 100): self.alive = Falsefor enemy in enemies:enemy.hit == Trueclass EnemyPlane(object):#敌机类def __init__(self, screen_temp):self.x = random.randint(15, 480)self.y = 0self.image = pygame.image.load("./feiji/enemy0.png")self.screen = screen_tempself.bullet_list = []#⽤来存储⼦弹对象的引⽤#self.direction = "right"#⽤来设置这个飞机默认的移动⽅向self.hit = Falseself.bomb_list = []self.__create_images()self.image_num = 0self.image_index = 0#利⽤产⽣的随机数,随机确定飞机初始移动⽅向self.k = random.randint(1, 20)if self.k <= 10:self.direction = "right"elif self.k > 10:self.direction = "left"def display(self, hero):#显⽰敌⼈的飞机if not self.hit:self.screen.blit(self.image, (self.x,self.y))else:self.screen.blit(self.bomb_list[self.image_index], (self.x,self.y))self.image_num += 1if self.image_num == 3 and self.image_index < 3:self.image_num = 0self.image_index += 1#print(self.image_index)# if self.image_index > 2:# time.sleep(0.1)for bullet in self.bullet_list:bullet.display()if(bullet.move(hero)):self.bullet_list.remove(bullet)def move(self):#利⽤随机数来控制飞机移动距离,以及移动范围d1 = random.uniform(1,3)d2 = random.uniform(0.2,3)p1 = random.uniform(50,100)p2 = random.uniform(-200,0)if self.direction == "right":self.x += d1elif self.direction == "left":self.x -= d1if self.x > 480 - p1:#480 - 50self.direction="left"elif self.x < p2:self.direction = "right"self.y += d2def bomb(self):self.hit = Truedef __create_images(self):self.bomb_list.append(pygame.image.load("./feiji/enemy0_down1.png")) self.bomb_list.append(pygame.image.load("./feiji/enemy0_down2.png")) self.bomb_list.append(pygame.image.load("./feiji/enemy0_down3.png")) self.bomb_list.append(pygame.image.load("./feiji/enemy0_down4.png")) def fire(self):#利⽤随机数来控制敌机的开⽕,1/80的概率s = random.randint(0,800)bullet1 = Bullet_Enemy(self.screen, self.x, self.y)if s < 10:self.bullet_list.append(bullet1)class EnemyPlanes(EnemyPlane):#敌机群类继承⾃EnemyPlane类def __init__(self, screen_temp):EnemyPlane.__init__(self, screen_temp)self.num = 0self.enemy_list = [] #⽤列表存储产⽣的多架敌机self.screen = screen_tempdef add_enemy(self, num):#产⽣多架敌机的函数self.num = numfor i in range(num):enemy = EnemyPlane(self.screen)self.enemy_list.append(enemy)def display(self, hero):for i in range(self.num):self.enemy_list[i].display(hero)def move(self):for i in range(self.num):self.enemy_list[i].move()def fire(self):#s = random.randint(0,1000)for i in range(self.num):self.enemy_list[i].fire()class Boss(EnemyPlane):#boss敌机类继承⾃EnemyPlane类def __init__(self,screen_temp):EnemyPlane.__init__(self,screen_temp)self.x = 150self.y = 0self.bomb_list = []self.__create_images()self.image = pygame.image.load("./feiji/enemy2.png")self.screen = screen_tempself.bullet_list = []def __create_images(self):#self.bomb_list.append(pygame.image.load("./feiji/enemy2.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down1.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down2.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down3.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down4.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down5.png"))self.bomb_list.append(pygame.image.load("./feiji/enemy2_down6.png"))def display(self, hero):#显⽰敌⼈的飞机global g#print(g)self.screen.blit(self.bomb_list[g], (self.x,self.y))for bullet in self.bullet_list:bullet.display()if(bullet.move(hero)):self.bullet_list.remove(bullet)def move(self):d1 = 0self.y += 0def fire(self):global ss += 1bullet1 = Bullet_Boss(self.screen, self.x, self.y)bullet2 = Bullet_Boss1(self.screen, self.x, self.y)bullet3 = Bullet_Boss2(self.screen, self.x, self.y)if s == 20:s = 0self.bullet_list.append(bullet1)self.bullet_list.append(bullet2)self.bullet_list.append(bullet3)def judge1(hero,enemy):#判断敌机的炸毁for bullet1 in hero.bullet_list:if bullet1.y in range(int(enemy.y),int(enemy.y + 30)) and bullet1.x in range(int(enemy.x-10),int(enemy.x + 50)): hero.bullet_list.remove(bullet1)enemy.bomb()if bullet1.y < 0 or bullet1.x < 0 or bullet1.x > 480: #删除越界的玩家⼦弹hero.bullet_list.remove(bullet1)def judge3(hero,boss):#判断boss的炸毁global goal, g, goal0for bullet3 in hero.bullet_list:if bullet3.y in range(int(boss.y), int(boss.y + 60)) and bullet3.x in range(int(boss.x), int(boss.x + 100)):hero.bullet_list.remove(bullet3)g += 1boss.image = boss.bomb_list[g]print("g = %d"%g)if g >= 6:boss.y, g, goal = 0, 0, 0boss.bomb()goal0 += 10def clear_enemy(enemies):#清除敌机群类中被炸毁的敌机global goal, goal0for enemy in enemies.enemy_list:if enemy.hit == True and enemy.image_index == 3:enemies.enemy_list.remove(enemy)enemies.num -= 1goal += 1goal0 += 5print("goal = %d"%goal)if enemy.y >= 850:enemies.enemy_list.remove(enemy)enemies.num -= 1def judge_num(enemies):#判断频幕上敌⼈的数量,如果为零,继续添加敌⼈n = random.randint(1,5)if len(enemies.enemy_list) == 0:enemies.add_enemy(n)def show_text(screen_temp):#在屏幕上显⽰⽂字text = "GOAL:" + str(goal0) + "Life:" + str(life)font_size = 50pos = (0,0)color = (0,255,0)cur_font = pygame.font.SysFont("宋体",font_size)text_fmt = cur_font.render(text, 1, color)screen_temp.blit(text_fmt, pos)def creat_bomb(screen_temp):bomb = bomb_bullet(screen_temp)bomb_list = []bomb_list.apend(bomb)#定义的全局变量goal = 0 #玩家得分goal0 = 0g = 0 #击中boss的次数life = 100#⽣命值s = 0 #判断⼤boss是否发射⼦弹q = 0def main():#主函数执⾏#获取事件,⽐如按键等bb = Falsemove_x = 0move_y = 0pygame.init()screen = pygame.display.set_mode((480,852),0,32)# 210,400background = pygame.image.load("./feiji/background.png") pygame.display.set_caption("飞机⼤战")atlas = pygame.image.load("./feiji/New Atlas.png")#创建玩家飞机hero = Hero(screen)#创建敌机群enemis = EnemyPlanes(screen)enemis.add_enemy(5)#创建boss对象boss = Boss(screen)#创建炸弹对象bomb = bomb_bullet(screen)#创建补给对象supply0 = supply(screen)clear = clear_bullet(screen)left_key, right_key, up_key, down_key, done = 0, 0, 0, 0, 0 # mark = 0#⽤来判断boss发射⼦弹while True:if done:if done % 8 == 0:done = 1hero.fire()else:done += 1for event in pygame.event.get():#判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()#判断是否是按下了键if event.type == KEYDOWN :#down#检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:#print('left')move_x = -5left_key += 1#检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT:#print('right')elif event.key == K_w or event.key == K_UP:move_y = -5up_key += 1elif event.key == K_s or event.key == K_DOWN: move_y = 5down_key += 1#检测按键是否是空格键elif event.key == K_SPACE:#print('space')hero.fire()done = 1#enemis.fire()elif event.key == K_b:print('b')hero.bomb()if event.type == KEYUP:if event.key == K_a or event.key == K_LEFT: left_key -= 1if right_key == 0:move_x = 0else:move_x = 5if event.key == K_d or event.key == K_RIGHT: right_key -= 1if left_key == 0:move_x = 0else:move_x = -5if event.key == K_w or event.key == K_UP:up_key -= 1if down_key == 0:move_y = 0else:move_y = 5if event.key == K_s or event.key == K_DOWN: down_key -= 1if up_key == 0:move_y = 0else:move_y = -5if event.key == K_SPACE:done = 0screen.blit(background, (0, 0))hero.move(move_x, move_y)hero.display()hero.judge()enemis.display(hero)enemis.move()enemis.fire()bomb.display()bomb.judge(hero)bomb.move()supply0.display()supply0.judge(hero)supply0.move()#clear.display()#clear.judge(hero, enemis)#clear.move()for i in range(enemis.num):judge1(hero, enemis.enemy_list[i])#enemis.enemy_list[i].judge(hero)clear_enemy(enemis)judge_num(enemis)show_text(screen)boss.move()# mark+=1# if mark==8:boss.fire()# mark = 0#boss.judgejudge3(hero, boss)pygame.display.update()if __name__ == "__main__":main()⽅法是利⽤⾯向对象的思想,写了基本的敌机类、英雄类、武器类等,利⽤继承关系产⽣多架敌机。

python学习日记第五天(飞机大战)

python学习日记第五天(飞机大战)

#
if self.y<0:
#
return True
#
else:
#
return False
# class EnemyBullet(object):
# def __init__(self,x,y,screen):
#
self.x=x+30
#
self.y=y+30
#
self.screen=screen
#
self.image=pygame.image.load("./11/1 (8).png").convert()
def judge(self): if self.y<0: return True else: return False
# class Bullet(object):
# def __init__(self,x,y,screen):
#
self.x=x+40
#
self.y=y-20
#
self.screen=screen
bullet.display() bullet.move() def move_left(self): self.x-=10 def move_right(self): self.x+=10 def move_up(self): self.y-=10 def move_down(self): self.y+=10 def launch_bullet(self): new_bullet=PublicBullet(self.x,self.y,self.screen,) self.bullet_list.append(new_bullet) class HeroPlane(Plane): def __init__(self,screen,name): #设 置 飞 机 的 默 认 位 置 self.x=230 self.y=600 self.image_name = "./11/1 (13).png" super().__init__(screen,name) class EnemyPlane(Plane): def __init__(self,screen,name): self.x=0 self.y=0 self.image_name = "./11/1 (6).png" super().__init__(screen,name) self.direction="right" def move(self): if self.direction == "right": self.x+=2 elif self.direction=="left": self.x-=2 if self.x>480-50: self.direction="left" elif self.x<0: self.direction="right" def launch_bullet(self): number=random.randint(1,100) if number == 88: super().launch_bullet()

python飞机大战代码

python飞机大战代码

python飞机大战代码以下是一个简单的 python 飞机大战游戏的代码示例:```python。

import pygame。

import random。

# 初始化 Pygame。

pygame.init()。

#设置游戏窗口大小和标题。

WINDOW_WIDTH=640。

WINDOW_HEIGHT=480。

screen = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))。

pygame.display.set_caption("飞机大战")。

#加载背景图片。

background_img =pygame.image.load("background.jpg").convert()。

#加载玩家飞机图片和音效。

player_img = pygame.image.load("player.png").convert_alpha()。

player_explosion_sound = pygame.mixer.Sound("explosion.wav")。

#加载敌机图片和音效。

enemy_img = pygame.image.load("enemy.png").convert_alpha()。

enemy_explosion_sound = pygame.mixer.Sound("explosion.wav")。

#加载子弹图片和音效。

bullet_img = pygame.image.load("bullet.png").convert_alpha()。

bullet_sound = pygame.mixer.Sound("bullet.wav")。

#定义玩家飞机和敌机的初始位置和速度。

player_x = 300。

python飞机大战的核心语句

python飞机大战的核心语句

python飞机大战的核心语句Python飞机大战是一款非常经典的游戏,其核心语句包括以下几个方面:1. 导入必要的模块在Python飞机大战游戏中,需要导入Pygame模块来完成游戏的绘制、音效等功能。

通常使用以下语句进行导入:```pythonimport pygame```2. 初始化Pygame在导入Pygame模块后,需要初始化Pygame来设置窗口、音效等参数。

通常使用以下语句进行初始化:```pythonpygame.init()```3. 创建游戏窗口在Pygame中,使用display模块来创建游戏窗口。

通常使用以下语句创建大小为800x600的窗口:```pythonscreen = pygame.display.set_mode((800, 600))```4. 加载游戏资源在游戏中需要使用到音效、图片等资源,可以使用以下语句来加载:```pythonbg_img = pygame.image.load('bg.png')```5. 监听事件在游戏中需要监听玩家的键盘输入等事件,可以使用以下语句来监听:```pythonfor event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:# 玩家按下了空格键```6. 绘制游戏界面在游戏中需要绘制背景、敌机、玩家飞机等游戏元素,可以使用以下语句来绘制:```pythonscreen.blit(bg_img, (0, 0))```7. 更新游戏界面在每次绘制完游戏界面后,需要使用以下语句来更新:```pythonpygame.display.update()```上述是Python飞机大战的核心语句,其中还有很多游戏逻辑实现的代码,但以上这些语句是游戏实现的基础。

python实现飞机大战游戏(pygame版)

python实现飞机大战游戏(pygame版)

python实现飞机⼤战游戏(pygame版)简介使⽤python实现pygame版的飞机⼤战游戏;环境:Windows系统+python3.8.0游戏规则:1.点击“PLAY”或者按键“P”开始游戏;2.敌机根据设置频率从顶部随机位置⽣成,⽣成后向下移动;3.飞船在底部中间⽣成,玩家使⽤上下左右键控制飞船移动,敲击空格键发射⼦弹;4.⼦弹打到敌机,该敌机产⽣爆炸效果并累计分数到右上⾓;5.消灭10只飞机后,等级升⾼,敌机⽣成频率变快,下落速度也变快;6.当三条命都消失了,游戏结束。

游戏运⾏效果如下:实现过程1.新建⽂件“file.py”,⽤来存储信息到⽂件和读取⽂件的信息,本例⽤来存储和读取最⾼分;import pickle# filename = 'file/stats.pkl'# 存储信息到⽂件def save_file(obj, filename):statsObj = load_file(filename)if statsObj == 0:# 不存在⽂件时,直接保存字典with open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)else:# 存在⽂件时,只修改⽂件中的最⾼分for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':statsObj[key] = obj['highScore']obj = statsObjwith open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)# 读取信息def load_file(filename):try:with open(filename, 'rb') as f:return pickle.load(f)except FileNotFoundError:# 不存在⽂件则输⼊错误信息msg = "Sorry, the file " + filename + " does not exist."print(msg)return 0# obj = {'highScore': 20, 'points': 5}# obj = {'highScore': 50}# save_file(obj, filename)# filedata = load_file(filename)# print(filedata)2.k新建⽂件settings.py,⽤来定义⼀些必须的基本属性和初始值;import file as fclass Settings():def __init__(self):self.screen_width = 480self.screen_height = 660self.bg_color = (230, 230, 230)# ⼦弹设置(宽、⾼、颜⾊、最⼤数量)self.bullet_width = 5self.bullet_height = 15self.bullet_color = 255, 255, 255# 敌机移动频率self.enemy_frequency = 0# 加快游戏节奏的速度self.speedup_scale = 1.1# 分数的提⾼速度self.score_scale = 1.5self.initialize_settings()# 初始化统计信息self.reset_stats()# 统计信息⽂件路径self.filename = 'file/stats.pkl'# 游戏刚启动时处于⾮活动状态self.game_active = False# 读取⽂件的最⾼分,在任何情况下都不应重置最⾼得分statsObj = f.load_file(self.filename)if statsObj == 0:# 不存在⽂件则显⽰最⾼分0highScore = 0else:for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':highScore = valself.high_score = highScoredef initialize_settings(self):"""初始化随游戏进⾏⽽变化的设置"""self.player_move_speed = 2.5self.bullet_speed = 3self.enemy_move_speed = 1# 记分self.one_points = 50def increase_speed(self):"""提⾼速度设置"""# self.player_move_speed *= self.speedup_scaleself.bullet_speed *= self.speedup_scaleself.enemy_move_speed *= self.speedup_scaleself.one_points = int(self.one_points * self.score_scale)def reset_stats(self):"""初始化在游戏运⾏期间可能变化的统计信息"""# 可射失的数量self.player_limit = 3# 射击分数self.score = 0# 等级self.level = 1# 打中多少矩形升⼀级self.level_number = 10# ⽣成敌机频率间隔self.enemy_frequency_space = 503.新建⽂件enemy.py,⽤来定义敌机类(位置topleft随机⽣成)和声明⽅法move;import pygameimport randomfrom pygame.sprite import Spriteclass Enemy(Sprite):def __init__(self, enemy_down_imgs, settings):super(Enemy, self).__init__()self.image = pygame.image.load('images/enemy1.png')self.rect = self.image.get_rect()self.rect.topleft = [random.randint(0, settings.screen_width - self.rect.width), 0]self.down_imgs = enemy_down_imgsself.speed = settings.enemy_move_speedself.down_index = 0# 敌机移动,边界判断及删除在游戏主循环⾥处理def move(self):self.rect.top += self.speed4.新建⽂件player.py,⽤来定义玩家类(可上下左右移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Player(Sprite):def __init__(self, settings, screen):super(Player, self).__init__()self.settings = settingsself.screen = screenself.screen_rect = self.screen.get_rect()# 引⼊飞船图⽚并定位self.image = pygame.image.load('images/player.png')self.rect = self.image.get_rect()self.rect.centerx = self.screen_rect.centerxself.rect.bottom = self.screen_rect.bottom# 移动标志self.move_left = Falseself.move_right = Falseself.move_down = Falseself.move_up = Falsedef rotate(self, angle):# 图⽚旋转self.image = pygame.transform.rotate(self.image, angle)def scale(self, multiple):# 图⽚缩放self.image = pygame.transform.smoothscale(self.image, (multiple, multiple))def update(self):if self.move_left and self.rect.left > self.screen_rect.left:self.rect.centerx -= self.settings.player_move_speedif self.move_right and self.rect.right < self.screen_rect.right:self.rect.centerx += self.settings.player_move_speedif self.move_down and self.rect.bottom < self.screen_rect.bottom:self.rect.centery += self.settings.player_move_speedif self.move_up and self.rect.top > 0:self.rect.centery -= self.settings.player_move_speeddef draw_player(self):"""绘制飞船到屏幕"""self.screen.blit(self.image, self.rect)5.新建⽂件“bullet.py”,⽤来定义⼦弹类(位置在飞船的顶部,并往上移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Bullet(Sprite):""" ⼀个对飞船发射的⼦弹进⾏管理的类 """def __init__(self, settings, screen, player):""" 在飞船所处的位置创建⼀个⼦弹对象 """super(Bullet, self).__init__()self.screen = screen# 在 (0,0) 处创建⼀个表⽰⼦弹的矩形,再设置正确的位置self.rect = pygame.Rect(0, 0, settings.bullet_width, settings.bullet_height)self.rect.centerx = player.rect.centerx# 飞船顶部self.rect.bottom = player.rect.top# 存储⽤⼩数表⽰的⼦弹位置self.y = float(self.rect.y)self.color = settings.bullet_colorself.speed = settings.bullet_speeddef update(self):"""向上移动⼦弹"""# 更新表⽰⼦弹位置的⼩数值(⼦弹往右)self.y -= self.speed# 更新表⽰⼦弹的rect的位置self.rect.y = self.ydef draw_bullet(self):"""在屏幕上绘制⼦弹"""pygame.draw.rect(self.screen, self.color, self.rect)6.新建⽂件“button.py”,⽤来定义按钮类和相应⽅法,本例使⽤于绘制“PLAY”按钮;import pygame.fontclass Button():def __init__(self, screen, msg):"""初始化按钮的属性"""self.screen = screenself.screen_rect = screen.get_rect()# 设置按钮的尺⼨和其他属性self.width, self.height = 100, 30self.button_color = (216, 30, 6)self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 36)# 创建按钮的rect对象,并使其居中self.rect = pygame.Rect(0, 0, self.width, self.height)self.rect.center = self.screen_rect.center# 按钮的标签只需创建⼀次self.prep_msg(msg)def prep_msg(self, msg):"""将msg渲染为图像,并使其在按钮上居中"""self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.centerdef draw_button(self):# 绘制⼀个⽤颜⾊填充的按钮,再绘制⽂本self.screen.fill(self.button_color, self.rect)self.screen.blit(self.msg_image, self.msg_image_rect)7.新建⽂件“scoreboard.py”,⽤来定义记分板,本例使⽤于绘制左上⾓飞船(⽣命数)、顶部中间的“最⾼分”、右上⾓的“积分”和“等级”;import pygame.fontfrom pygame.sprite import Groupfrom player import Playerclass Scoreboard():"""显⽰得分信息的类"""def __init__(self, settings, screen):"""初始化显⽰得分涉及的属性"""self.screen = screenself.screen_rect = screen.get_rect()self.settings = settings# 显⽰得分信息时使⽤的字体设置self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 30)# 飞船缩放值self.scaleValue = 20# 准备初始得分图像\最⾼得分\等级self.prep_score()self.prep_high_score()self.prep_level()self.prep_players()def prep_score(self):"""将得分转换为渲染的图像"""rounded_score = int(round(self.settings.score, -1))score_str = '{:,}'.format(rounded_score)self.score_image = self.font.render(score_str, True, self.text_color)# 将得分放在屏幕右上⾓self.score_rect = self.score_image.get_rect()self.score_rect.right = self.screen_rect.right -20self.score_rect.top = 10def prep_high_score(self):""" 将最⾼得分转换为渲染的图像 """high_score = int(round(self.settings.high_score, -1))high_score_str = "{:,}".format(high_score)self.high_score_image = self.font.render(high_score_str, True, self.text_color)# 将最⾼得分放在屏幕顶部中央self.high_score_rect = self.high_score_image.get_rect()self.high_score_rect.centerx = self.screen_rect.centerxself.high_score_rect.top = self.score_rect.topdef prep_level(self):"""将等级转换为渲染的图像"""self.level_image = self.font.render(str(self.settings.level), True, self.text_color)# 将等级放在得分下⽅self.level_rect = self.level_image.get_rect()self.level_rect.right = self.score_rect.rightself.level_rect.top = self.score_rect.bottom + 10def prep_players(self):""" 显⽰还余下多少艘飞船 """self.players = Group()for player_number in range(self.settings.player_limit):player = Player(self.settings, self.screen)# 缩放球⼤⼩并赋值位置player.scale(self.scaleValue)player.rect.x = 10 + player.rect.width * player_number * 0.5player.rect.y = self.score_rect.topself.players.add(player)def show_score(self):"""在屏幕上显⽰得分"""self.screen.blit(self.score_image, self.score_rect)self.screen.blit(self.high_score_image, self.high_score_rect)self.screen.blit(self.level_image, self.level_rect)# 绘制飞船self.players.draw(self.screen)8.新建⽂件“game_functions.py”,存放跟游戏有关的所有业务逻辑函数(代码有详细的注释信息);import sysimport pygamefrom bullet import Bulletfrom enemy import Enemyimport file as f# 事件def check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound):""" 响应按键和⿏标事件 """for event in pygame.event.get():if event.type == pygame.QUIT:save_file(settings)sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound)elif event.type == pygame.KEYUP:check_keyup_events(event, player)elif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y)def check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound):""" 响应按键 """if event.key == pygame.K_DOWN:player.move_down = Trueelif event.key == pygame.K_UP:player.move_up = Trueelif event.key == pygame.K_LEFT:player.move_left = Trueelif event.key == pygame.K_RIGHT:player.move_right = Trueelif event.key == pygame.K_SPACE:fireSound.play()# 点击空格键创建⼀颗⼦弹fire_bullet(settings, screen, player, bullets)elif event.key == pygame.K_p:start_game(settings, scoreboard)elif event.key == pygame.K_q:save_file(settings)sys.exit()def check_keyup_events(event, player):""" 响应松开 """if event.key == pygame.K_DOWN:player.move_down = Falseelif event.key == pygame.K_UP:player.move_up = Falseelif event.key == pygame.K_LEFT:player.move_left = Falseelif event.key == pygame.K_RIGHT:player.move_right = Falsedef check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y):"""在玩家单击Play按钮时开始新游戏"""button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)if button_clicked and not settings.game_active:start_game(settings, scoreboard)def start_game(settings, scoreboard):"""开始游戏"""# 重置游戏设置settings.initialize_settings()# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏统计信息settings.reset_stats()settings.game_active = True# 重置记分牌图像scoreboard.prep_score()scoreboard.prep_high_score()scoreboard.prep_level()scoreboard.prep_players()def save_file(settings):# 保持⽂件obj = {'highScore': settings.high_score}f.save_file(obj, settings.filename)# 敌机def update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound): # ⽣成敌机,需要控制⽣成频率if settings.enemy_frequency % settings.enemy_frequency_space == 0:enemy1 = Enemy(enemy_down_imgs, settings)enemies.add(enemy1)settings.enemy_frequency += 1if settings.enemy_frequency >= 100:settings.enemy_frequency = 0for enemy in enemies:# 移动敌机enemy.move()# 敌机与玩家飞机碰撞效果处理两个精灵之间的圆检测if pygame.sprite.collide_circle(enemy, player):enemies_down.add(enemy)enemies.remove(enemy)settings.player_limit -= 1scoreboard.prep_players()break# 移动出屏幕后删除飞机if enemy.rect.top < 0:enemies.remove(enemy)# 敌机被⼦弹击中效果处理# 将被击中的敌机对象添加到击毁敌机 Group 中,⽤来渲染击毁动画# ⽅法groupcollide()是检测两个精灵组中精灵们的矩形冲突enemies1_down = pygame.sprite.groupcollide(enemies, bullets, True, True)if enemies1_down:explosiveSound.play()# 计算分数并渲染for enemys in enemies1_down.values():settings.score += settings.one_points * len(enemys)scoreboard.prep_score()# 渲染最⾼分check_high_score(settings, scoreboard)# 等达到等级数量升级并渲染新等级settings.level_number -= 1if settings.level_number == 0:settings.increase_speed()settings.level += 1scoreboard.prep_level()# 还原为4(同settings⼀致)settings.level_number = 10# 加快⽣成敌机if settings.enemy_frequency_space > 10:settings.enemy_frequency_space -= 10# 遍历key值返回的碰撞敌机for enemy_down in enemies1_down:# 点击销毁的敌机到列表enemies_down.add(enemy_down)# 敌机被⼦弹击中效果显⽰for enemy_down in enemies_down:if enemy_down.down_index == 0:passif enemy_down.down_index > 7:enemies_down.remove(enemy_down)continue#显⽰碰撞图⽚screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2], enemy_down.rect) enemy_down.down_index += 1# 显⽰精灵enemies.draw(screen)# ⼦弹def fire_bullet(settings, screen, player, bullets):"""创建⼦弹"""new_bullet = Bullet(settings, screen, player)bullets.add(new_bullet)def update_bullets(screen, bullets):"""更新⼦弹的位置,并删除已消失的⼦弹"""# 更新⼦弹的位置bullets.update()# 删除已消失的⼦弹并同时更新飞船的⽣命for bullet in bullets.copy():if bullet.rect.top < screen.get_rect().top:bullets.remove(bullet)# 分数def check_high_score(settings, scoreboard):"""检查是否诞⽣了新的最⾼得分"""if settings.score > settings.high_score:settings.high_score = settings.scorescoreboard.prep_high_score()# 屏幕def update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets): """ 更新屏幕上的图像,并切换到新屏幕 """# 绘制飞船到屏幕player.draw_player()# 绘制⼦弹到屏幕for bullet in bullets.sprites():bullet.draw_bullet()# 渲染记分牌信息scoreboard.show_score()#if settings.player_limit == 0:settings.game_active = Falsesettings.reset_stats()# 清空矩形列表和⼦弹列表enemies.empty()bullets.empty()screen_rect = screen.get_rect()player.rect.centerx = screen_rect.centerxplayer.rect.bottom = screen_rect.bottom# 如果游戏处于⾮活动状态,就绘制 Play 按钮if not settings.game_active:play_button.draw_button()# 让最近绘制的屏幕可见pygame.display.flip()9.新建⽂件shootingenemy.py,主函数⽤来初始化程序,并同步更新程序的信息;import pygamefrom pygame.sprite import Groupfrom settings import Settingsfrom button import Buttonfrom player import Playerimport game_functions as gffrom scoreboard import Scoreboarddef run_game():pygame.init()# 初始化全部⾳频,并加载爆炸声⾳乐pygame.mixer.init()# 等待1spygame.time.delay(1000)pygame.mixer.music.load('file/bgsound.mp3')# -1代表⽆限循环(背景⾳乐)pygame.mixer.music.play(-1)# 爆炸声explosiveSound = pygame.mixer.Sound('file/explosiveSound.wav')# 枪声fireSound = pygame.mixer.Sound('file/fireSound.wav')# 游戏循环帧率设置clock = pygame.time.Clock()settings = Settings()screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))# 全屏显⽰# screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)pygame.display.set_caption('飞机⼤战')# 左上⾓图标ic_launcher = pygame.image.load('images/ic_launcher.png').convert_alpha()pygame.display.set_icon(ic_launcher)# 背景图background = pygame.image.load('images/background.png').convert_alpha()# 敌机图⽚enemy_img1= pygame.image.load('images/enemy1.png')enemy_img2= pygame.image.load('images/enemy2.png')enemy_img3= pygame.image.load('images/enemy3.png')enemy_img4= pygame.image.load('images/enemy4.png')# 敌机不同状态的图⽚列表,多张图⽚展⽰为动画效果enemy_down_imgs = []enemy_down_imgs.append(enemy_img1)enemy_down_imgs.append(enemy_img2)enemy_down_imgs.append(enemy_img3)enemy_down_imgs.append(enemy_img4)# 储存敌机enemies = Group()# 存储被击毁的飞机,⽤来渲染击毁动画enemies_down = Group()# 创建Play按钮play_button = Button(screen, 'Play')# 创建飞船player = Player(settings, screen)# 创建⼦弹的编组bullets = Group()# 创建记分牌scoreboard = Scoreboard(settings, screen)while True:# 绘制背景screen.blit(background, (0, 0))# 控制游戏最⼤频率clock.tick(60)# 检查玩家输⼊(不加会导致⼀直加载)gf.check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound)if settings.game_active:# 更新飞船位置player.update()# 更新敌机gf.update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound)# 更新⼦弹位置gf.update_bullets(screen, bullets)# 更新屏幕信息gf.update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets)run_game(),10.在⽂件shootingenemy.py⽬录路径下,执⾏命令“python shootingenemy.py”弹出窗⼝,即可对其操作游玩。

Python小游戏代码:飞机大战(超详细)

Python小游戏代码:飞机大战(超详细)

Python⼩游戏代码:飞机⼤战(超详细)我⽤的是pycharm,⼤家可以⽤别的Python编辑器。

创建⼀个新的⽂件夹,把图⽚的⽂件夹导⼊,图⽚的链接我放下⾯了,⼤家⾃取。

提取码:Leo1在刚才的⽂件夹⾥新建Python⽂件,输⼊以下代码# coding:utf-8import pygame, sys, random, time, easyguifrom pygame.locals import *# 初始化pygame环境pygame.init()# 创建⼀个长宽分别为480/650窗⼝canvas = pygame.display.set_mode((480, 650))canvas.fill((255, 255, 255))# 设置窗⼝标题pygame.display.set_caption("飞机⼤战")bg = pygame.image.load("images/bg1.png")enemy1 = pygame.image.load("images/enemy1.png")enemy2 = pygame.image.load("images/enemy2.png")enemy3 = pygame.image.load("images/enemy3.png")b = pygame.image.load("images/bullet1.png")h = pygame.image.load("images/hero.png")#开始游戏图⽚startgame=pygame.image.load("images/startGame.png")#logo图⽚logo=pygame.image.load("images/LOGO.png")#暂停图⽚pause = pygame.image.load("images/game_pause_nor.png")# 添加时间间隔的⽅法def isActionTime(lastTime, interval):if lastTime == 0:return TruecurrentTime = time.time()return currentTime - lastTime >= interval# 定义Sky类class Sky():def __init__(self):self.width = 480self.height = 852self.img = bgself.x1 = 0self.y1 = 0self.x2 = 0self.y2 = -self.height# 创建paint⽅法def paint(self):canvas.blit(self.img, (self.x1, self.y1))canvas.blit(self.img, (self.x2, self.y2))# 创建step⽅法def step(self):self.y1 = self.y1 + 1self.y2 = self.y2 + 1if self.y1 > self.height:self.y1 = -self.heightif self.y2 > self.height:self.y2 = -self.height# 定义⽗类FlyingObjectclass FlyingObject(object):def __init__(self, x, y, width, height, life, img):self.x = xself.y = yself.width = widthself.height = heightself.life = lifeself.img = img# 敌飞机移动的时间间隔stTime = 0self.interval = 0.01# 添加删除属性self.canDelete = False# 定义paint⽅法def paint(self):canvas.blit(self.img, (self.x, self.y))# 定义step⽅法def step(self):# 判断是否到了移动的时间间隔if not isActionTime(stTime, self.interval):returnstTime = time.time()# 控制移动速度self.y = self.y + 2# 定义hit⽅法判断两个对象之间是否发⽣碰撞def hit(self, component):c = componentreturn c.x > self.x - c.width and c.x < self.x + self.width and \ c.y > self.y - c.height and c.y < self.y + self.height# 定义bang⽅法处理对象之间碰撞后的处理def bang(self, bangsign):# 敌机和英雄机碰撞之后的处理if bangsign:if hasattr(self, 'score'):GameVar.score += self.scoreif bangsign == 2:self.life -= 1# 设置删除属性为Trueself.canDelete = True# 敌机和⼦弹碰撞之后的处理else:self.life -= 1if self.life == 0:# 设置删除属性为Trueself.canDelete = Trueif hasattr(self, 'score'):GameVar.score += self.score# 定义outOfBounds⽅法判断对象是否越界def outOfBounds(self):return self.y > 650# 重构Enemy类class Enemy(FlyingObject):def __init__(self, x, y, width, height, type, life, score, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.type = typeself.score = score# 重构Hero类class Hero(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.x = 480 / 2 - self.width / 2self.y = 650 - self.height - 30self.shootLastTime = 0self.shootInterval = 0.3def shoot(self):if not isActionTime(self.shootLastTime, self.shootInterval):returnself.shootLastTime = time.time()GameVar.bullets.append(Bullet(self.x + self.width / 2 - 5, self.y - 10, 10, 10, 1, b))# 重构Bullet类class Bullet(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)def step(self):self.y = self.y - 2# 重写outOfBounds⽅法判断⼦弹是否越界def outOfBounds(self):return self.y < -self.height# 创建componentEnter⽅法def componentEnter():# 随机⽣成坐标x = random.randint(0, 480 - 57)x1 = random.randint(0, 480 - 50)x2 = random.randint(0, 480 - 100)# 根据随机整数的值⽣成不同的敌飞机n = random.randint(0, 9)# 判断是否到了产⽣敌飞机的时间if not isActionTime(stTime, GameVar.interval):returnstTime = time.time()if n <= 7:GameVar.enemies.append(Enemy(x, 0, 57, 45, 1, 1, 1, enemy1))elif n == 8:GameVar.enemies.append(Enemy(x1, 0, 50, 68, 2, 3, 5, enemy2))elif n == 9:if len(GameVar.enemies) == 0 or GameVar.enemies[0].type != 3:GameVar.enemies.insert(0, Enemy(x2, 0, 100, 153, 3, 10, 20, enemy3))# 创建画组件⽅法def componentPaint():# 判断是否到了飞⾏物重绘的时间if not isActionTime(GameVar.paintLastTime, GameVar.paintInterval):returnGameVar.paintLastTime = time.time()# 调⽤sky对象的paint⽅法GameVar.sky.paint()for enemy in GameVar.enemies:enemy.paint()# 画出英雄机GameVar.hero.paint()# 画出⼦弹对象for bullet in GameVar.bullets:bullet.paint()# 写出分数和⽣命值renderText('SCORE:' + str(GameVar.score), (0, 0))renderText('LIFE:' + str(GameVar.heroes), (380, 0))# 创建组件移动的⽅法def componentStep():# 调⽤sky对象的step⽅法GameVar.sky.step()for enemy in GameVar.enemies:enemy.step()# 使⼦弹移动for bullet in GameVar.bullets:bullet.step()# 创建删除组件的⽅法def componentDelete():for enemy in GameVar.enemies:if enemy.canDelete or enemy.outOfBounds():GameVar.enemies.remove(enemy)for bullet in GameVar.bullets:if bullet.canDelete or bullet.outOfBounds():GameVar.bullets.remove(bullet)# 从列表中删除英雄机if GameVar.hero.canDelete == True:GameVar.heroes -= 1if GameVar.heroes == 0:#easygui.msgbox('游戏结束')GameVar.state = GameVar.STATES['GAME_OVER']else:GameVar.hero = Hero(0, 0, 60, 75, 1, h)# 定义GameVar类class GameVar():sky = Sky()enemies = []# 产⽣敌飞机的时间间隔lastTime = 0interval = 1.5# 重绘飞⾏物的时间间隔paintLastTime = 0paintInterval = 0.04# 创建英雄机对象hero = Hero(0, 0, 60, 75, 1, h)# 创建列表存储⼦弹对象bullets = []# 添加分数和⽣命值score = 0heroes = 3#创建字典存储游戏状态STATES = {'START':1,'RUNNING':2,'PAUSE':3,'GAME_OVER':4}state = STATES['START']print(GameVar.state)# 定义renderText⽅法def renderText(text, position):my_font = pygame.font.SysFont("微软雅⿊", 40)newText = my_font.render(text, True, (255, 255, 255))canvas.blit(newText, position)# 创建游戏退出事件处理⽅法def handleEvent():for event in pygame.event.get():if event.type == pygame.QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: pygame.quit()sys.exit()#点击⿏标开始游戏if event.type == MOUSEBUTTONDOWN and event.button == 1:if GameVar.state == GameVar.STATES['START']:GameVar.state = GameVar.STATES['RUNNING']# 英雄机跟随⿏标移动if event.type == MOUSEMOTION:if GameVar.state == GameVar.STATES['RUNNING']:GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2 GameVar.hero.y = event.pos[1] - GameVar.hero.height / 2# 调⽤⽅法判断⿏标移⼊画布if isMouseOver(event.pos[0], event.pos[1]):#print('⿏标移⼊事件')if GameVar.state == GameVar.STATES['PAUSE']:GameVar.state = GameVar.STATES['RUNNING']# 调⽤⽅法判断⿏标移出画布if isMouseOut(event.pos[0], event.pos[1]):#print('⿏标移出事件')if GameVar.state == GameVar.STATES['RUNNING']:GameVar.state = GameVar.STATES['PAUSE']# 创建⽅法判断⿏标移出画布def isMouseOut(x, y):if x >= 479 or x <= 0 or y >= 649 or y <= 0:return Trueelse:return False# 创建⽅法判断⿏标移⼊画布def isMouseOver(x, y):if x > 1 and x < 479 and y > 1 and y < 649:return Trueelse:return False# 创建checkHit⽅法def checkHit():# 判断英雄机是否与每⼀架敌飞机发⽣碰撞for enemy in GameVar.enemies:if GameVar.hero.hit(enemy):# 敌机和英雄机调⽤bang⽅法enemy.bang(1)GameVar.hero.bang(2)# 判断每⼀架敌飞机是否与每⼀颗⼦弹发⽣碰撞for bullet in GameVar.bullets:if enemy.hit(bullet):# 敌机和⼦弹调⽤bang⽅法enemy.bang(0)bullet.bang(0)#创建controlState⽅法控制游戏状态def controlState():#游戏开始状态if GameVar.state == GameVar.STATES['START']:GameVar.sky.paint()GameVar.sky.step()canvas.blit(logo,(-40,200))canvas.blit(startgame,(150,400))#游戏运⾏状态elif GameVar.state == GameVar.STATES['RUNNING']:componentEnter()componentPaint()componentStep()checkHit()GameVar.hero.shoot()componentDelete()#游戏暂停状态elif GameVar.state == GameVar.STATES['PAUSE']:componentPaint()componentPaint()GameVar.sky.step()canvas.blit(pause,(0,0))#游戏结束状态elif GameVar.state == GameVar.STATES['GAME_OVER']: componentPaint()GameVar.sky.step()renderText('gameOver',(180,320))while True:#调⽤控制游戏状态的⽅法controlState()# 刷新屏幕pygame.display.update()# 调⽤handleEvent⽅法handleEvent()# 延迟处理pygame.time.delay(15)运⾏程序就可以了!。

飞机大战 java 源代码

飞机大战 java  源代码

package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Plane {Image feijiImage = null;int x = 300;int y = 700;int lifeCount=5;public Plane() {try {feijiImage = ImageIO.read(Plane.class.getClassLoader().getResourceAsStream("images/feiji.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画飞机图片g.drawImage(feijiImage, x, y, null);//飞机移动this.move();// 血条if(lifeCount>0){g.setColor(Color.WHITE);g.fillRect(20, 80, 100, 10);g.setColor(Color.red);g.fillRect(20, 80, (100/5)*lifeCount, 10);g.setColor(Color.blue);g.setFont(new Font("幼圆", Font.BOLD, 30));g.drawString("Score:"+Play01.count, 20, 60);}}public void move(){if(isUP && !isDown && !isLeft && !isRight){//上y=y-5;}else if(!isUP && isDown && !isLeft && !isRight){ //下y=y+5;}else if(!isUP && !isDown && isLeft && !isRight){ //左x=x-5;}else if(!isUP && !isDown && !isLeft && isRight){ //右x=x+5;}else if(isUP && !isDown && isLeft && !isRight){ //左上x=x-5;y=y-5;}else if(!isUP && isDown && isLeft && !isRight){ //左下x=x-5;y=y+5;}else if(isUP && !isDown && !isLeft && isRight){ //右上x=x+5;y=y-5;}else if(!isUP && isDown && !isLeft && isRight){ //右下x=x+5;y=y+5;}}boolean isUP = false;boolean isDown = false;boolean isLeft = false;boolean isRight = false;// 摁下public void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {isRight=true;} else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {isLeft=true;} else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {isUP=true;} else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { isDown=true;}}// 放开public void keyReleased(KeyEvent e) {int keyCode = e.getKeyCode();if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {isRight=false;} else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {isLeft=false;} else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {isUP=false;} else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { isDown=false;}}public Rectangle getRectangle(){return new Rectangle(x,y,feijiImage.getWidth(null),feijiImage.getHeight(null));}}package com;public class PlaneStatus {public static int roleNum = 1;public static int playStatus = 0;// 0 游戏开始前 1 第一关-1 游戏结束}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Power {Image PowerImage = null;int x = 20;int y = 0;public Power() {this.x=(int)(Math.random()*540)+20;try {PowerImage = ImageIO.read(Gift.class.getClassLoader().getResourceAsStream("images/power.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画血瓶图片g.drawImage(PowerImage, x, y, null);//血瓶移动y++;}public Rectangle getRectangle(){return new Rectangle(x,y,PowerImage.getWidth(null),PowerImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;// 第一关public class Play01 {static int count=0;Image bgImage = null;// 战机Plane plane = new Plane();// 战机子弹List<MyZiDan> mzds = new ArrayList<MyZiDan>();// 敌机List<Diji> dijis = new ArrayList<Diji>();// 敌机子弹//List<DijiZiDan> dijizidans = new ArrayList<DijiZiDan>();// 血瓶List<Gift> gifts = new ArrayList<Gift>();List<Power> powers = new ArrayList<Power>();public Play01() {try {bgImage = ImageIO.read(Play01.class.getClassLoader().getResourceAsStream("images/bg_01.jpg"));} catch (IOException e) {e.printStackTrace();}}int bgY1 = 0;int bgY2 = -600;int fireTime = 0;boolean flag=false;public void draw(Graphics g) {// 画背景图片g.drawImage(bgImage, 0, bgY1, null);bgY1 += 5;if (bgY1 <= 600) {bgY1 = 0;}g.drawImage(bgImage, 0, bgY2, null);bgY2 += 5;if (bgY2 >= 0) {bgY2 = -600;}// 清理战机子弹for (int i = 0; i < mzds.size(); i++) {MyZiDan myZidan = mzds.get(i);if (myZidan.x > 800) {mzds.remove(i);}}// 添加子弹if (isFire1 == true && flag==false) {if (fireTime % 8 == 0) {mzds.add(new MyZiDan(plane.x + 25, plane.y + 0));}fireTime++;}if (isFire1== true && flag==true) {if (fireTime % 4 == 0) {mzds.add(new MyZiDan(plane.x +8, plane.y +0));mzds.add(new MyZiDan(plane.x +52, plane.y +0));}fireTime++;}// 画战机子弹for (int i = 0; i < mzds.size(); i++) {MyZiDan myZidan = mzds.get(i);myZidan.draw(g);}// 清理敌机for (int i = 0; i < dijis.size(); i++) {Diji dj = dijis.get(i);if (dj.x < -100) {dijis.remove(i);}}// 抽奖:添加敌机if ((int) (Math.random() * 20) == 5) {dijis.add(new Diji());}// 抽奖:添加血瓶if ((int) (Math.random() * 1000) == 5) {gifts.add(new Gift());}for (int i = 0; i < gifts.size(); i++) {Gift gift = gifts.get(i);gift.draw(g);}//// 抽奖:添加powerif ((int) (Math.random() * 1000) == 5) {powers.add(new Power());}for (int i = 0; i < powers.size(); i++) {Power power = powers.get(i);power.draw(g);}// 画敌机for (int i = 0; i < dijis.size(); i++) {Diji dj = dijis.get(i);dj.draw(g);}// 画飞机plane.draw(g);// 判断战机相撞for (int i = 0; i < dijis.size(); i++) {// 先得到每一个敌机Diji dj = dijis.get(i);Rectangle r1 = dj.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {dijis.remove(i);plane.lifeCount = plane.lifeCount - 1;if(plane.lifeCount>0)flag=false;if(plane.lifeCount<1){ PlaneStatus.playStatus=-1; }}// 判断战机和血瓶相撞for (int i = 0; i < gifts.size(); i++) {// 先得到每一个血瓶Gift gift = gifts.get(i);Rectangle r1 = gift.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {gifts.remove(i);if (plane.lifeCount <5) {plane.lifeCount = plane.lifeCount + 1;}}}//// 判断战机和Power相撞for (int i = 0; i < powers.size(); i++) {// 先得到每一个powerPower power = powers.get(i);Rectangle r1 = power.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {powers.remove(i);flag=true;}}// 判断敌机在中弹for (int i = 0; i < mzds.size(); i++) {// 得到每个战机子弹MyZiDan myzidan = mzds.get(i);Rectangle r1 = myzidan.getRectangle();for (int j = 0; j < dijis.size(); j++) {// 每一个敌机Diji diji = dijis.get(j);Rectangle r2 = diji.getRectangle();if (r1.intersects(r2)) {mzds.remove(i);dijis.remove(j);count++;}}}boolean isFire1 = false;boolean isFire2 = false;public void keyPressed(KeyEvent e) {plane.keyPressed(e);if (e.getKeyCode() == KeyEvent.VK_J) {isFire1 = true;}/*if (e.getKeyCode() == KeyEvent.VK_K) {isFire2 = true;}*/}public void keyReleased(KeyEvent e) {plane.keyReleased(e);if (e.getKeyCode() == KeyEvent.VK_J) {isFire1 = false;fireTime = 0;}/*if (e.getKeyCode() == KeyEvent.VK_K) {isFire2 = false;fireTime = 0;}*/if( e.getKeyCode()==KeyEvent.VK_P){for(int i=0;i<dijis.size();i++)dijis.remove(i);}}}package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;// 游戏结束public class Over {Image obg=null;Image ng=null;public Over() {try {obg = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/obg.jpg"));ng = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/ng.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g){g.drawImage(obg, 0, 0, null);g.drawImage(ng, 120,100, null);g.setColor(Color.black);g.setFont(new Font("幼圆", Font.BOLD, 40));g.drawString("游戏结束啦!",200 ,600 );}public void keyPressed(KeyEvent e) {}public void keyReleased(KeyEvent e) {}}package com;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import javax.swing.JFrame;public class MainFrame extends JFrame {Before before =new Before();Play01 play01 = new Play01();Over over = new Over();public MainFrame() {//设置标题this.setTitle(" 让子弹飞一会~"); //设置大小this.setSize(600, 800);//定位居中this.setLocationRelativeTo(null);//添加关闭操作this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //禁止重置大小zthis.setResizable(false);//添加键盘监听器//KeyListener --> KeyAdapterthis.addKeyListener(new KeyAdapter(){@Overridepublic void keyPressed(KeyEvent e) {if(PlaneStatus.playStatus == 0){before.keyPressed(e);}else if(PlaneStatus.playStatus ==1){play01.keyPressed(e);}else if(PlaneStatus.playStatus==-1){over.keyPressed(e);}}@Overridepublic void keyReleased(KeyEvent e) {if(PlaneStatus.playStatus == 0){before.keyReleased(e);}else if(PlaneStatus.playStatus ==1){play01.keyReleased(e);}else if(PlaneStatus.playStatus==-1){over.keyReleased(e);}}});//启动一个线程:每隔20 毫秒执行一次new Thread(){public void run(){while(true){MainFrame.this.repaint();try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();//显示this.setVisible(true);}Image bufferImage =null;//这个方法也是20毫秒执行一次public void paint(Graphics g){if(bufferImage==null){bufferImage = this.createImage(600, 800);}Graphics g4Image = bufferImage.getGraphics();g4Image.setColor(Color.BLACK);g4Image.fillRect(0, 0, 600, 800);this.draw(g4Image);g.drawImage(bufferImage, 0, 0, null);}public void draw(Graphics g){if(PlaneStatus.playStatus == 0){before.draw(g);}else if(PlaneStatus.playStatus ==1){play01.draw(g);}else if(PlaneStatus.playStatus==-1){over.draw(g);}}public static void main(String[] args) {new MainFrame();}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.io.IOException;import javax.imageio.ImageIO;public class MyZiDan {Image zidanImage = null;int x ;int y ;public MyZiDan(int x,int y) {this.x=x;this.y=y;try {zidanImage = ImageIO.read(MyZiDan.class.getClassLoader().getResourceAsStream("images/zidan.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画我军子弹图片g.drawImage(zidanImage, x, y, null);//我的飞机子弹移动速度y-=20;}public Rectangle getRectangle(){return new Rectangle(x,y,zidanImage.getWidth(null),zidanImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Diji {Image dijiImage = null;int y = -20;int x = 10;//20 ~ 760int r;public Diji() {this.x=(int)(Math.random()*540)+40;try {r = (int)(Math.random()*3)+1;dijiImage = ImageIO.read(Diji.class.getClassLoader().getResourceAsStream("images/diji_"+r+".png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画敌机图片g.drawImage(dijiImage, x, y, null);//敌机移动if(r==1){y+=4;}else if(r==2){y+=4;}else if(r==3){y+=7;}}public Rectangle getRectangle(){return new Rectangle(x,y,dijiImage.getWidth(null),dijiImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Gift {Image GiftImage = null;int x = 20;int y = 0;public Gift() {this.x=(int)(Math.random()*540)+20;try {GiftImage = ImageIO.read(Gift.class.getClassLoader().getResourceAsStream("images/blood.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画血瓶图片g.drawImage(GiftImage, x, y, null);//血瓶移动y++;}public Rectangle getRectangle(){return new Rectangle(x,y,GiftImage.getWidth(null),GiftImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.io.IOException;import javax.imageio.ImageIO;public class DijiZiDan {Image zidanImage = null;int x ;int y ;int fangxiang =0;public DijiZiDan(int x,int y) {this.x=x;this.y=y;fangxiang = (int)(Math.random()*5);//0 ~ 7try {zidanImage = ImageIO.read(DijiZiDan.class.getClassLoader().getResourceAsStream("images/dijizidan.jpg"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画敌机子弹图片g.drawImage(zidanImage, x, y, null);//移动this.move();}public void move(){if(fangxiang==0){//下y=y+2;}else if(fangxiang==1){//左x=x-2;}else if(fangxiang==2){//右x=x+2;}else if(fangxiang==3){//左下x=x-2;y=y+2;}else if(fangxiang==4){//右下x=x+2;y=y+2;}}public Rectangle getRectangle(){return new Rectangle(x,y,zidanImage.getWidth(null),zidanImage.getHeight(null));}}package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;// 游戏开始之前public class Before {Image bg=null;Image wfeiji=null;Image kdiji1=null;Image kdiji2=null;Image kdiji3=null;public Before() {try {bg = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/bg.jpg"));wfeiji = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/feiji_1.png"));kdiji1 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_01.png"));kdiji2 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_02.png"));kdiji3 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_03.png"));} catch (IOException e) {e.printStackTrace();}}int time=0;public void draw(Graphics g){if(PlaneStatus.roleNum==1){// 画妹妹g.drawImage(bg, 0, 0, null);g.drawImage(wfeiji, 260, 600, null);g.drawImage(kdiji1, 200, 50, null);g.drawImage(kdiji1, 400, 50, null);g.drawImage(kdiji1, 150, 480, null);g.drawImage(kdiji1, 400, 480, null);g.drawImage(kdiji2, 100, 200, null);g.drawImage(kdiji2, 300, 100, null);g.drawImage(kdiji2, 480, 200, null);g.drawImage(kdiji3, 300, 300, null);g.drawImage(kdiji3, 70, 400, null);g.drawImage(kdiji3, 510, 400, null);}//画回车符time++;g.setColor(Color.YELLOW);g.setFont(new Font("幼圆", Font.BOLD, 30));if(time<=10){g.drawString("[Enter]>>", 50, 750);}else if(time<=20){g.drawString("[Enter] >>", 50, 750);}else if(time<=30){g.drawString("[Enter] >>", 50, 750);if(time==30){time=0;}}}public void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();if(keyCode == KeyEvent.VK_ENTER){PlaneStatus.playStatus=1;}if(keyCode ==KeyEvent.VK_LEFT ||keyCode==KeyEvent.VK_RIGHT ){ PlaneStatus.roleNum = 3-PlaneStatus.roleNum;//1~2 互换}}public void keyReleased(KeyEvent e) {}}。

飞机大战c++语言源代码,C++编写简易的飞机大战

飞机大战c++语言源代码,C++编写简易的飞机大战

飞机⼤战c++语⾔源代码,C++编写简易的飞机⼤战初学C/C++的⼩伙伴可以⽤做这个⼩游戏来熟悉⼀下编程的乐趣。

#include#include"resource.h"#include#include#include#define TIMER_DIREN 101 //定义定时器#define TIMER_DIRENMOVE 102#define TIMER_ZIDAN 103#define TIMER_DIRENRELEASE 104typedef struct Node //敌⼈,⾃⼰,⼦弹结构体{int x;int y;struct Node *pnext;}DiRen,FeiJi,ZiDan;void ZaoDiRen(); //造敌⼈void ShowDiRen(DiRen *pHead,HWND hWnd); //显⽰敌⼈void ZaoZiDan(); //造⼦弹void ShowZiDan(ZiDan *pHead,HWND hWnd); //显⽰⼦弹void DiRenMove(DiRen *pHead); //敌⼈移动void ZiDanMove(DiRen *pHead); //⼦弹移动void shoot(HWND hWnd,FeiJi *ziji,DiRen **diren,ZiDan **zidan);//判断是否射中void ReleaseDiren(DiRen **pHead); //释放出去的敌⼈void ReleaseZidan(ZiDan **pHead); //释放出去的⼦弹void ZaoZiJi(HWND hWnd); //造⾃⼰LRESULT CALLBACK pp(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);//回调函数int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){WNDCLASSEX wc;HWND hWnd;wc.cbClsExtra=0;wc.cbSize=sizeof(WNDCLASSEX);wc.cbWndExtra=0;wc.hIcon=NULL ;wc.hCursor=NULL ;wc.hIconSm=NULL;wc.lpfnWndProc=pp;wc.lpszClassName="hello";wc.lpszMenuName=NULL;wc.style=CS_HREDRAW|CS_VREDRAW | CS_OWNDC ;wc.hbrBackground=(HBRUSH)5;RegisterClassEx(&wc);hWnd=CreateWindow("hello","world", WS_OVERLAPPEDWINDOW,100,100,600,600,NULL,NULL,hInstance,NULL); ShowWindow(hWnd,nCmdShow);while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg);DispatchMessage(&msg);}return 0;}DiRen *pDiRen=NULL; //敌⼈ZiDan *pZiDan=NULL; //⼦弹FeiJi *pZiJi=NULL; //⾃⼰static int score=0; //分数static char sco[20]; //装分数的字符窜LRESULT CALLBACK pp(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam){int i=1, //位jscore;HDC hdc;HDC memdc;switch(msg){case WM_TIMER: //定时器hdc=GetDC(hWnd); //得到设备句柄hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP4));//载⼊背景位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);BitBlt(hdc,0,0,600,600,memdc,0,0,SRCCOPY);/*itoa(score,sco,10);*/sprintf(sco,"%d",score); //将分数装⼊字符窜jscore=score;while((jscore=jscore/10)>0) //判断分数有⼏位i++;TextOut(hdc,0,0,"分数",4);TextOut(hdc,30,0,sco,i); //显⽰分数DeleteDC(memdc);ReleaseDC(hWnd,hdc); //释放句柄DeleteObject(hbm);ZaoZiJi(hWnd); //造⾃⼰if(TIMER_ZIDAN==wParam) //定时器101{ZiDanMove(pZiDan); //⼦弹移动ReleaseZidan(&pZiDan); //释放出屏幕的⼦弹}else if( TIMER_DIREN==wParam) //定时器102{ZaoDiRen(); //造敌⼈}else if(TIMER_DIRENRELEASE==wParam) //定时器103{ReleaseDiren(&pDiRen); //释放出屏幕的敌⼈DiRenMove(pDiRen); //敌⼈移动ShowZiDan(pZiDan,hWnd); //显⽰⼦弹shoot(hWnd,pZiJi,&pDiRen,&pZiDan); //是否射中break;case WM_CLOSE: //关闭PostQuitMessage(0);break;case WM_KEYDOWN: //判断按键switch(wParam){case VK_LEFT: //左移if(pZiJi->x>0)pZiJi->x-=20;break;case VK_RIGHT: //右移if(pZiJi->x<530)pZiJi->x+=20;break;case VK_UP: //上移if(pZiJi->y>0)pZiJi->y-=20;break;case VK_DOWN: //下移if(pZiJi->y<520)pZiJi->y+=20;break;case VK_SPACE: //空格发射⼦弹ZaoZiDan();break;}break;case WM_CREATE: //创建pZiJi->x=200; //⾃⼰的xpZiJi->y=500; //⾃⼰的ySetTimer(hWnd,TIMER_DIREN,1000,NULL); //设置定时器SetTimer(hWnd,TIMER_DIRENMOVE,200,NULL);SetTimer(hWnd,TIMER_ZIDAN,100,NULL);SetTimer(hWnd,TIMER_DIRENRELEASE,300,NULL);break;}return DefWindowProc(hWnd,msg,wParam,lParam);}void ZaoDiRen() //造⼦弹{DiRen *u;u=(struct Node*)malloc(sizeof(struct Node));u->x=rand()%550; //⼦弹的x随机出现u->y=-10; //出现的纵坐标固定u->pnext=NULL;if(NULL==pDiRen){pDiRen=u;}else{u->pnext=pDiRen; //将新产⽣的链表放在头pDiRen=u;}}void ShowDiRen(struct Node *pHead,HWND hWnd) //显⽰敌⼈{HDC hdc;HDC memdc;HBITMAP hbm;hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP1));//载⼊敌⼈位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);while(pHead!=NULL) //敌⼈链表不为空,显⽰敌机{BitBlt(hdc,pHead->x,pHead->y,40,40,memdc,0,0,SRCCOPY);pHead=pHead->pnext;}DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);}void ZaoZiJi(HWND hWnd){HDC hdc;HDC memdc;HBITMAP hbm;BITMAP bminfo;hdc=GetDC(hWnd);hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP3));//载⼊⾃⼰的位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);BitBlt(hdc,pZiJi->x,pZiJi->y,40,40,memdc,0,0,SRCCOPY); //显⽰⾃⼰DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);}void ZaoZiDan() //造⼦弹{ZiDan *u;u->y=pZiJi->y+10;u->pnext=NULL;if(pZiDan==NULL){pZiDan=u;}else{u->pnext=pZiDan; //将⼦弹放在链表头pZiDan=u;}}void ShowZiDan(ZiDan *pHead,HWND hWnd) //显⽰⼦弹{HDC hdc;HDC memdc;HBITMAP hbm;BITMAP bminfo;hdc=GetDC(hWnd);hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP2)); //插⼊⼦弹位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);while(pHead!=NULL) //⼦弹链表不为空,显⽰⼦弹{/*Ellipse(hdc,pHead->x,pHead->y,pHead->x+5,pHead->y+5);*/BitBlt(hdc,pHead->x,pHead->y,10,10,memdc,0,0,SRCCOPY);pHead=pHead->pnext;}DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);{while(pHead!=NULL) //链表不为空,敌⼈移动{if(score<500){pHead->y+=10;pHead=pHead->pnext;}else{pHead->y+=20;pHead=pHead->pnext;}}}void ZiDanMove(DiRen *pHead) //⼦弹移动{while(pHead!=NULL) //链表不为空⼦弹移动{pHead->y-=20;pHead=pHead->pnext;}}void shoot(HWND hWnd,FeiJi *ziji,DiRen **diren,ZiDan **zidan) //判断是否中{DiRen *js1=*diren;ZiDan *js2=*zidan;int n = 1;while(js1!=NULL) //判断⾃⼰是否撞机{//撞击释放定时器游戏结束if((ziji->x-js1->x<30&&ziji->x-js1->x>-38)&&(ziji->y-js1->y<25&&ziji->y-js1->y>-38))KillTimer(hWnd,TIMER_ZIDAN);KillTimer(hWnd,TIMER_DIRENMOVE);KillTimer(hWnd,TIMER_DIRENRELEASE);MessageBox(hWnd,"You Lose","窗⼝",MB_OK);PostQuitMessage(0);break;}elsejs1=js1->pnext; //没有判断下⼀个敌机}js1=*diren; //敌机回到头while((js1=*diren)!=NULL) //判断敌⼈是否为空{zidan = &pZiDan;n = 0;while((js2=*zidan)!=NULL) //判断⼦弹是否为空{//敌机中弹if((js2->x - js1->x <= 40&&js2->x - js1->x>=-5)&&(js2->y - js1->y <= 40&&js2->y - js1->y>=-8)) {score+=100;n = 1;*zidan = js2->pnext;if(js1->pnext!=NULL) //链表下节不为空,指向下⼀个释放中弹的飞机⼦弹{*diren = js1->pnext;diren = &pDiRen;free(js1);free(js2);}else*diren = NULL;else{zidan = &js2->pnext; //没中看下⼀个}}if(n != 1) //判断是否是中弹出来的{diren = &js1->pnext;}}}void ReleaseDiren(DiRen **pHead) //释放飞出屏幕的敌⼈{DiRen *js=*pHead;while((js=*pHead)!=NULL){if(js->y>600) //飞出屏幕释放{*pHead=js->pnext;free(js);}else{pHead = &js->pnext; //看下⼀个}}}void ReleaseZidan(ZiDan **pHead) //释放⼦弹{ZiDan *js=*pHead;while((js=*pHead)!=NULL){*pHead=js->pnext;free(js);}elsepHead=&js->pnext; //没飞出看下⼀个}}同时分享⼀个⽹友的⽅法//mytestView.cpp:Cmytest;//;#include"stdafx.h;#include"mytest.h;#include"mytestDoc;#include"mytestView;#ifdef_DEBUG;#definenewDEBUG_NEW;#endif;//CmytestVie// mytestView.cpp : CmytestView 类的实现//#include "stdafx.h"#include "mytest.h"#include "mytestDoc.h"#include "mytestView.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// CmytestViewIMPLEMENT_DYNCREATE(CmytestView, CView) BEGIN_MESSAGE_MAP(CmytestView, CView) ON_WM_CREATE()ON_WM_TIMER()ON_WM_KEYDOWN()END_MESSAGE_MAP()CmytestView::CmytestView(){// TODO: 在此处添加构造代码m_x_me=0;m_x_enemy=0;m_y_enemyone=0;m_y_enemytwo=0;m_y_bomb=0;m_x_bomb=0;m_x_ball=0;m_y_ball=0;m_x_explsion=0;}CmytestView::~CmytestView(){}BOOL CmytestView::PreCreateWindow(CREATESTRUCT& cs) {// TODO: 在此处通过修改// CREATESTRUCT cs 来修改窗⼝类或样式return CView::PreCreateWindow(cs);}// CmytestView 绘制void CmytestView::OnDraw(CDC* pDC){CmytestDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);if (!pDoc)return;// TODO: 在此处为本机数据添加绘制代码/*CBitmap bitmap;bitmap.LoadBitmapW(IDB_ME);*//*pDC->BitBlt(100,50,50,60,&MemDC,0,0,SRCCOPY);*/ /*POINT pt;pt.x=200;pt.y=200;CImageList imageList;imageList.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList.Add(&bitmap,RGB(0,0,0));imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap);*///RECT rc;//GetClientRect(&rc);//CBrush brush;//brush.CreateSolidBrush(RGB(3,108,254));//pDC->SelectObject(&brush);//CBrush *oldbrush=pDC->SelectObject(&brush);//pDC->Rectangle(&rc);//pDC->SelectObject(oldbrush);//CBitmap bitmap;//bitmap.LoadBitmapW(IDB_ME);//POINT pt;//pt.x=200;//pt.y=200;//CImageList imageList;//imageList.Create(60,50,ILC_COLOR24|ILC_MASK,1,0); //imageList.Add(&bitmap,RGB(0,0,0));//imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);// CDC MemDC;//MemDC.CreateCompatibleDC(NULL);//MemDC.SelectObject(&bitmap);//刷新RECT rc;CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//敌机CBitmap bitmap1;bitmap1.LoadBitmapW(IDB_enemy);POINT pt1;pt1.x=200;pt1.y=m_y_enemyone;POINT pt1_2;pt1_2.x=300;pt1_2.y=m_y_enemytwo;CImageList imageList1;imageList1.Create(35,35,ILC_COLOR24|ILC_MASK,1,0); imageList1.Add(&bitmap1,RGB(0,0,0));imageList1.Draw(pDC,0,pt1,ILD_TRANSPARENT); imageList1.Draw(pDC,1,pt1_2,ILD_TRANSPARENT);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;CImageList imageList2;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//⼦弹CBitmap bitmap3;bitmap3.LoadBitmapW(IDB_ball);pt3.y=m_y_ball;CImageList imageList3;imageList3.Create(8,8,ILC_COLOR24|ILC_MASK,1,0); imageList3.Add(&bitmap3,RGB(0,0,0));imageList3.Draw(pDC,0,pt3,ILD_TRANSPARENT);//炸弹CBitmap bitmap4;bitmap4.LoadBitmapW(IDB_bomb);POINT pt4;pt4.x=m_x_bomb;pt4.y=250;CImageList imageList4;imageList4.Create(10,20,ILC_COLOR24|ILC_MASK,1,0); imageList4.Add(&bitmap4,RGB(0,0,0));imageList4.Draw(pDC,0,pt4,ILD_TRANSPARENT);//爆炸CBitmap bitmap5;bitmap5.LoadBitmapW(IDB_explsion);POINT pt5_1;pt5_1.x=310;pt5_1.y=310;POINT pt5_2;pt5_2.x=330;pt5_2.y=330;POINT pt5_3;pt5_3.x=350;pt5_3.y=450;POINT pt5_4;pt5_4.x=470;pt5_4.y=470;POINT pt5_5;pt5_5.x=510;pt5_6.x=530;pt5_6.y=530;POINT pt5_7;pt5_7.x=540;pt5_7.y=540;POINT pt5_8;pt5_8.x=450;pt5_8.y=250;CImageList imageList5;imageList5.Create(66,66,ILC_COLOR24|ILC_MASK,1,0); imageList5.Add(&bitmap5,RGB(0,0,0));imageList5.Draw(pDC,0,pt5_1,ILD_TRANSPARENT); imageList5.Draw(pDC,1,pt5_2,ILD_TRANSPARENT); imageList5.Draw(pDC,2,pt5_3,ILD_TRANSPARENT); imageList5.Draw(pDC,3,pt5_4,ILD_TRANSPARENT); imageList5.Draw(pDC,4,pt5_5,ILD_TRANSPARENT); imageList5.Draw(pDC,5,pt5_6,ILD_TRANSPARENT); imageList5.Draw(pDC,6,pt5_7,ILD_TRANSPARENT); imageList5.Draw(pDC,7,pt5_8,ILD_TRANSPARENT);/*CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap2);*/}// CmytestView 诊断#ifdef _DEBUGvoid CmytestView::AssertValid() const{CView::AssertValid();}void CmytestView::Dump(CDumpContext& dc) const{CView::Dump(dc);CmytestDoc* CmytestView::GetDocument() const // ⾮调试版本是内联的 {ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CmytestDoc))); return (CmytestDoc*)m_pDocument; }#endif //_DEBUG// CmytestView 消息处理程序int CmytestView::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1)return -1;// TODO: 在此添加您专⽤的创建代码SetTimer(1,30,NULL);return 0;}void CmytestView::OnTimer(UINT_PTR nIDEvent){// TODO: 在此添加消息处理程序代码和/或调⽤默认值CView::OnTimer(nIDEvent);CDC *pDC=GetDC();//刷新背景RECT rc;GetClientRect(&rc);CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//⼦弹欢迎试玩⼀下游戏 ⽅向键:w,a,s,d 控制键:J,K。

Python基础知识飞机大战——飞机大战游戏框架

Python基础知识飞机大战——飞机大战游戏框架

Python基础知识飞机大战——飞机大战游戏框架您所在的位置:首页 > IT干货资料 > python > 【Python基础知识】飞机大战——飞机大战游戏框架【Python基础知识】飞机大战——飞机大战游戏框架来源:优就业2022-09-28 09:57:45 阅读() 分享手机端入口1、游戏窗口经过安装Pygame,以及了解Pygame的核心功能之后,可以开始编写一个小的游戏案例了。

下面将制作一个飞机大战游戏,游戏内容是敌对的两架飞机互相射击。

游戏开始前需要调用初始化函数,代码如下:pygame.init()否则,在本案例中输出汉字时,会提示错误,字体没有初始化。

创建一个游戏窗口,加载背景,设置窗口标题和图标等,代码如下:# 创建一个游戏窗口surface = ode((480, 652)) # 加载背景图片background = pygame.image.load('./img/background.png') # 调整连续按键事件生成时间pygame.key.set_repeat(50, 50) # 设置窗口标题pygame.display.set_caption('飞机大战') # 设置窗口图标pygame.display.set_icon(pygame.image.load('./img/icon72某72.png'))2、游戏循环飞机大战中设计了游戏循环,还设计了玩家飞机、敌机、玩家子弹和敌人子弹四个类,以及碰撞和控制两个功能函数。

另外,还有游戏启动界面和结束界面等函数。

整个游戏的游戏循环如下:①绘制背景图片。

②控制玩家飞机,主要响应玩家的操作。

例如,玩家点击关闭按钮,则退出游戏;玩家按下左箭头键,则飞机向左移动;玩家按下右箭头键,则飞机向右移动;玩家按下空格键,则飞机发射子弹。

③绘制玩家飞机,包括正常状态和被击毁状态;绘制玩家飞机发射的子弹。

c语言飞机大战代码

c语言飞机大战代码

c语言飞机大战代码#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#define LEFT 75 //宏定义方向键#define RIGHT 77#define UP 72#define DOWN 80int main(){char a; //声明变量aint x=10,y=10; //声明变量x,y分别表示飞机的横纵坐标 int stp; //声明变量stpint direct; //声明变量directint i,j; //声明变量i,j循环int score; //声明变量scorechar key; //声明变量keyscore = 0; //初始分数设为0srand((unsigned)time(NULL)); //设置随机数system("cls"); //清屏while(1){key=_getch(); //读取按键if(key=='w') //若键盘输入的是w{direct=UP;key=' ';}if(key=='s') //若键盘输入的是s{direct=DOWN;key=' ';}if(key=='a') //若键盘输入的是a{direct=LEFT;key=' ';}if(key=='d') //若键盘输入的是d{direct=RIGHT;key=' ';}if(direct==UP) //若direction的值为UPy=y-1; //将y的值减1if(direct==DOWN) //若direction的值为DOWN y=y+1; //将y的值加1if(direct==LEFT) //若direction的值为LEFT x=x-1; //将x的值减1if(direct==RIGHT) //若direction的值为RIGHTx=x+1; //将x的值加1system("cls"); //清屏for(i=0;i<20;i++) //循环20次{for(j=0;j<40;j++) //循环40次{if(i==x && j==y) //如果i等于x并且j等于y printf("A"); //输出Aelseprintf("-"); //输出-}printf("\n"); //换行}Sleep(50); //休眠50毫秒if(x==0||x==20||y==0||y==20)break; //若x或y的值为0,20则结束程序stp=rand()%8; //随机一个stp的值if(stp==0){score++; //每随机出0时分数加1printf("分数:%d\n",score); //显示分数}}printf("你的最终得分是:%d\n",score); //显示最终得分return 0;}上面是C语言飞机大战的代码,代码的功能是控制一架飞机位置并且记分,玩家通过按键来控制飞机的位置,飞机撞到边界则游戏结束。

C语言代码实现飞机大战

C语言代码实现飞机大战

C语⾔代码实现飞机⼤战本⽂实例为⼤家分享了C语⾔实现简单飞机⼤战的具体代码,供⼤家参考,具体内容如下这个游戏的功能很单⼀,也就是“飞机⼤战”,哈哈哈哈。

总共只有300多⾏代码左右,你也可以想想它会有多简陋,把它复制下来编译⼀下可以直接执⾏,需要的同学可以⾃取~PS:我运⾏的环境是 dev c++,前提你要在C99的环境中执⾏以下是源代码#include<stdio.h>#include<stdio.h>#include<windows.h> //将⽤户从键盘获得的输⼊进⾏输出#include<conio.h> //获得⽤户键盘的输⼊//定义全局变量int high,width; //定义边界int position_x,position_y; //飞机位置int bullet_x,bullet_y; //⼦弹位置int enemy_x,enemy_y; //敌军飞机int score; //获得分数int flag; //飞机状态void gotoxy(int x,int y); //光标移动到(x,y)位置void welcometogame(); //初始化界⾯int color(int c); //更改⽂字颜⾊void explation(); //游戏右侧显⽰void scoreandtips(); //显⽰游戏提⽰void show(); //显⽰游戏界⾯void endgame(); //游戏结束/*** ⽂字颜⾊函数*/int color(int c){SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c); //更改⽂字颜⾊return 0;}/*** 设置光标位置*/void gotoxy(int x,int y){COORD c;c.X=x;c.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);}void welcometogame() //开始界⾯{int n;color(15);gotoxy(43,10);printf("飞机⼤战");color(11);gotoxy(25, 22);printf("1.开始游戏");gotoxy(45, 22);printf("2.游戏说明");gotoxy(65, 22);printf("3.退出游戏");gotoxy(40,27);color(3);printf("请选择 1 2 3:");color(14);scanf("%d", &n); //输⼊选项switch (n){case 1:break;case 2:explation(); //游戏说明函数break;case 3:exit(0); //退出游戏break;default:color(12);gotoxy(40,28);printf("请输⼊1-3之间的数!");_getch(); //输⼊任意键system("cls"); //清屏welcometogame();}}void explation() //游戏提⽰{int i,j = 1;system("cls");color(10);gotoxy(44,1);printf("游戏说明");color(2);for (i = 3; i <= 28; i++) //输出上下边框==={for (j = 6; j <= 80; j++) //输出左右边框||{gotoxy(j, i);if (i == 3 || i == 28) printf("=");else if (j == 6 || j == 80) printf("||");}}color(3);gotoxy(20,5);printf("1. W,A,S,D 分别控制飞机的上下左右移动");color(10);gotoxy(20,8);printf("2. 按空格发射⼦弹,打中敌机即可得到⼀分");color(14);gotoxy(20,11);printf("3.碰到敌机⼦弹死亡");color(11);gotoxy(20,14);printf("4. ESC :退出游戏");color(4);gotoxy(20,17);printf("5. 玩的愉快");color(7);gotoxy(20,20);printf("/*****按任意键返回主页⾯*****/");_getch(); //按任意键返回主界⾯system("cls");welcometogame();}void scoreandtips()//游戏侧边提⽰{gotoxy(50,8);color(14);printf("游戏得分:%d ",score);gotoxy(50,10);printf("⽤W A S D 分别控制飞机的移动");gotoxy(50,12);printf("按下空格键即为发射炮弹");gotoxy(50,14);printf("@ 的样⼦就是敌⼈的飞机");}void HideCursor() // ⽤于隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第⼆个值为0表⽰隐藏光标}void startup() //数据初始化{high=20; //定义游戏界⾯的⾼度width=40; //游戏界⾯的宽度position_x=high-3; //定义飞机的初始位置position_y=width/2;bullet_x=0;bullet_y=position_y;enemy_x=0;enemy_y=position_y;score=0;flag=0; //飞机完好HideCursor();}void show() //显⽰界⾯{int i,j,k;for(i=0;i<high;i++){for(j=0;j<width;j++){if(flag)break;else if((i==position_x)&&(j==position_y)) //飞机坐标{printf("^");}else if((i==enemy_x)&&(j==enemy_y)) //敌机坐标printf("@");else if((i==bullet_x)&&(j==bullet_y)) //⼦弹坐标printf("|");else if ((j==width-1)||(i==high-1)||(j==0)||(i==0)) //打印边界 printf("-");elseprintf(" ");}printf("\n");}printf("\n");if((position_x==enemy_x)&&(position_y==enemy_y)){flag=1; //飞机撞毁游戏结束system("cls");printf("游戏结束\n");}else{printf("分数 %d",score);}/** _getch(); //按任意键返回主界⾯system("cls");welcometogame();*/}void endgame(){int k,f;system("cls");printf("输⼊1再玩⼀次,输⼊2返回主菜单,输⼊3退出游戏"); scanf("%d",&k);case 1:printf("重新玩游戏");system("cls");startup(); // 数据初始化show();break;case 2:printf("返回主菜单");system("cls");welcometogame();startup();break;case 3:printf("退出成功");exit(0);break;default:color(12);gotoxy(40,28);system("cls");printf("输⼊错误,输⼊任意键回到主菜单");_getch(); //输⼊任意键welcometogame();startup();system("cls"); //清屏}}void withoutInpute() //与⽤户输⼊⽆关{if(bullet_x>0) //⼦弹上升效果bullet_x--;if((bullet_x==enemy_x)&&(bullet_y==enemy_y)) //⼦弹命中敌机 {score++;bullet_x=-1;enemy_x=1;enemy_y=2+rand()%width-2;}static int speed;if(speed<30) //减慢敌机速度,不影响飞机和⼦弹速度speed++;if(speed==30){if(enemy_x<high)enemy_x++;else{enemy_x=0;enemy_y=2+rand()%width-2;}speed=0;}}void withInpute() //与⽤户输⼊有关{char input;if(kbhit()) //控制飞机⽅向{input=getch();if((input=='w')&&position_x>1)position_x--;if((input=='s')&&position_x<high-2)position_x++;if((input=='a')&&position_y>1)position_y--;if((input=='d')&&position_y<width-2)bullet_x=position_x-1;bullet_y=position_y;}}}int main(){system("mode con cols=100 lines=30"); //设置控制台的宽⾼welcometogame();startup(); // 数据初始化//explation();while(1) // 游戏循环执⾏{gotoxy(0,0);show(); // 显⽰画⾯scoreandtips();if(flag == 1){endgame();}withoutInpute(); // 与⽤户输⼊⽆关的更新withInpute(); // 与⽤户输⼊有关的更新}return 0;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

飞机大战 java 源代码,DOC

飞机大战 java  源代码,DOC

packagecom;importimportimportfeijiImage=.getResourceAsStream("images/feiji.png"));}catch(IOExceptione){e.printStackTrace();}}publicvoiddraw(Graphicsg){// 画飞机图片g.drawImage(feijiImage,x,y,null);// 飞机移动publicvoidmove(){if(isUP&&!isDown&&!isLeft&&!isRight){// 上y=y-5;}elseif(!isUP&&isDown&&!isLeft&&!isRight){// 下y=y+5;}elseif(!isUP&&!isDown&&isLeft&&!isRight){ // 左x=x-5;// 右上x=x+5;y=y-5;}elseif(!isUP&&isDown&&!isLeft&&isRight){ // 右下x=x+5;y=y+5;}}booleanisUP=false;nt.VK_A){isLeft=true;}elseif(keyCode==KeyEvent.VK_UP||keyCode==KeyEvent .VK_W){isUP=true;}elseif(keyCode==KeyEvent.VK_DOWN||keyCode==KeyE vent.VK_S){isDown=true;isLeft=false;}elseif(keyCode==KeyEvent.VK_UP||keyCode==KeyEvent .VK_W){isUP=false;}elseif(keyCode==KeyEvent.VK_DOWN||keyCode==KeyE vent.VK_S){isDown=false;}}packagecom;importimportimportimportimportimportpublicclassPower{ImagePowerImage=null;publicvoiddraw(Graphicsg){// 画血瓶图片g.drawImage(PowerImage,x,y,null); // 血瓶移动y++;}publicRectanglegetRectangle(){returnnewRectangle(x,y,PowerImage.getWidth(null),Pow erImage.getHeight(null));publicclassPlay01{staticintcount=0;ImagebgImage=null;//战机Planeplane=newPlane();//战机子弹List<MyZiDan>mzds=newArrayList<MyZiDan>(); //敌机List<Diji>dijis=newArrayList<Diji>();//敌机子弹intbgY1=0;intbgY2=-600;intfireTime=0;booleanflag=false;publicvoiddraw(Graphicsg){//画背景图片g.drawImage(bgImage,0,bgY1,null);bgY1+=5;if(bgY1<=600){bgY1=0;}//添加子弹if(isFire1==true&&flag==false){if(fireTime%8==0){mzds.add(newMyZiDan(plane.x+25,plane.y+0));}fireTime++;}if(isFire1==true&&flag==true){ if(fireTime%4==0){Dijidj=dijis.get(i);if(dj.x<-100){dijis.remove(i);}}//抽奖:添加敌机if((int)(Math.random()*20)==5){ dijis.add(newDiji());}//抽奖:添加血瓶for(inti=0;i<powers.size();i++){Powerpower=powers.get(i);power.draw(g);}//画敌机for(inti=0;i<dijis.size();i++){Dijidj=dijis.get(i);dj.draw(g);}//画飞机if(plane.lifeCount<1){PlaneStatus.playStatus=-1;} }}//判断战机和血瓶相撞for(inti=0;i<gifts.size();i++){//先得到每一个血瓶Giftgift=gifts.get(i);Rectangler1=gift.getRectangle();Rectangler2=plane.getRectangle();if(r1.intersects(r2)){if(r1.intersects(r2)){powers.remove(i);flag=true;}}//判断敌机在中弹for(inti=0;i<mzds.size();i++){//得到每个战机子弹MyZiDanmyzidan=mzds.get(i);Rectangler1=myzidan.getRectangle();booleanisFire1=false;booleanisFire2=false; publicvoidkeyPressed(KeyEvente){plane.keyPressed(e);if(e.getKeyCode()==KeyEvent.VK_J){isFire1=true;}/*if(e.getKeyCode()==KeyEvent.VK_K){ isFire2=true;}*/for(inti=0;i<dijis.size();i++)dijis.remove(i);}}}packagecom;importimportimportimporte.printStackTrace();}}publicvoiddraw(Graphicsg){g.drawImage(obg,0,0,null);g.drawImage(ng,120,100,null);g.setColor(Color.black);g.setFont(newFont("幼圆",Font.BOLD,40));g.drawString("游戏结束啦!",200,600);}publicclassMainFrameextendsJFrame{Beforebefore=newBefore();Play01play01=newPlay01();Overover=newOver();publicMainFrame(){// 设置标题this.setTitle("让子弹飞一会~");// 设置大小this.setSize(600,800);// 定位居中before.keyPressed(e);}elseif(PlaneStatus.playStatus==1){play01.keyPressed(e);}elseif(PlaneStatus.playStatus==-1){over.keyPressed(e);}}@Override publicvoidkeyReleased(KeyEvente){ if(PlaneStatus.playStatus==0){try{Thread.sleep(20);}catch(InterruptedExceptione){e.printStackTrace();}}}}.start();// 显示g.drawImage(bufferImage,0,0,null);}publicvoiddraw(Graphicsg){if(PlaneStatus.playStatus==0){before.draw(g);}elseif(PlaneStatus.playStatus==1){ play01.draw(g);}elseif(PlaneStatus.playStatus==-1){ over.draw(g);}ImagezidanImage=null;intx;inty;publicMyZiDan(intx,inty){this.x=x;this.y=y;try{zidanImage=.getResourceAsStream("images/zidan.png"));}catch(IOExceptione){mage.getHeight(null));}}packagecom;importimportimportimportimportimport}catch(IOExceptione){e.printStackTrace();}}publicvoiddraw(Graphicsg){// 画敌机图片g.drawImage(dijiImage,x,y,null); // 敌机移动if(r==1){y+=4;packagecom;importimportimportimportimportimportpublicclassGift{ImageGiftImage=null;intx=20;g.drawImage(GiftImage,x,y,null); // 血瓶移动y++;}publicRectanglegetRectangle(){returnnewRectangle(x,y,GiftImage.getWidth(null),GiftIma ge.getHeight(null));}}this.x=x;this.y=y;fangxiang=(int)(Math.random()*5);//0~7try{zidanImage=.getResourceAsStream("images/dijizidan.jpg"));}catch(IOExceptione){e.printStackTrace();}// 左x=x-2;}elseif(fangxiang==2){// 右x=x+2;}elseif(fangxiang==3){ // 左下x=x-2;y=y+2;}elseif(fangxiang==4){importimportimportimportimportimportimport//游戏开始之前publicclassBefore{Imagebg=null;e.printStackTrace();}}inttime=0;publicvoiddraw(Graphicsg){if(PlaneStatus.roleNum==1){//画妹妹g.drawImage(bg,0,0,null);g.drawImage(wfeiji,260,600,null);g.drawImage(kdiji1,200,50,null);g.setColor(Color.YELLOW);g.setFont(newFont("幼圆",Font.BOLD,30)); if(time<=10){g.drawString("[Enter]>>",50,750);}elseif(time<=20){g.drawString("[Enter]>>",50,750);}elseif(time<=30){g.drawString("[Enter]>>",50,750);if(time==30){time=0;互换}}publicvoidkeyReleased(KeyEvente){}}。

飞机大战(完整代码)

飞机大战(完整代码)

飞机大战(完整代码)package com.cetc.shoot;/** 敌机: 是飞行物,也是敌人 */public class Airplane extends FlyingObject implements Enemy {private int speed = 2; //走步的步数/** 构造方法 */public Airplane(){image = ShootGame.airplane; //图片width = image.getWidth(); //宽height = image.getHeight(); //高x = (int) (Math.random()*(ShootGame.WIDTH-this.width));// x=100;// y=100;}/** 重写getScore() */public int getScore(){return 5;}/** 重写step() */public void step(){y+=speed; //y加(向下)}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y>=ShootGame.HEIGHT; //敌机的y>=屏幕的高,即为越界}}Award类的完整代码如下所示:package com.cetc.shoot;public interface Award {public int DOUBLE_FIRE = 0; //火力public int LIFE = 1; //命/** 获取奖励类型 0为火力 1为命 */public int getType();}Bee类的完整代码如下所示:package com.cetc.shoot;import java.util.Random;/** 小蜜蜂: 是飞行物,也是奖励 */public class Bee extends FlyingObject implements Award {private int xSpeed = 1; //x坐标走步步数private int ySpeed = 2; //y坐标走步步数private int awardType; //奖励类型/** 构造方法 */public Bee(){image = ShootGame.bee; //图片width = image.getWidth(); //宽height = image.getHeight(); //高y = -height; //y:负的蜜蜂的高Random rand = new Random(); //创建随机数对象x = rand.nextInt(ShootGame.WIDTH-this.width); //x:0到(屏幕宽-蜜蜂宽)之内的随机数 awardType = rand.nextInt(2); //奖励类型为0到1之间的随机数// x=100;// y=200;}/** 重写getType() */public int getType(){return awardType;}/** 重写step() */public void step(){x+=xSpeed; //x加(向左或向右)y+=ySpeed; //y加(向下)if(x>=ShootGame.WIDTH-this.width){ //x>=(屏幕宽-蜜蜂宽)时,x减(向左)xSpeed = -1;}if(x<=0){ //x<=0时,x加(向右)xSpeed = 1;}}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y>=ShootGame.HEIGHT; //蜜蜂的y>=屏幕的高,即为越界 }}Bullet类的完整代码如下所示:package com.cetc.shoot;/** 子弹: 是飞行物 */public class Bullet extends FlyingObject {private int speed = 3; //走步步数/** 构造方法 x:子弹的x坐标 y:子弹的y坐标*/public Bullet(int x,int y){image = ShootGame.bullet; //图片this.x = x; //x坐标:与英雄机有关this.y = y; //y坐标:与英雄机有关}/** 重写step() */public void step(){y-=speed; //y减(向上)}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y<=-this.height; //子弹的y<=负的子弹的高,即为越界 }}Enemy类的完整代码如下所示:package com.cetc.shoot;/*** 敌人 ,可以有分数**/public interface Enemy {/*** 敌人的分数*/public int getScore();}FlyingObject类的完整代码如下所示:package com.cetc.shoot;import java.awt.image.BufferedImage;public abstract class FlyingObject {protected int x; //x坐标protected int y; //y坐标protected int width; //宽protected int height; //高protected BufferedImage image; //图片public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;public void setHeight(int height) {this.height = height;}public BufferedImage getImage() {return image;}public void setImage(BufferedImage image) {this.image = image;}/** 飞行物走一步 */public abstract void step();/*** 检查当前飞行物体是否被子弹(x,y)击(shoot)中,* @param bullet 子弹对象* @return true表示击中*/public boolean shootBy(Bullet bullet) {int x = bullet.x;int y = bullet.y;return this.x<x && x<this.x+width&&this.y<y && y<this.y+height;}/** 检查飞行物是否出界 */public abstract boolean outOfBounds();}Hero类的完整代码如下所示:```csharppackage com.cetc.shoot;import java.awt.image.BufferedImage;/** 英雄机: 是飞行物 */public class Hero extends FlyingObject {private int life; //命private int doubleFire; //火力值private BufferedImage[] images = {}; //图片切换数组private int index = 0; //协助图片切换/** 构造方法 */public Hero(){image = ShootGame.hero0; //图片width = image.getWidth(); //宽height = image.getHeight(); //高x = 150; //x坐标:固定的值y = 400; //y坐标:固定的值life = 3; //命数为3doubleFire = 0; //火力值为0(单倍火力)images = new BufferedImage[]{ShootGame.hero0,ShootGame.hero1}; //两张图片切换}/** 重写step() */public void step() {if(images.length>0) {image = images[index++/10%images.length];}}/** 英雄机发射子弹 */public Bullet[] shoot(){int xStep = this.width/4; //1/4英雄机的宽int yStep = 20; //固定的值if(doubleFire>0){ //双倍Bullet[] bs = new Bullet[2]; //两发子弹bs[0] = new Bullet(this.x+1*xStep,this.y-yStep); //x:英雄机的x+1/4英雄机的宽 y:英雄机的y-20 bs[1] = new Bullet(this.x+3*xStep,this.y-yStep); //x:英雄机的x+3/4英雄机的宽 y:英雄机的y-20 doubleFire-=2; //发射一次双倍火力时,火力值减2return bs;}else{ //单倍Bullet[] bs = new Bullet[1]; //一发子弹bs[0] = new Bullet(this.x+2*xStep,this.y-yStep); //x:英雄机的x+2/4英雄机的宽 y:英雄机的y-20 return bs;}}/** 英雄机随着鼠标移动 x:鼠标的x坐标 y:鼠标的y坐标*/public void moveTo(int x,int y){this.x = x - this.width/2; //英雄机的x:鼠标的x-1/2英雄机的宽this.y = y - this.height/2; //英雄机的y:鼠标的y-1/2英雄机的高/** 英雄机增火力 */public void addDoubleFire(){doubleFire+=40; //火力值增40}/** 增命 */public void addLife(){life++; //命数增1}/** 获取命 */public int getLife(){return life; //返回命数}/** 减命 */public void subtractLife(){life--;}public void setDoubleFire(int doubleFire) {this.doubleFire = doubleFire;}/** 重写outOfBounds() */public boolean outOfBounds(){return false; //永不越界}/** 检测英雄机与敌人的碰撞 this:英雄机 other:敌人 */public boolean hit(FlyingObject other){int x1 = other.x-this.width/2; //x1:敌人的x-1/2英雄机的宽int x2 = other.x+other.width+this.width/2; //x2:敌人的x+敌人的宽+1/2英雄机的宽 int y1 = other.y-this.height/2; //y1:敌人的y-1/2英雄机的高int y2 = other.y+other.height+this.height/2; //y2:敌人的y+敌人的高+1/2英雄机的高 int x = this.x+this.width/2; //x:英雄机的x+1/2英雄机的宽int y = this.y+this.height/2; //y:英雄机的y+1/2英雄机的高return x>x1 && x<x2&&y>y1 && y<y2; //x在x1和x2之间,并且,y在y1和y2之间,即为撞上了}}ShootGame类的完整代码如下所示:package com.cetc.shoot;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import java.util.Arrays;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JPanel;//主程序类public class ShootGame extends JPanel{public static final int WIDTH = 400; //窗口宽public static final int HEIGHT = 654; //窗口高public static BufferedImage background; //背景图public static BufferedImage start; //启动图public static BufferedImage pause; //暂停图public static BufferedImage gameover; //游戏结束图public static BufferedImage airplane; //敌机public static BufferedImage bee; //小蜜蜂public static BufferedImage bullet; //子弹public static BufferedImage hero0; //英雄机0public static BufferedImage hero1; //英雄机1private Hero hero = new Hero(); //英雄机对象private FlyingObject[] flyings = {}; //敌人(敌机+小蜜蜂)数组private Bullet[] bullets = {}; //子弹数组private Timer timer; //定时器private int intervel = 1000/100; //时间间隔(毫秒)private int score = 0; //玩家的得分private int state;public static final int START = 0; //启动状态public static final int RUNNING = 1; //运行状态public static final int PAUSE = 2; //暂停状态public static final int GAME_OVER = 3; //游戏结束状态public ShootGame(){// flyings = new FlyingObject[2];// flyings[0] = new Airplane();// flyings[1] = new Bee();// bullets = new Bullet[1];// bullets[0] = new Bullet(150,180);}static{ //加载图片try{background = ImageIO.read(ShootGame.class.getResource('background.png'));start = ImageIO.read(ShootGame.class.getResource('start.png'));pause = ImageIO.read(ShootGame.class.getResource('pause.png'));gameover = ImageIO.read(ShootGame.class.getResource('gameover.png'));airplane = ImageIO.read(ShootGame.class.getResource('airplane.png'));bee = ImageIO.read(ShootGame.class.getResource('bee.png'));bullet = ImageIO.read(ShootGame.class.getResource('bullet.png'));hero0 = ImageIO.read(ShootGame.class.getResource('hero0.png'));hero1 = ImageIO.read(ShootGame.class.getResource('hero1.png'));}catch(Exception e){e.printStackTrace();}}/** 重写paint() g:画笔*/public void paint(Graphics g){g.drawImage(background,0,0,null); //画背景图paintHero(g); //画英雄机paintFlyingObjects(g); //画敌人(敌机+小蜜蜂)paintBullets(g); //画子弹paintScore(g); //画分数paintState(g); //画状态}/** 画英雄机对象 */public void paintHero(Graphics g){g.drawImage(hero.image,hero.x,hero.y,null); //画对象}/** 画敌人(敌机+小蜜蜂)对象 */public void paintFlyingObjects(Graphics g){for(int i=0;i<flyings.length;i++){ //遍历敌人(敌机+小蜜蜂)数组FlyingObject f = flyings[i]; //获取每一个敌人g.drawImage(f.image,f.x,f.y,null); //画敌人对象}}/** 画子弹对象 */public void paintBullets(Graphics g){for(int i=0;i<bullets.length;i++){ //遍历子弹数组Bullet b = bullets[i]; //获取每一个子弹g.drawImage(b.image,b.x,b.y,null); //画子弹对象}}public static void main(String[] args) {JFrame frame = new JFrame('Fly'); //创建一个Jframe对象ShootGame game = new ShootGame(); //创建一个JPanel对象frame.add(game); //将面板添加到框架中frame.setSize(WIDTH, HEIGHT); //设置窗口大小frame.setAlwaysOnTop(true); //设置总是在最上面frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序) frame.setLocationRelativeTo(null); //设置居中显示frame.setVisible(true); //1.设置窗口可见 2.尽快调用paint()game.action(); //启动执行}/** 随机生成飞行物 */public FlyingObject nextOne(){Random rand = new Random(); //创建随机数对象int type = rand.nextInt(20); //生成0到19之间的随机数if(type==0){ //为0时返回蜜蜂对象return new Bee();}else{ //为1到19时返回敌机对象return new Airplane();}}int flyEnteredIndex = 0; //敌人入场计数/** 敌人(敌机+小蜜蜂)入场 */public void enterAction(){ //10毫秒走一次flyEnteredIndex++; //每10毫秒增1if(flyEnteredIndex%40==0){ //400(10*40)毫秒走一次FlyingObject obj = nextOne(); //获取敌人(敌机+小蜜蜂)对象flyings = Arrays.copyOf(flyings,flyings.length+1); //扩容(扩大一个容量) flyings[flyings.length-1] = obj; //将敌人对象赋值给数组的最后一个元素}}/** 飞行物走一步 */public void stepAction(){ //10毫秒走一次hero.step(); //英雄机走一步for(int i=0;i<flyings.length;i++){ //遍历所有敌人flyings[i].step(); //每个敌人走一步}for(int i=0;i<bullets.length;i++){ //遍历所有子弹bullets[i].step(); //每个子弹走一步}}/** 启动程序的执行 */public void action(){MouseAdapter l = new MouseAdapter(){ //创建侦听器对象/** 鼠标移动事件 */public void mouseMoved(MouseEvent e){if(state==RUNNING){ //运行状态时执行int x = e.getX(); //获取鼠标的x坐标int y = e.getY(); //获取鼠标的y坐标hero.moveTo(x, y); //英雄机随着鼠标动}}/** 鼠标点击事件 */public void mouseClicked(MouseEvent e){switch(state){ //不同状态时点击后有不同的反应case START: //启动状态时state = RUNNING; //当前状态变为运行状态break;case GAME_OVER: //游戏结束状态时score = 0; //清理现场hero = new Hero();flyings = new FlyingObject[0];bullets = new Bullet[0];state = START; //当前状态变为启动状态break;}}/** 鼠标移出事件 */public void mouseExited(MouseEvent e){if(state==RUNNING){ //运行状态时state=PAUSE; //当前状态改为暂停状态}}/** 鼠标移入事件 */public void mouseEntered(MouseEvent e){if(state==PAUSE){ //暂停状态时state=RUNNING; //当前状态改为运行状态}}};this.addMouseListener(l); //处理鼠标操作事件this.addMouseMotionListener(l); //处理鼠标滑动操作timer = new Timer(); //创建定时器对象timer.schedule(new TimerTask(){public void run(){ //10毫秒走一次--定时干的那个事if(state==RUNNING){ //运行状态时执行enterAction(); //敌人(敌机+小蜜蜂)入场stepAction(); //飞行物走一步shootAction(); //英雄机发射子弹--子弹入场bangAction(); //子弹与敌人的碰撞outOfBoundsAction(); //删除越界的飞行物checkGameOverAction(); //检测游戏是否结束}repaint(); //重画,调用paint()}},intervel,intervel);}int shootIndex = 0; //射击计数/** 英雄机发射子弹(子弹入场) */public void shootAction(){ //10毫秒走一次shootIndex++; //每10毫秒增1if(shootIndex%30==0){ //每300(10*30)毫秒走一次Bullet[] bs = hero.shoot(); //获取英雄机发射出来的子弹bullets = Arrays.copyOf(bullets, bullets.length+bs.length); //扩容(bs有几个元素就扩大几个容量)System.arraycopy(bs,0,bullets,bullets.length-bs.length,bs.length); //数组的追加(将bs追加到bullets数组中) }}/** 所有子弹与所有敌人撞 */public void bangAction(){ //10毫秒走一次for(int i=0;i<bullets.length;i++){ //遍历所有子弹Bullet b = bullets[i]; //获取每一个子弹bang(b); //一个子弹与所有敌人撞}}/** 一个子弹与所有敌人撞 */public void bang(Bullet b){int index = -1; //被撞敌人的下标for(int i=0;i<flyings.length;i++){ //遍历所有敌人FlyingObject f = flyings[i]; //获取每一个敌人if(f.shootBy(b)){ //撞上了index = i; //记录被撞敌人的下标break; //其余敌人不再比较}}if(index != -1){ //有撞上的FlyingObject one = flyings[index]; //获取被撞的敌人对象if(one instanceof Enemy){ //若被撞对象是敌人Enemy e = (Enemy)one; //将被撞对象强转为敌人score += e.getScore(); //累加分数}if(one instanceof Award){ //若被撞对象是奖励Award a = (Award)one; //将被撞对象强转为奖励int type = a.getType(); //获取奖励类型switch(type){ //根据type的不同取值获取相应的奖励case Award.DOUBLE_FIRE: //奖励类型为火力时hero.addDoubleFire(); //英雄机增火力break;case Award.LIFE: //奖励类型为命时hero.addLife(); //英雄机增命break;}}//交换被撞敌人对象与数组中的最后一个元素FlyingObject t = flyings[index];flyings[index] = flyings[flyings.length-1];flyings[flyings.length-1] = t;//缩容(去掉最后一个元素,即:被撞敌人对象)flyings = Arrays.copyOf(flyings, flyings.length-1);}}/** 画分数 */public void paintScore(Graphics g){int x = 10;int y = 25;Font font = new Font(Font.SANS_SERIF,Font.BOLD,14);g.setColor(new Color(0x3A3B3B)); //设置颜色(纯红)g.setFont(font); //设置样式(字体:SANS_SERIF,样式:加粗,字号:24)g.drawString('SCORE: '+score,x,y); //画分y+=20;g.drawString('LIFE: '+hero.getLife(),x,y); //画命}/** 删除越界的飞行物 */public void outOfBoundsAction(){int index = 0; //1.不越界敌人数组下标 2.不越界敌人个数FlyingObject[] flyingLives = new FlyingObject[flyings.length]; //不越界敌人数组for(int i=0;i<flyings.length;i++){ //遍历所有敌人FlyingObject f = flyings[i]; //获取每一个敌人if(!f.outOfBounds()){ //不越界flyingLives[index] = f; //将不越界敌人添加到不越界敌人数组中index++; //1.下标增一 2.不越界敌人个数增一}}flyings = Arrays.copyOf(flyingLives, index); //将不越界敌人复制到flyings数组中,index为flyings的新长度index = 0; //1.下标归零 2.不越界个数归零Bullet[] bulletLives = new Bullet[bullets.length]; //不越界子弹数组for(int i=0;i<bullets.length;i++){ //遍历所有子弹Bullet b = bullets[i]; //获取每一个子弹if(!b.outOfBounds()){ //不越界bulletLives[index] = b; //将不越界子弹添加到不越界子弹数组中index++; //1.下标增一 2.不越界子弹个数增一}}bullets = Arrays.copyOf(bulletLives, index); //将不越界敌人复制到bullets数组中,index为bullets的新长度}。

飞机大战c语言代码

飞机大战c语言代码

飞机大战这种游戏较为复杂,无法直接给出完整的C语言源代码。

但是,我可以提供一个简单的基本构架,以便你了解如何利用C语言开始编写一个飞机大战游戏。

若要构建完整游戏,你需要进一步完善该基本结构并添加更多功能。

以下是C语言实现一个简易飞机大战游戏的基本雏形:#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>// 常量,用于界定屏幕尺寸#define SCREEN_WIDTH 50#define SCREEN_HEIGHT 20// 玩家结构体typedef struct {int x, y;} Player;// 敌人结构体typedef struct {int x, y;} Enemy;// 子弹结构体typedef struct {int x, y;} Bullet;// 按ASCII码清屏void clearScreen() {system("cls");}// 跳转到指定坐标void gotoxy(int x, int y) {COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}// 游戏循环void gameLoop() {Player player;Enemy enemy[10];Bullet bullet;int i;// 初始化游戏player.x = SCREEN_WIDTH / 2;player.y = SCREEN_HEIGHT - 1;// 敌人的初始位置for (i = 0; i < 10; i++) {enemy[i].x = i * 5 + 1;enemy[i].y = 1;}// 游戏主循环while (1) {clearScreen();// 绘制玩家gotoxy(player.x, player.y);printf("^");// 绘制敌人for (i = 0; i < 10; i++) {gotoxy(enemy[i].x, enemy[i].y);printf("V");}// 绘制子弹 (若存在)if (bullet.y >= 0) {gotoxy(bullet.x, bullet.y);printf("|");// 更新子弹位置bullet.y -= 1;// 判断是否击中敌人for (i = 0; i < 10; i++) {if (bullet.x == enemy[i].x && bullet.y == enemy[i].y) { enemy[i].y = -1; // 隐藏已经被击中的敌人}}}// 检测操作if (_kbhit()) {char input = _getch();switch (input) {case 'a': // 往左移动player.x -= 1;break;case 'd': // 往右移动player.x += 1;break;case ' ': // 发射子弹bullet.x = player.x;bullet.y = player.y - 1;break;case 'q': // 退出游戏exit(0);break;}}// 刷新画布Sleep(100);}}int main() {gameLoop();return 0;}这个代码示例使用了C语言(在Windows操作系统下运行),为玩家提供了移动(A,D键)和射击(空格键)功能。

python开发飞机大战游戏

python开发飞机大战游戏

python开发飞机⼤战游戏本⽂实例为⼤家分享了python开发飞机⼤战游戏的具体代码,供⼤家参考,具体内容如下import pygameimport randomimport math # 数学模块# 初始化界⾯pygame.init()# 设置窗⼝⼤⼩windows = pygame.display.set_mode((800, 600))# 设置窗⼝标题pygame.display.set_caption("⼩赵同学")# 引⼊图⽚ logoicon = pygame.image.load('logo.jpg')pygame.display.set_icon(icon)# 4.游戏获取背景bgcolor = pygame.image.load('bj.png')# 5.设置玩家飞机playerimg = pygame.image.load('fj.png')X = 350 # 设置玩家X轴Y = 480 # 设置玩家Y轴# 停⽌移动就可以将palyerStep改为0。

控制⼀个变量来指定飞机指定移动playerStep = 0# 添加背景⾳乐pygame.mixer.music.load('bj.mp3')pygame.mixer.music.play(-1)# 添加射中的⾳效# bao_music = pygame.mixer.Sound('bj.mp3')# 分数score = 0# 添加字体和⼤⼩font = pygame.font.Font('freesansbold.ttf', 32)# 字体类def show_score():# 显⽰的⽂字text = f"Score:{score}"# 渲染然后显⽰显⽰text True表⽰24位的字score_render = font.render(text, True, (0, 255, 0))# 指定字体放到那个位置windows.blit(score_render, (10, 10))# 游戏结束的变量over = Falseover_font = pygame.font.Font('freesansbold.ttf', 64)# 结束的提⽰语def check_over():if over:text = "Game Over"render = font.render(text, True, (255, 0, 0))windows.blit(render, (320, 200))# 8.添加敌⼈.# 11.添加多个敌⼈number_enemy = 6# 敌⼈类class Enemy:def __init__(self):#self.img = pygame.image.load('enemy.png')self.x = random.randint(200, 600) # 随机产⽣Xself.y = random.randint(50, 250) # 随机产⽣Yself.step = random.randint(2, 4) # 随机产⽣速度# 当被射中时恢复位置def reset(self):self.x = random.randint(200, 600)self.y = random.randint(50, 180)def distance(bx, by, ex, ey):a = bx - exb = by - eyreturn math.sqrt(a * a + b * b) # 开根号# 保存所有的敌⼈enemis = []for i in range(number_enemy): # 每次循环都都在class Enemy中过⼀边,所以随机产⽣⼀个敌⼈的参数并且保存到列表中 enemis.append(Enemy())# 显⽰敌⼈并且实现敌⼈的移动下沉def enemy(): # 循环保存敌⼈的列表,每个敌⼈都过在这个for循环⾥被限制了移动的轨迹global overfor e in enemis:windows.blit(e.img, (e.x, e.y))e.x += e.stepif e.x > 750 or e.x < 0: # 判断敌⼈是否到了边界e.step *= -1 # 敌⼈碰到界⾯往返e.y += 40 # 设置敌⼈往下沉# 判断敌⼈的位置如果到达指定的地⽅则游戏结束if e.y > 436:over = Trueprint("游戏结束啦")enemis.clear()# 设置飞机及飞机移动范围的函数 == 飞机类型def fiji_type(): # 设置飞机的坐标和飞机X Y轴最⼤的移动位置global X, Y# 5. 设置飞机windows.blit(playerimg, (X, Y))# 6.飞机移动X += plagerStep# 预防飞机出界if X > 680:X = 680if X < 0:X = 0# ⼦弹的类class Bullet:def __init__(self):self.img = pygame.image.load('bullet.png')self.x = X + 55 # 设置⼦弹的X轴self.y = Y + 5 # ⼦弹出现在玩家的上⽅self.step = 2 # ⼦弹移动的速度# 击中敌⼈def hit(self):global scorefor e in enemis:if distance(self.x, self.y, e.x, e.y) < 30:# 射中了bullets.remove(self)e.reset() # 重置敌⼈# 没击中加10分score += 10bullets = [] # 保存现有的⼦弹# 显⽰⼦弹移动def show_bullets():for b in bullets:windows.blit(b.img, (b.x, b.y))b.hit() # 查看是否击中了敌⼈b.y -= b.step # 往上移动# 判断⼦弹是否出了界⾯if b.y < 0:bullets.remove(b)# 3.游戏主循环running = Truewhile running:# 4.背景# 每个循环是画⼀张画组成的# 画出来bgcolorwindows.blit(bgcolor, (0, 0))# 调⽤这个字体show_score()# event.get操作事件for event in pygame.event.get():# 判断操作类型是不是QUITif event.type == pygame.QUIT:# 如果程序为False就会停⽌则关闭running = False# 7.控制飞机的移动# 通过控制键盘的事件来控制(playerStep值)飞机的移动 if event.type == pygame.KEYDOWN:# 判断按下键盘右键,按下则移动if event.key == pygame.K_RIGHT:plagerStep = 3# 判断按下左键elif event.key == pygame.K_LEFT:plagerStep = -3# 判断按下空格健的反应elif event.key == pygame.K_SPACE:# 创建⼀个⼦弹b = Bullet()bullets.append(b)# 判断松来按键停⽌,if event.type == pygame.KEYUP:plagerStep = 0# 调⽤飞机的类型的函数fiji_type()# 调⽤敌⼈这个函数enemy()show_bullets() # 显⽰⼦弹# 游戏结束语check_over()# 刷新更新数据pygame.display.update()# global 设置全局变量''' 游戏结构1.设置窗⼝⼤⼩2.背景图3.显⽰飞机4.移动飞机5.控制出界6.获取键盘事件7.显⽰敌⼈8.敌⼈移动9.下沉和随机位置10.显⽰多个敌⼈11.响应空格键12.添加⼦弹13.发射⼦弹14.射中检测之距离15.射中检测16.添加⾳效17.添加并显⽰分数18.游戏结束19.结束提⽰'''以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

python飞机大战源码和素材

python飞机大战源码和素材

python飞机⼤战源码和素材python飞机⼤战素材及代码已上传百度云,链接: 提取码: pqxnplane_main1 import pygame2 from plane_sprites import *345 class PlaneGame(object):6 """飞机⼤战主游戏"""78 def __init__(self):9 print("游戏初始化")1011 # 1.创建游戏的窗⼝12 self.screen = pygame.display.set_mode(SCREEN_RECT.size)13 # 2.创建游戏的时钟14 self.clock = pygame.time.Clock()15 # 3.调⽤私有⽅法,精灵和精灵组的创建16 self.__create_sprites()1718 # 4.设置定时器事件——创建敌机 1S19 pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)20 pygame.time.set_timer(HERO_FIRE_EVENT, 500)2122 # 定义精灵和精灵组23 def __create_sprites(self):24 # 创建背景精灵和精灵组25 bg1 = Background()26 bg2 = Background(True)27 # bg2起始位置在bg1的上⽅28 # bg2.rect.y = -bg2.rect.height2930 self.back_group = pygame.sprite.Group(bg1, bg2)3132 # 创建敌机的精灵组33 self.enemy_group = pygame.sprite.Group()3435 # 创建英雄的精灵和精灵组36 self.hero = Hero()37 self.hero_group = pygame.sprite.Group(self.hero)3839 # 游戏循环40 def start_game(self):41 print("游戏开始...")4243 while True:44 # 1.设置刷新帧率45 self.clock.tick(FRAME_PER_SEC)46 # 2.事件监听47 self.__even_handler()48 # 3.碰撞检测49 self.__check_collide()50 # 4.更新/绘制精灵组51 self.__update_sprites()52 # 5.更新屏幕显⽰53 pygame.display.update()5455 pass5657 # 定义事件监听函数58 def __even_handler(self):59 for event in pygame.event.get():6061 # 判断是否退出游戏62 if event.type == pygame.QUIT:63 PlaneGame.__game_over()64 elif event.type == CREATE_ENEMY_EVENT:65 # print("敌机出场...")66 # 创建敌机精灵67 enemy = Enemy()6869 # 将敌机精灵添加到敌机精灵组70 self.enemy_group.add(enemy)71 elif event.type == HERO_FIRE_EVENT:72 self.hero.fire()73 # 直接判断键盘按键不能持续的获取按键事件74 # elif event.type == pygame.KEYDOWN and event.type == pygame.K_RIGHT:75 # print("向右移动...")7677 # 使⽤键盘模块提供的⽅法获取键盘按键——键盘模块可以持续的获取键盘按键78 keys_pressed = pygame.key.get_pressed()79 # 判断元祖中对应的按键索引值80 if keys_pressed[pygame.K_RIGHT] or keys_pressed[pygame.K_d]:81 self.hero.rect.x += 282 elif keys_pressed[pygame.K_LEFT] or keys_pressed[pygame.K_a]:83 self.hero.rect.x -= 284 elif keys_pressed[pygame.K_UP] or keys_pressed[pygame.K_w]:85 self.hero.rect.y -= 286 elif keys_pressed[pygame.K_DOWN] or keys_pressed[pygame.K_s]:87 self.hero.rect.y += 288 else:89 self.hero.speed = 09091 # 定义碰撞检测92 def __check_collide(self):9394 # 1.⼦弹摧毁敌机—— groupcollide可以判断两个精灵组之间是否碰撞95 pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)9697 # 敌机撞毁英雄——spritecollide可以判断精灵和精灵组之间是否碰撞98 enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)99100 # 判断列表是否有内容101 if len(enemies) > 0:102103 # 让英雄牺牲104 self.hero.kill()105106 # 结束游戏107 PlaneGame.__game_over()108109 # 定义精灵组调⽤update()和draw()⽅法实现屏幕更新110 def __update_sprites(self):111112 self.back_group.update()113 self.back_group.draw(self.screen)114 self.enemy_group.update()115 self.enemy_group.draw(self.screen)116 self.hero_group.update()117 self.hero_group.draw(self.screen)118 self.hero.bullets.update()119 self.hero.bullets.draw(self.screen)120121 # 游戏结束122 @staticmethod123 def __game_over():124 print("游戏结束...")125126 pygame.quit()127 exit()128129130 if __name__ == '__main__':131132 # 创建游戏对象133 game = PlaneGame()134135 # 启动游戏136 game.start_game()plane_sprites1 import random2 import pygame34 # 定义屏幕⼤⼩的常量5 SCREEN_RECT = pygame.Rect(0, 0, 480, 700)6 # 定义刷新帧率的常量7 FRAME_PER_SEC = 608 # 创建敌机的定时器常量9 CREATE_ENEMY_EVENT = EREVENT10 # 英雄发射⼦弹事件11 HERO_FIRE_EVENT = EREVENT + 1121314 class GameSprite(pygame.sprite.Sprite):15 """飞机⼤战游戏精灵"""1617 def __init__(self, image_name, speed=1):1819 # 调⽤⽗类的初始化⽅法20 super().__init__()2122 # 定义对象的属性23 self.image = pygame.image.load(image_name)24 self.rect = self.image.get_rect()25 self.speed = speed2627 def update(self):2829 # 在屏幕的垂直⽅向上移动30 self.rect.y += self.speed313233 class Background(GameSprite):34 """游戏背景精灵"""35 def __init__(self, is_alt=False):3637 # 1.调⽤⽗类⽅法实现精灵的创建38 super().__init__("./images/background.png")3940 if is_alt:41 self.rect.y = -self.rect.height4243 def update(self):4445 # 1.调⽤⽗类的⽅法实现46 super().update()4748 # 2.判断是否移出屏幕,如果移出,将图像移⾄屏幕上⽅49 if self.rect.y >= SCREEN_RECT.height:50 self.rect.y = -self.rect.height515253 class Enemy(GameSprite):54 """敌机精灵"""5556 def __init__(self):5758 # 1.调⽤⽗类⽅法,创建敌机精灵,同时指定敌机图⽚59 super().__init__("./images/enemy1.png")60 # 2.指定敌机的初始随机速度——1到361 self.speed = random.randint(1, 3)6263 # 3.指定敌机的初始随机位置64 self.rect.bottom = 0 # 设置敌机是从屏幕外飞进屏幕65 # 敌机要完整的在屏幕内 — 敌机的最⼤X值是屏幕的宽减去敌机的宽66 max_x = SCREEN_RECT.width-self.rect.width67 self.rect.x = random.randint(0, max_x)6869 def update(self):7071 # 1.调⽤⽗类⽅法保持垂直⽅向的飞⾏72 super().update()73 # 2.判断是否飞出屏幕,如果是需要从精灵组中删除敌机74 if self.rect.y >= SCREEN_RECT.height: # 敌机的y值⼤于屏幕的⾼即飞出屏幕75 # print("飞出屏幕,需从精灵组中删除...")76 # kill⽅法可以将精灵从所有精灵组中移出,精灵就好被⾃动销毁77 self.kill()7879 # 判断敌机是否被销毁80 def __del__(self):81 # print("敌机挂了 %s" % self.rect)82 pass838485 class Hero(GameSprite):86 """英雄精灵"""8788 def __init__(self):8990 # 1.调⽤⽗类⽅法设置image和速度91 super().__init__("./images/me1.png", 0)92 # 2.设置英雄的初始位置93 self.rect.centerx = SCREEN_RECT.centerx94 self.rect.bottom = SCREEN_RECT.bottom - 1209596 # 3.创建⼦弹的精灵组97 self.bullets = pygame.sprite.Group()9899 def update(self):100101 # # 英雄在⽔平⽅向移动102 # self.rect.x += self.speed103104 # 控制英雄不能离开屏幕105 if self.rect.x < 0:106 self.rect.x = 0107 elif self.rect.right > SCREEN_RECT.width:108 self.rect.right = SCREEN_RECT.width109 elif self.rect.y < 0:110 self.rect.y = 0111 elif self.rect.bottom > SCREEN_RECT.bottom:112 self.rect.bottom = SCREEN_RECT.bottom113114 def fire(self):115116 # 1.创建⼦弹精灵117 # bullet = Bullet()118 # bullet1 = Bullet()119 # bullet2 =Bullet()120121 # # 2.设置⼦弹精灵的位置122 # bullet.rect.bottom = self.rect.y - 20123 # bullet1.rect.bottom = self.rect.y124 # bullet2.rect.bottom = self.rect.y -40125 # bullet.rect.centerx = self.rect.centerx126 # bullet1.rect.centerx = self.rect.centerx127 # bullet2.rect.centerx = self.rect.centerx128129 for i in (0, 1, 2):130131 # 1.创建⼦弹精灵132 bullet = Bullet()133134 # 2.设置⼦弹的位置135 bullet.rect.bottom = self.rect.y - i*20136 bullet.rect.centerx = self.rect.centerx137138 # 3.将精灵添加到精灵组139 self.bullets.add(bullet)140 pass141142143 class Bullet(GameSprite):144 """⼦弹精灵"""145146 def __init__(self):147148 # 调⽤⽗类⽅法设置⼦弹图⽚和初始速度149 super().__init__("./images/bullet2.png", -2) 150151 def update(self):152153 # 调⽤⽅法让⼦弹沿垂直⽅向飞⾏154 super().update()155156 # 判断⼦弹是否飞出屏幕157 if self.rect.bottom < 0:158 self.kill()159160 # def __del__(self):161 # print("⼦弹被销毁")。

python实现飞机大战项目

python实现飞机大战项目

python实现飞机⼤战项⽬本⽂实例为⼤家分享了python实现飞机⼤战的具体代码,供⼤家参考,具体内容如下引⽤了⼩甲鱼的框架,往上⾯添加了⼀些新功能1、我⽅飞机模块import pygameclass MyPlane(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image1 = pygame.image.load(r'E:\learn pygame\image\me1.png').convert_alpha()self.image2 = pygame.image.load(r'E:\learn pygame\image\me2.png').convert_alpha()self.image3 = pygame.image.load(r'E:\learn pygame\image\me_protect.png').convert_alpha()self.destroy_images = []self.destroy_images.extend([\pygame.image.load(r'E:\learn pygame\image\me_destroy_1.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\me_destroy_2.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\me_destroy_3.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\me_destroy_4.png').convert_alpha() \])self.rect = self.image1.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.top = (self.width - self.rect.width) // 2,self.height - self.rect.height - 60self.speed = 10self.active = Trueself.invincible = Falseself.mask = pygame.mask.from_surface(self.image1)def moveUp(self):if self.rect.top > 0:self.rect.top -= self.speedelse:self.rect.top = 0def moveDown(self):if self.rect.bottom < self.height - 30:self.rect.top += self.speedelse:self.rect.bottom = self.height - 30def moveLeft(self):if self.rect.left > 0:self.rect.left -= self.speedelse:self.rect.left = 0def moveRight(self):if self.rect.right < self.width:self.rect.left += self.speedelse:self.rect.right = self.widthdef reset(self):self.rect.left,self.rect.top = (self.width - self.rect.width) // 2,self.height - self.rect.height - 30self.active = Trueself.invincible = True2、敌机与背景动图模块import pygamefrom random import *class SmallEnemy(pygame.sprite.Sprite):energy = 1def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\enemy1.png').convert_alpha()self.destroy_images = []self.destroy_images.extend([\pygame.image.load(r'E:\learn pygame\image\enemy1_down1.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy1_down2.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy1_down3.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy1_down4.png').convert_alpha() \])self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 2self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)self.mask = pygame.mask.from_surface(self.image)self.energy = SmallEnemy.energyself.hit = Falsedef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = SmallEnemy.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)class MidEnemy(pygame.sprite.Sprite):energy = 4def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\enemy2.png').convert_alpha()self.image_hit = pygame.image.load(r'E:\learn pygame\image\enemy2_hit.png').convert_alpha()self.destroy_images = []self.destroy_images.extend([\pygame.image.load(r'E:\learn pygame\image\enemy2_down1.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy2_down2.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy2_down3.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy2_down4.png').convert_alpha() \])self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-10 * self.height, -self.height)self.mask = pygame.mask.from_surface(self.image)self.energy = MidEnemy.energyself.hit = Falsedef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = MidEnemy.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-10 * self.height, -self.height)class BigEnemy(pygame.sprite.Sprite):energy = 8def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image1 = pygame.image.load(r'E:\learn pygame\image\enemy3_n1.png').convert_alpha() self.image2 = pygame.image.load(r'E:\learn pygame\image\enemy3_n2.png').convert_alpha() self.image_hit = pygame.image.load(r'E:\learn pygame\image\enemy3_hit.png').convert_alpha() self.destroy_images = []self.destroy_images.extend([\pygame.image.load(r'E:\learn pygame\image\enemy3_down1.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy3_down2.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy3_down3.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy3_down4.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy3_down5.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\enemy3_down6.png').convert_alpha() \])self.rect = self.image1.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 2self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-15 * self.height, -5 * self.height)self.mask = pygame.mask.from_surface(self.image1)self.energy = BigEnemy.energyself.hit = Falsedef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = BigEnemy.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-15 * self.height, -5 * self.height)class Cloud1(pygame.sprite.Sprite):energy = 2def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\cloud1.png').convert_alpha()self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 1self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)self.energy = Cloud1.energydef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = Cloud1.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)class Cloud2(pygame.sprite.Sprite):energy = 2def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\cloud1.png').convert_alpha()self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 1self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)self.energy = Cloud2.energydef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = Cloud2.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-5 * self.height, 0)class BombEnemy(pygame.sprite.Sprite):energy = 10self.image1 = pygame.image.load(r'E:\learn pygame\image\bomb_enemy1.png').convert_alpha() self.image2 = pygame.image.load(r'E:\learn pygame\image\bomb_enemy2.png').convert_alpha() self.rect = self.image1.get_rect()self.destroy_images = []self.destroy_images.extend([ \pygame.image.load(r'E:\learn pygame\image\bomb_enemy_down1.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\bomb_enemy_down2.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\bomb_enemy_down3.png').convert_alpha(), \pygame.image.load(r'E:\learn pygame\image\bomb_enemy_down4.png').convert_alpha(), \])self.width,self.height = bg_size[0],bg_size[1]self.speed = 2self.active = Trueself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-15 * self.height, -5 * self.height)self.mask = pygame.mask.from_surface(self.image1)self.energy = BombEnemy.energyself.hit = Falsedef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.energy = BombEnemy.energyself.rect.left,self.rect.top = \randint(0,self.width - self.rect.width), \randint(-15 * self.height, -5 * self.height)class BackGround1(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\background1.png').convert_alpha() self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 1self.active = Trueself.rect.center = ((self.width // 2), (self.height // 2))def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.rect.center = ((self.width // 2), -(self.height // 2))class BackGround2(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\background1.png').convert_alpha() self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.speed = 1self.active = Trueself.rect.center = ((self.width // 2), -(self.height // 2))def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = Trueself.rect.center = ((self.width // 2), -(self.height // 2))3、⼦弹模块import pygameclass Bullet1(pygame.sprite.Sprite):def __init__(self,position):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bullet1.png').convert_alpha()self.rect = self.image.get_rect()self.rect.left,self.rect.top = positionself.speed = 18self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):self.rect.top -= self.speedif self.rect.top < 0:self.active = Falsedef reset(self,position):self.rect.left,self.rect.top = positionself.active = Trueclass Bullet2(pygame.sprite.Sprite):def __init__(self,position):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bullet2.png').convert_alpha()self.rect = self.image.get_rect()self.rect.left,self.rect.top = positionself.speed = 18self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):self.rect.top -= self.speedif self.rect.top < 0:self.active = Falsedef reset(self,position):self.rect.left,self.rect.top = positiondef __init__(self,position):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bullet3.png').convert_alpha()self.rect = self.image.get_rect()self.rect.left,self.rect.top = positionself.speed = 120self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):self.rect.top -= self.speedif self.rect.top < 0:self.active = Falsedef reset(self,position):self.rect.left,self.rect.top = positionself.active = Trueclass Bullet4(pygame.sprite.Sprite):def __init__(self,position,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bullet4.png').convert_alpha()self.rect = self.image.get_rect()self.rect.left,self.rect.top = positionself.width,self.height = bg_size[0],bg_size[1]self.speed = 9self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):self.rect.top -= self.speedif self.rect.top < 0:self.active = Falsedef reset(self,position):self.rect.left,self.rect.top = positionself.active = True4、补给模块import pygamefrom random import *class Bullet_Supply(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bullet_supply.png').convert_alpha() self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100class Bomb_Supply(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\bomb_supply.png').convert_alpha() self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100class Laser_Supply(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\laser_supply.png').convert_alpha() self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100class Fire_Supply(pygame.sprite.Sprite):self.image = pygame.image.load(r'E:\learn pygame\image\fire_supply.png').convert_alpha()self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100class Me_Protect_Supply(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\me_protect_supply.png').convert_alpha()self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100class Life_Supply(pygame.sprite.Sprite):def __init__(self,bg_size):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\life_supply.png').convert_alpha()self.rect = self.image.get_rect()self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -100self.speed = 5self.active = Falseself.mask = pygame.mask.from_surface(self.image)def move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.active = Falsedef reset(self):self.active = Trueself.rect.left,self.rect.bottom = \randint(0,self.width - self.rect.width), -1005、掉落星星模块(还没完善好)import pygameclass Star(pygame.sprite.Sprite):energy = 1def __init__(self,bg_size,star_left,star_top):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(r'E:\learn pygame\image\star_bling1.png').convert_alpha()self.rect = self.image.get_rect()self.star_images = []self.star_images.extend([pygame.image.load(r'E:\learn pygame\image\star_bling1.png').convert_alpha(),pygame.image.load(r'E:\learn pygame\image\star_bling2.png').convert_alpha(),pygame.image.load(r'E:\learn pygame\image\star_bling3.png').convert_alpha() self.width,self.height = bg_size[0],bg_size[1]self.rect.left,self.rect.top = star_left,star_topself.speed = 1self.active = Trueself.is_star = Falseself.star_is_touch = Falsedef move(self):if self.rect.top < self.height:self.rect.top += self.speedelse:self.reset()def reset(self):self.active = True6、主模块import pygameimport sysimport tracebackimport timeimport myplaneimport enemyimport bulletimport supplyimport starfrom random import *from pygame.locals import *pygame.init()pygame.mixer.init()bg_size = width, height = 450,675screen = pygame.display.set_mode(bg_size)pygame.display.set_caption('飞机⼤战')background = pygame.image.load(r'E:\learn pygame\image\background1.png').convert()background_rect = background.get_rect()BLACK = (0,0,0)WHITE = (255,255,255)GREEN = (0,255,0)RED = (255,0,0)#载⼊游戏⾳乐pygame.mixer.music.load(r'E:\learn pygame\music\bg_music.ogg')pygame.mixer.music.set_volume(0.2)bomb_enemy_fly_sound = pygame.mixer.Sound(r'E:\learn pygame\music\bomb_enemy_flying.wav') bomb_enemy_fly_sound.set_volume(0.1)enemy3_fly_sound = pygame.mixer.Sound(r'E:\learn pygame\music\enemy3_flying.wav')enemy3_fly_sound.set_volume(0.1)enemy1_down_sound = pygame.mixer.Sound(r'E:\learn pygame\music\enemy1_down.wav')enemy1_down_sound.set_volume(0.5)enemy2_down_sound = pygame.mixer.Sound(r'E:\learn pygame\music\enemy2_down.wav')enemy2_down_sound.set_volume(0.5)enemy3_down_sound = pygame.mixer.Sound(r'E:\learn pygame\music\bomb_enemy_down.wav') enemy3_down_sound.set_volume(0.5)bomb_enemy_down_sound = pygame.mixer.Sound(r'E:\learn pygame\music\bomb_enemy_down.wav') bomb_enemy_down_sound.set_volume(0.5)me_down_sound = pygame.mixer.Sound(r'E:\learn pygame\music\me_down.wav')me_down_sound.set_volume(0.5)upgrade_sound = pygame.mixer.Sound(r'E:\learn pygame\music\upgrade.wav')upgrade_sound.set_volume(0.5)bomb_sound = pygame.mixer.Sound(r'E:\learn pygame\music\use_bomb.wav')bomb_sound.set_volume(0.5)supply_sound = pygame.mixer.Sound(r'E:\learn pygame\music\supply.wav')supply_sound.set_volume(0.5)get_bomb_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_bomb.wav')get_bomb_sound.set_volume(0.5)get_bullet_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_bullet.wav')get_bullet_sound.set_volume(0.5)get_laser_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_laser.wav')get_laser_sound.set_volume(0.5)get_fire_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_fire.wav')get_fire_sound.set_volume(0.5)get_me_protect_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_me_protect.wav')get_me_protect_sound.set_volume(0.5)get_life_sound = pygame.mixer.Sound(r'E:\learn pygame\music\get_life.wav')get_life_sound.set_volume(0.5)bullet_sound = pygame.mixer.Sound(r'E:\learn pygame\music\bullet.wav')bullet_sound.set_volume(0.2)fire_bullet_sound = pygame.mixer.Sound(r'E:\learn pygame\music\fire_bullet.wav')fire_bullet_sound.set_volume(0.2)def add_small_enemies(group1,group2,num):for i in range(num):e1 = enemy.SmallEnemy(bg_size)group1.add(e1)group2.add(e1)def add_mid_enemies(group1,group2,num):for i in range(num):e2 = enemy.MidEnemy(bg_size)group1.add(e2)group2.add(e2)def add_big_enemies(group1,group2,num):for i in range(num):e3 = enemy.BigEnemy(bg_size)group1.add(e3)group2.add(e3)def add_bomb_enemies(group1,group2,num):for i in range(num):e3 = enemy.BombEnemy(bg_size)group1.add(e3)group2.add(e3)def add_cloud1_enemies(group1,group2,num):for i in range(num):e4 = enemy.Cloud1(bg_size)group1.add(e4)group2.add(e4)def add_cloud2_enemies(group1,group2,num):for i in range(num):e5 = enemy.Cloud2(bg_size)group1.add(e5)group2.add(e5)def add_background1(group1,group2,num):for i in range(num):e6 = enemy.BackGround1(bg_size)group1.add(e6)group2.add(e6)def add_background2(group1,group2,num):for i in range(num):e7 = enemy.BackGround2(bg_size)group1.add(e7)group2.add(e7)def add_star(group1,group2,star_left,star_top,num):for i in range(num):e8 = star.Star(bg_size,star_left,star_top)group1.add(e8)group2.add(e8)def inc_speed(inc,*targets):for each in targets:for every in each:every.speed += incdef inc_speed_background(inc,target):for each in target:each.speed += incdef inc_speed_me(inc,target):target.speed += incdef inc_speeds(inc,*targets):for each in targets:for every in each:every.speed += incdef main():pygame.mixer.music.play(-1)#⽣成我⽅飞机、背景、敌机、云朵、星星的类,以便做碰撞检测me = myplane.MyPlane(bg_size)enemies = pygame.sprite.Group()clouds = pygame.sprite.Group()stars = pygame.sprite.Group()bullets = pygame.sprite.Group()#⽣成背景1background1 = pygame.sprite.Group()add_background1(background1,backgrounds,1)#⽣成背景2background2 = pygame.sprite.Group()add_background2(background2,backgrounds,1)#⽣成敌⽅⼩型飞机small_enemies = pygame.sprite.Group()add_small_enemies(small_enemies,enemies,15)#⽣成敌⽅中型飞机mid_enemies = pygame.sprite.Group()add_mid_enemies(mid_enemies,enemies,4)#⽣成敌⽅⼤型飞机big_enemies = pygame.sprite.Group()add_big_enemies(big_enemies,enemies,2)#⽣成敌⽅超级炸弹bomb_enemies = pygame.sprite.Group()add_bomb_enemies(bomb_enemies,enemies,1)#⽣成云朵1cloud1_enemies = pygame.sprite.Group()add_cloud1_enemies(cloud1_enemies,clouds,1)#⽣成云朵2cloud2_enemies = pygame.sprite.Group()add_cloud2_enemies(cloud2_enemies,clouds,1)#⽣成星星star = pygame.sprite.Group()#⽣成普通⼦弹bullet1 = []bullet1_index = 0BULLET1_NUM = 6for i in range(BULLET1_NUM):bullet1.append(bullet.Bullet1(me.rect.midtop))clock = pygame.time.Clock()#⽣成超级⼦弹bullet2 = []bullet2_index = 0BULLET2_NUM = 12for i in range(BULLET2_NUM // 2):bullet2.append(bullet.Bullet2((me.rect.centerx - 33,me.rect.centery)))bullet2.append(bullet.Bullet2((me.rect.centerx + 30,me.rect.centery)))clock = pygame.time.Clock()#⽣成激光bullet3 = []bullet3_index = 0BULLET3_NUM = 1for i in range(BULLET3_NUM):bullet3.append(bullet.Bullet3((me.rect.midtop)))clock = pygame.time.Clock()#⽣成⽕焰弹bullet4 = []bullet4_index = 0BULLET4_NUM = 4for i in range(BULLET4_NUM):bullet4.append(bullet.Bullet4((me.rect.midtop),bg_size))clock = pygame.time.Clock()#中弹图⽚索引e1_destroy_index = 0e2_destroy_index = 0e3_destroy_index = 0e4_destroy_index = 0me_destroy_index = 0#统计得分和星星score = 0score_font = pygame.font.Font(r'E:\learn pygame\font\font.ttf',20)#统计星星和加载星星图⽚star_score = 0star_score_font = pygame.font.Font(r'E:\learn pygame\font\font.ttf',20)star_score_image = pygame.image.load(r'E:\learn pygame\image\star_score.png').convert_alpha()star_score_rect = star_score_image.get_rect()#标志是否暂停游戏paused = Falsepaused_nor_image = pygame.image.load(r'E:\learn pygame\image\pause_nor.png').convert_alpha()paused_pressed_image = pygame.image.load(r'E:\learn pygame\image\pause_pressed.png').convert_alpha() resume_nor_image = pygame.image.load(r'E:\learn pygame\image\resume_nor.png').convert_alpha()resume_pressed_image = pygame.image.load(r'E:\learn pygame\image\resume_pressed.png').convert_alpha() paused_rect = paused_nor_image.get_rect()paused_rect.left,paused_rect.top = width - paused_rect.width - 10,10paused_image = paused_nor_image#游戏暂停画⾯continues_image = pygame.image.load(r'E:\learn pygame\image\continues.png').convert_alpha()continues_rect = continues_image.get_rect()continues_rect.left,continues_rect.top = \(width - continues_rect.width) // 2, \(height - continues_rect.height) // 2#设置难度级别level = 1#全屏炸弹bomb_image = pygame.image.load(r'E:\learn pygame\image\bomb.png').convert_alpha()bomb_rect = bomb_image.get_rect()bomb_font = pygame.font.Font(r'E:\learn pygame\font\font.ttf',30)bomb_num = 3#每30秒发放⼀个补给包bullet_supply = supply.Bullet_Supply(bg_size)bomb_supply = supply.Bomb_Supply(bg_size)laser_supply = ser_Supply(bg_size)fire_supply = supply.Fire_Supply(bg_size)me_protect_supply = supply.Me_Protect_Supply(bg_size)life_supply = supply.Life_Supply(bg_size)pygame.time.set_timer(SUPPLY_TIME, 18 * 1000)#标志是否使⽤正常⼦弹is_normal_bullet = True#超级⼦弹定时器DOUBLE_BULLET_TIME = USEREVENT + 1#标志是否使⽤超级⼦弹is_double_bullet = False#解除我⽅⽆敌状态定时器INVINCIBLE_TIME = USEREVENT + 2#激光定时器LASER_BULLET_TIME = USEREVENT + 3#标志是否使⽤激光is_laser_bullet = False#⽕焰弹定时器FIRE_BULLET_TIME = USEREVENT + 4#标志是否使⽤⽕焰弹is_fire_bullet = False#保护罩定时器ME_PROTECT_BULLET_TIME = USEREVENT + 5#标志是否使⽤保护罩is_me_protect_bullet = False#死亡⽣成星星图⽚索引s1_star_index = 0#⽣命数量life_image = pygame.image.load(r'E:\learn pygame\image\life.png').convert_alpha()life_rect = life_image.get_rect()life_num = 3#游戏开始画⾯logo_image = pygame.image.load(r'E:\learn pygame\image\logo.png').convert_alpha()logo_rect = logo_image.get_rect()logo_rect.left,logo_rect.top = \(width - logo_rect.width) // 2, \(height - logo_rect.height) // 2begingame_image = pygame.image.load(r'E:\learn pygame\image\begingame.png').convert_alpha() begingame_rect = begingame_image.get_rect()begingame_rect.left,begingame_rect.top = \(width - begingame_rect.width) // 2, \(logo_rect.bottom + 10)#游戏结束画⾯gameover_font = pygame.font.Font(r'E:\learn pygame\font\font.ttf',48)again_image = pygame.image.load(r'E:\learn pygame\image\again.png').convert_alpha()again_rect = again_image.get_rect()gameover_image = pygame.image.load(r'E:\learn pygame\image\gameover.png').convert_alpha() gameover_rect = gameover_image.get_rect()#⽤于阻⽌重复打开记录⽂件recorded = False#⽤于切换图⽚switch_image = True#⽤于延迟delay = 100#游戏开始running = True#正式开始游戏start = Falsewhile running:for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()elif event.type == MOUSEBUTTONDOWN:if event.button == 1 and paused_rect.collidepoint(event.pos):paused = not pausedif paused:pygame.time.set_timer(SUPPLY_TIME,0)pygame.mixer.music.pause()pygame.mixer.pause()else:pygame.time.set_timer(SUPPLY_TIME,30 * 1000)pygame.mixer.music.unpause()pygame.mixer.unpause()elif event.type == MOUSEMOTION:if paused_rect.collidepoint(event.pos):if paused:paused_image = resume_pressed_imageelse:paused_image = paused_pressed_imageelse:if paused:paused_image = resume_nor_imageelse:paused_image = paused_nor_imageelif event.type == KEYDOWN:if event.key == K_SPACE:if bomb_num:bomb_num -= 1bomb_sound.play()for each in enemies:if each.rect.bottom > 0:each.active = Falseelif event.type == SUPPLY_TIME:supply_sound.play()if choice([1,2,3,4,5,6]) == 1:bomb_supply.reset()elif choice([1,2,3,4,5,6]) == 2:bullet_supply.reset()elif choice([1,2,3,4,5,6]) == 3:laser_supply.reset()elif choice([1,2,3,4,5,6]) == 4:fire_supply.reset()elif choice([1,2,3,4,5,6]) == 5:。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_D)
{
x=x+7;
}
if(e.getKeyCode()==KeyEvent.VK_A){
x=x-7;
}
if(e.getKeyCode()==KeyEvent.VK_W){
import javax.swing.*;
public class TakGame extends JFrame {
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
TakGame tg=new TakGame();
g.drawImage(im, x,y, 60,50, this);
break;
case 1:
Image im1=Toolkit.getDefaultToolkit().
getImage(Panel.class.getResource("/tk.PNG"));
g.drawImage(im1, x+150,y+500, 60,50, this);
//画出子弹
if(mytk.z != null)
{ g.setColor(Color.yellow);
g.draw3DRect(mytk.z.x+165,mytk.z.y+480, 4, 4, false);
}
this.drawTank(x, y, g, 1);
for(int i=0;i<drtk.size();i++){
while(true)
{
try{
Thread.sleep(50);
}catch(Exception e){
}
y=y-3;
}
}
}
y=y-5;
}
if(e.getKeyCode()==KeyEvent.VK_S){
y=y+5;
}
if(e.getKeyCode()==KeyEvent.VK_J)
{
this.mytk.kaiHuo();
}
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
int type = 0;
this.drawTank(drt).getX(), g, type);
}
}
public MyPanel()
{
mytk=new MyTk(11,11);
for (int i=0;i<drtksize;i++){
DrTk dtk=new DrTk((i+1)*50,0);
MyTk mytk=null;
//定义敌人坦克
Vector<DrTk> drtk=new Vector<DrTk>();
int drtksize=4;
int x;
int y;
//重写paint
public void paint(Graphics g){
g.fillRect(0, 0, 400, 600);
}
//构造函数
public TakGame()
{
mp=new MyPanel();
//启动线程
Thread t=new Thread(mp);
t.start();
this.add(mp);
this.addKeyListener(mp);
this.setLocation(400, 90);
this.setSize(400, 600);
t.start();
}
}
//敌人的坦克类
class DrTk extends TanKe implements Runnable{
public DrTk(int x, int y) {
super(x, y);
}
@Override
public void run() {
// TODO Auto-generated method stub
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public TanKe(int x,int y)
{
this.x=x;
this.y=y;
while(true){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
this.repaint();
}
}
}
//坦克类
class TanKe {
//坦克的坐标
int x=0;
int y=0;
int type;
public int getX() {
while(true){
y+=1;
}
}
}
//子弹类
class ZiD implements Runnable{
int x;
int y;
public ZiD(int x,int y){
this.x=x;
this.y=y;
}
@Override
public void run() {
// TODO Auto-generated method stub
package com.Tak;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;
import java.util.Vector;
drtk.add(dtk);
}
}
public void drawTank(int x,int y,Graphics g,int type){
switch(type){
case 0:
Image im=Toolkit.getDefaultToolkit().
getImage(Panel.class.getResource("/tk1.PNG"));
}
}
//我的坦克类
class MyTk extends TanKe{
//子弹
ZiD z=null;
public MyTk(int x, int y)
{
super(x, y);
}
//发出子弹
public void kaiHuo(){
z=new ZiD(x,y);
Thread t=new Thread(z);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//面板
class MyPanel extends JPanel implements KeyListener,Runnable
{
//定义一个my坦克
相关文档
最新文档