飞机小游戏源代码
用Java实现一个简单的打飞机游戏

用Java实现一个简单的打飞机游戏打飞机游戏是一类经典的游戏,具有简单、刺激和容易上手的特点。
在本文中,我们将使用Java编程语言来实现一个简单的打飞机游戏。
要实现这个游戏,我们可以分为三个主要的步骤:游戏初始化、游戏逻辑和游戏界面。
第一步是游戏初始化。
我们需要设置游戏窗口的大小和标题,以及创建游戏界面所需的元素,如玩家飞机、敌机和子弹。
我们可以使用Java提供的图形库,如AWT或JavaFX来创建游戏窗口和界面元素。
第二步是游戏逻辑。
我们需要定义游戏的规则和行为。
首先,我们需要让玩家飞机可以根据用户的输入(如键盘按键)进行移动。
然后,我们需要创建敌机,并使其在游戏界面上自动移动。
接下来,我们需要创建子弹,并使其可以击中敌机。
当玩家的飞机与敌机相撞或者子弹击中敌机时,游戏将结束。
最后一步是游戏界面。
我们需要定义游戏界面的显示方式。
可以在游戏界面上显示玩家的飞机和敌机,并实时更新它们的位置。
还可以显示分数和游戏状态,以提供更好的游戏体验。
下面是一个简单的示例代码,演示了如何使用Java实现一个简单的打飞机游戏:```javaimport javax.swing.*;import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;public class SimplePlaneGame extends JFrame implements KeyListener {private final int WINDOW_WIDTH = 800;private final int WINDOW_HEIGHT = 600;private int playerX = 400;private int playerY = 500;private boolean gameRunning = true;public SimplePlaneGame() {setTitle("Simple Plane Game");setSize(WINDOW_WIDTH, WINDOW_HEIGHT);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setResizable(false);setLocationRelativeTo(null);setLayout(null);setVisible(true);addKeyListener(this);}public void paint(Graphics g) {super.paint(g);g.setColor(Color.BLUE);g.fillRect(playerX, playerY, 50, 50);}public void keyPressed(KeyEvent e) {if (e.getKeyCode() == KeyEvent.VK_LEFT) {playerX -= 5;repaint();} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { playerX += 5;repaint();}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}public static void main(String[] args) {SimplePlaneGame game = new SimplePlaneGame();while (game.gameRunning) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}}```在这个示例中,我们使用了一个继承自JFrame的类来创建游戏窗口。
python 打飞机代码

以下是一个简单的Python 打飞机游戏的代码示例:```pythonimport pygameimport random# 初始化Pygamepygame.init()# 设置窗口大小screen_width = 800screen_height = 600screen = pygame.display.set_mode((screen_width, screen_height))# 设置颜色white = (255, 255, 255)blue = (0, 0, 255)red = (255, 0, 0)# 加载飞机和子弹图片plane_image = pygame.image.load("plane.png").convert_alpha()bullet_image = pygame.image.load("bullet.png").convert_alpha()bullet_speed = 5# 设置飞机和子弹的位置和速度plane_x = screen_width // 2plane_y = screen_height // 2bullets = []for i in range(10):bullet_x = random.randint(0, screen_width - bullet_image.get_width())bullet_y = random.randint(0, screen_height)bullets.append((bullet_x, bullet_y))bullet_speed *= 1.1# 游戏主循环while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:bullet_x = plane_x + plane_width // 2 - bullet_image.get_width() // 2bullet_y = plane_y - bullet_image.get_height()bullets[-1] = (bullet_x, bullet_y)bullets.append(None)bullets[len(bullets) - 1].direction = random.choice([-1, 1])keys = pygame.key.get_pressed()if keys[pygame.K_LEFT]:plane_x -= bullet_speed * keys[pygame.K_LEFT] * 1.1 * -1if keys[pygame.K_RIGHT]:plane_x += bullet_speed * keys[pygame.K_RIGHT] * 1.1 * 1if keys[pygame.K_UP]:plane_y -= bullet_speed * keys[pygame.K_UP] * 1.1 * -1 * -1 / bullet_image.get_height() / 3 # 这行代码用于计算飞机的上升速度,根据图片的高度计算。
c语言小飞机源代码

c语言小飞机源代码写一篇1500-2000字的关于C语言小飞机源代码的文章,以中括号内的内容为主题,一步一步回答。
[中括号内的内容:C语言小飞机源代码]前言:C语言作为一种高效且广泛应用的编程语言,在软件开发领域有着极为重要的地位。
而小飞机作为一种常见的娱乐玩具,具有吸引人的外观和操控性。
本文通过编写一个C语言小飞机源代码来展示C 语言的基础语法及其在实践中的应用。
我们将逐步分解这个源代码,并解释每个部分的功能和实现原理。
希望读者通过阅读本文,能够更深入了解C语言,并通过实际编码体验其应用之乐趣。
一、介绍:[这部分介绍小飞机源代码的背景、目的和基本功能。
]我们编写的小飞机源代码旨在实现一个简单的小飞机游戏。
玩家可以通过键盘控制小飞机的飞行,并躲避障碍物。
游戏界面使用字符画绘制,使得整个游戏更加有趣。
二、源代码分析:1. 引用头文件和定义全局变量:cinclude <stdio.h>include <conio.h>int x, y; 飞机的坐标int sx, sy; 障碍物的坐标[这部分主要是包含所需的头文件,并声明全局变量x、y、sx、sy。
]在这个示例中,我们引用了stdio.h和conio.h两个头文件。
stdio.h用于标准输入输出,而conio.h中定义了控制台输入输出的一些函数,比如getch()函数用于读取用户按下的键盘字符。
全局变量x和y分别表示飞机的横纵坐标,而sx和sy表示障碍物的横纵坐标。
通过全局变量的设置,我们可以在代码的不同部分共享这些变量的数值。
2. 定义函数-初始化游戏界面:cvoid InitGame(){x = 0;y = 0;sx = 50;sy = 10;}[这部分是定义了一个名为InitGame()的函数,用于初始化游戏界面。
]在这个函数内部,我们给飞机和障碍物的坐标赋初始值。
将飞机的x和y坐标设为0,将障碍物的sx和sy坐标设为固定值。
[python]小游戏-play_plane
![[python]小游戏-play_plane](https://img.taocdn.com/s3/m/f5ebaa1317fc700abb68a98271fe910ef12daeb2.png)
[python]⼩游戏-play_plane ⽬前只做了第⼀部分:⼀个界⾯,有个飞机,可以左右移动,放⼦弹。
暂⽆计划做第⼆部分。
alien_invasion.pyimport sysimport pygamefrom settings import Settingsfrom ship import Shipimport game_functions as gffrom pygame.sprite import Groupdef run_game():# 初始化游戏并创建⼀个屏幕对象pygame.init()ai_settings = Settings()screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screnn_height))pygame.display.set_caption('Alien Invasion')# 创建⼀艘飞船ship = Ship(ai_settings, screen)# 创建⼀个存储的⼦弹组bullets = Group()# 设置背景⾊bg_color = (230, 230, 230)# 开始游戏的主循环while True:gf.check_events(ai_settings, screen, ship, bullets)ship.update()gf.update_bullets(bullets)gf.update_screen(ai_settings, screen, ship, bullets)run_game() bullet.pyimport pygamefrom pygame.sprite import Spriteclass Bullet(Sprite):def__init__(self, ai_settings, screen, ship):super(Bullet, self).__init__()self.screen = screenself.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)self.rect.centerx = ship.rect.centerxself.rect.top = ship.rect.top# 存储⽤⼩数表⽰的⼦弹位置self.y = float(self.rect.y)self.color = ai_settings.bullet_colorself.speed_factor = ai_settings.bullet_speed_factordef update(self):self.y -= self.speed_factor# 更新⼦弹位置self.rect.y = self.ydef draw_bullet(self):pygame.draw.rect(self.screen, self.color, self.rect) game_functionsimport sysimport pygamefrom bullet import Bulletdef check_events(ai_settings, screen, ship, bullets):# 监听键盘和⿏标的事件for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event, ai_settings, screen, ship, bullets) elif event.type == pygame.KEYUP:check_keyup_events(event, ship)def update_screen(ai_settings, screen, ship, bullets):# 每次循环时都重绘屏幕screen.fill(ai_settings.bg_color)# 在飞船和外星⼈后⾯重绘所有⼦弹for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()# 让最近绘制的屏幕可见pygame.display.flip()def check_keydown_events(event, ai_settings, screen, ship, bullets):if event.key == pygame.K_RIGHT:ship.moving_right = Trueelif event.key == pygame.K_LEFT:ship.moving_left = Trueelif event.key == pygame.K_SPACE:# 创建⼀颗⼦弹,并将其加⼊到编组 bullets 中fire_bullet(ai_settings, screen, ship, bullets)def check_keyup_events(event, ship):if event.key == pygame.K_RIGHT:ship.moving_right = Falseelif event.key == pygame.K_LEFT:ship.moving_left = Falsedef update_bullets(bullets):bullets.update()# 删除已经消失的⼦弹for bullet in bullets.copy():if bullet.rect.bottom <= 0:bullets.remove(bullet)def fire_bullet(ai_settings, screen, ship, bullets):if len(bullets) < ai_settings.bullets_allowed:new_bullet = Bullet(ai_settings, screen, ship)bullets.add(new_bullet) settings.pyclass Settings():def__init__(self):# 屏幕设置self.screen_width = 1200self.screnn_height = 800self.bg_color = (230, 230, 230)self.ship_speed_factor = 1.5# ⼦弹设置self.bullet_speed_factor = 1self.bullet_width = 3self.bullet_height = 15self.bullet_color = 60, 60, 60self.bullets_allowed = 5 ship.pyimport pygameclass Ship():def__init__(self, ai_settings, screen):self.screen = screenself.ai_settings = ai_settings# 加载飞船图像并获取其外接矩形self.image = pygame.image.load('images/ship.bmp')self.rect = self.image.get_rect()self.screen_rect = screen.get_rect()# 将每艘新飞船放在屏幕底部中央self.rect.centerx = self.screen_rect.centerxself.rect.bottom = self.screen_rect.bottom# 在飞船的属性 center 中存储⼩数值self.center = float(self.rect.centerx)# 移动标识self.moving_right = Falseself.moving_left = Falsedef blitme(self):# 屏幕指定位置绘制飞船self.screen.blit(self.image, self.rect)def update(self):if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor elif self.moving_left and self.rect.left > 0:self.center -= self.ai_settings.ship_speed_factor # 更新 rect 对象self.rect.centerx = self.center。
C语言控制台实现打飞机小游戏

C语⾔控制台实现打飞机⼩游戏本⽂实例为⼤家分享了C语⾔实现打飞机⼩游戏的具体代码,供⼤家参考,具体内容如下初学C语⾔总觉得不能做些什么好玩的,这个⼩游戏只需 “⼀点点” (千真万确)C语⾔知识就能完成!总计不到200⾏的⾮空⽩代码(没有强⾏压缩⾏数)操作说明:1.W、S、A、D 控制上、下、左、右⽅向,空格攻击2.每击中⼀架敌机增加1分,界⾯下⽅显⽰实时分数3.撞到敌机后显⽰ game over! 2.5秒(时间可更改)⼦弹连发移动的同时发射⼦弹飞机撞上敌机结束游戏可通过更改相关变量的值来调节敌机飞⾏速度、敌机密度、敌机刷新速度等相⽐与上⼀个极度简陋版,功能基本完善所需C语⾔知识真的不多,感兴趣的C程序员朋友来复刻吧!以下是详细注释的源代码:#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>#define high 25 //画布⾼#define width 60 //画布宽#define border -1 //边界#define blank 0 //空⽩#define plane 1 //飞机#define bullet 2 //⼦弹#define enemy 3 //敌机#define destroy 4 //摧毁标记int canvas[high+2][width+2]; //游戏场景的⾼和宽int pos_h, pos_w; //飞机位置int enemynum; //敌机数量int interval; //同个计次来模拟时间间隔int itv_move; //敌机移动的时间间隔int itv_new; //敌机刷新的时间间隔int score; //分数int IsOver; //判断游戏是否结束void Startup(); //游戏数值初始化void Show(); //游戏界⾯输出void UpdateInput(); //与输⼊⽆关的游戏状态更新void UpdateNormal(); //因输⼊导致的游戏状态更新int main(){Startup(); //初始化while(IsOver){ //游戏循环UpdateInput();UpdateNormal();Show();}printf("\t\tgame over!\n");Sleep(2500); //暂停游戏结束界⾯(毫秒)system("pause");return 0;}void Startup(){ //游戏数值初始化IsOver=1;score=0; //初始化分数for(int i=0;i<high+2;i++){ //初始化画布for(int j=0;j<width+2;j++){if(i==0 || i==high+1 ||j==0 || j==width+1){canvas[i][j]=border;}else canvas[i][j]=blank;}}pos_h=high/2; //初始化飞机竖直坐标pos_w=width/2; //初始化飞机⽔平坐标canvas[pos_h][pos_w]=plane; //初始化飞机位置enemynum=3; //敌机数量srand(time(NULL));interval=4; //初始化时间间隔计数itv_move=5; //初始化敌机移动时间间隔itv_new =40; //初始化敌机刷新时间间隔}void Show(){ //游戏界⾯输出HideCursor(); //隐藏光标gotoxy(1,1); //回调光标、刷新画⾯for(int i=0;i<high+2;i++){for(int j=0;j<width+2;j++){if( canvas[i][j] == plane ){ //当前位置为飞机位置printf("*");}else if( canvas[i][j] == bullet ){ //当前位置为⼦弹位置printf("|");}else if( canvas[i][j] == enemy ){ //当前位置为敌机位置printf("@");}else if( canvas[i][j] == border ){ //当前位置为边界printf("#");}else if( canvas[i][j] == blank ){ //当前位置⽆物,且在边界内 printf(" ");}else if( canvas[i][j] == destroy ){ //当前位置⽆物,且在边界内 printf("x");}}printf("\n");}printf("\n得分:%d",score);}void UpdateInput(){ //与输⼊⽆关的游戏状态更新char key_W=GetKeyState('W'), //监测 W 键是否按下key_S=GetKeyState('S'), //监测 S 键是否按下key_A=GetKeyState('A'), //监测 A 键是否按下key_D=GetKeyState('D'), //监测 D 键是否按下key_attack=GetKeyState(' '); //监测空格键是否按下if(kbhit()){ //当有键按下时if(key_W<0){ //当按下 W 键,上移if(pos_h>1){canvas[pos_h][pos_w]=blank;if(canvas[pos_h-1][pos_w] == enemy){ //下个位置是敌机,撞毁canvas[pos_h-1][pos_w]= destroy;IsOver=0;}else canvas[--pos_h][pos_w]=plane;}}if(key_S<0){ //当按下 S 键,下移if(pos_h<high){canvas[pos_h][pos_w]=blank;if(canvas[pos_h+1][pos_w] == enemy){ //下个位置是敌机,撞毁 canvas[pos_h+1][pos_w]= destroy;IsOver=0;}else canvas[++pos_h][pos_w]=plane;}}if(key_A<0){ //当按下 A 键,左移if(pos_w>1){canvas[pos_h][pos_w]=blank;if(canvas[pos_h][pos_w-1] == enemy){ //下个位置是敌机,撞毁canvas[pos_h][pos_w-1]= destroy;IsOver=0;}else canvas[pos_h][--pos_w]=plane;}}if(key_D<0){ //当按下 D 键,右移if(pos_w<width){canvas[pos_h][pos_w]=blank;if(canvas[pos_h][pos_w+1] == enemy){ //下个位置是敌机,撞毁 canvas[pos_h][pos_w+1]= destroy;IsOver=0;}else canvas[pos_h][++pos_w]=plane;}}if(key_attack<0){ //当按下空格键,发射⼦弹if(pos_h!=1)canvas[pos_h-1][pos_w]=bullet;}}}void UpdateNormal(){ //因输⼊导致的游戏状态更新int temp[high+2][width+2]; //⽤来判断原位置的临时数组for(int i=1;i<=high;i++){for(int j=1;j<=width;j++){temp[i][j]=canvas[i][j];}}for(int i=1;i<=high;i++){ //遍历临时数组,修改画布for(int j=1;j<=width;j++){if(temp[i][j]==enemy && interval%itv_move==0){ //当前位置为敌机 canvas[i][j]=blank;if(temp[i+1][j]==bullet){ //下⾯为⼦弹,敌机被击中canvas[i+1][j]=blank;score++;printf("\a"); //击中⾳效}else if(i<high){canvas[i+1][j]=enemy;}if(i+1==pos_h&&j==pos_w){ //下⾯为飞机,玩家飞机被撞毁canvas[i+1][j]=destroy;IsOver=0;}}if(temp[i][j]==bullet){ //当前位置为⼦弹canvas[i][j]=blank;if(temp[i-1][j]==enemy){ //下个位置是敌机,敌机被击毁canvas[i-1][j]=blank;score++;printf("\a");}else if(i>1){canvas[i-1][j]=bullet;}}}}if(interval%itv_new==0) //刚好到时间间隔for(int i=0;i<enemynum;i++){ //新增敌机群canvas[rand()%2+1][rand()%width+1]=enemy;}if(interval<=100){ //时间间隔计次interval++;}else{ //时间间隔计次清零interval=0;}}void gotoxy(int x,int y){ //回调光标COORD pos;pos.X=x-1;pos.Y=y-1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);}void HideCursor(){ //隐藏光标函数CONSOLE_CURSOR_INFO cursor;cursor.bVisible = FALSE;cursor.dwSize = sizeof(cursor);HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorInfo(handle, &cursor);}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
python打飞机代码

python打飞机代码Python打飞机游戏开发:从零开始,一步一步教你制作一个简单的飞机射击游戏摘要:本文将以Python编程语言为基础,一步一步教你如何制作一个简单的飞机射击游戏。
我们将使用Pygame库来实现游戏的图形界面和交互功能,通过编写游戏的关键代码,如飞机的移动、敌机的生成和碰撞检测等,最终实现一个完整的飞机射击游戏。
第一步:准备工作在开始编写代码之前,我们需要先安装Pygame库。
在命令行中输入以下命令:pip install pygamePygame是专门用于游戏开发的Python库,它提供了丰富的函数和方法,方便我们进行游戏开发。
第二步:创建游戏窗口在创建游戏窗口之前,我们需要先导入Pygame库,并初始化它。
在代码的开头添加以下代码:pythonimport pygame# 初始化Pygame库pygame.init()# 设置游戏窗口大小screen_width = 480screen_height = 600screen = pygame.display.set_mode((screen_width, screen_height)) 第三步:加载游戏图片和音效在游戏中,我们需要使用一些图片和音效来呈现游戏的效果。
在创建游戏窗口的代码后面,我们可以添加以下代码来加载游戏需要的资源:python# 加载背景图片background = pygame.image.load("background.png")# 加载飞机图片player = pygame.image.load("player.png")# 加载敌机图片enemy = pygame.image.load("enemy.png")# 加载爆炸图片和音效explosion_img = pygame.image.load("explosion.png") explosion_sound = pygame.mixer.Sound("explosion.wav")第四步:绘制游戏界面我们使用一个循环来更新游戏界面,并获取玩家的输入。
java飞机游戏源代码

import//借用工具importimportimportimportimportimportimport//引用随机数public class planegames {/*** @param args*/public static void main(String[] args) {Frame window=new Frame();//创建一个窗体window.setSize(240,320);//窗体大小window.setTitle("是男人就坚持20秒");//窗体名字myPanel mp=new myPanel();//创建一个画布window.add(mp);//将画布添加到窗体上window.setVisible(true);//显示窗体new Thread(mp).start();mp.addKeyListener(mp);// TODO Auto-generated method stub}}class myPanel extends Panel implements Runnable,KeyListener{Toolkit tk=Toolkit.getDefaultToolkit();//获得读取数据工具Random r=new Random();boolean alive=true;Image bg=tk.createImage(this.getClass().getResource("bg.png"));//背景Image bulletImg= tk.createImage(this.getClass().getResource("bullet.png")); //子弹//子弹相关数据int nums=30;int[]bx=new int[nums];//子弹的x坐标int[]by=new int[nums];//子弹的y坐标Image planeImg=tk.createImage(this.getClass().getResource("plane.png"));//飞机相关数据int px=113;//飞机的x坐标int py=160;//y坐标boolean[]moveFlag=new boolean[4];//移动方向标志默认都为Falsedouble []cos=new double[nums];double []sin=new double[nums];public void paint (Graphics g){update(g);}public void update(Graphics g){Image tmp=createImage(240,320);//创建一个透明图片Graphics _g=tmp.getGraphics();//取得这个图片_g.drawImage(bg,0,0,this);//最后一个this表示在哪个画布上if(alive){_g.drawImage(planeImg,px,py,px+15,py+15,0,0,15,15,this);}else{_g.drawImage(planeImg,px,py,px+15,py+15,15,0,30,15,this);}for(int i=0;i<nums;i++){_g.drawImage(bulletImg,bx[i],by[i],this);}g.drawImage(tmp,0,0,this);}public void run(){for(int i=0;i<nums;i++){int direct=r.nextInt(4);//0出现在上方1左2下3右if(direct==0){bx[i]=r.nextInt(240);by[i]=0;}if(direct==1){bx[i]=0;by[i]=r.nextInt(320);}if(direct==2){bx[i]=r.nextInt(240);by[i]=320;}if(direct==3){bx[i]=240;by[i]=r.nextInt(320);}int dx=px-bx[i];//子弹与飞机x轴距离int dy=py-by[i];//子弹与飞机y轴距离double dLine=Math.sqrt(dx*dx+dy*dy);cos[i]=dx/dLine;sin[i]=dy/dLine;}while(alive){//死循环一直去重新绘制图片实现动画效果if(moveFlag[0]){//说明up为按下状态py-=5;}if(moveFlag[1]){//说明left为按下状态px-=5;}if(moveFlag[2]){//说明down为按下状态py+=5;}if(moveFlag[3]){//说明right为按下状态px+=5;}if(py<0){//如果飞机从上方出界py=0;}if(px<0){//如果飞机从左方出界px=0;}if(py>265){//如果飞机从下方出界py=265;}if(px>210){//如果飞机从右方出界px=210;}for(int i=0;i<nums;i++){bx[i]=(int)(bx[i]+3*cos[i]);by[i]=(int)(by[i]+3*sin[i]);if(bx[i]+3>px&&px+15>bx[i]//子弹和飞机碰撞&&by[i]+3>py&&py+15>by[i]){alive=false;}if (bx[i]<0||by[i]<0||bx[i]>240||by[i]>320){ int direct=r.nextInt(4);//0出现在上方1左2下3右if(direct==0){bx[i]=r.nextInt(240);by[i]=0;}if(direct==1){bx[i]=0;by[i]=r.nextInt(320);}if(direct==2){bx[i]=r.nextInt(240);by[i]=320;}if(direct==3){bx[i]=240;by[i]=r.nextInt(320);}int dx=px-bx[i];//子弹与飞机x轴距离int dy=py-by[i];//子弹与飞机y轴距离double dLine=Math.sqrt(dx*dx+dy*dy);cos[i]=dx/dLine;sin[i]=dy/dLine;}}repaint(); //重新绘制try{Thread.sleep(40L);//每秒25帧}catch(InterruptedException e){}}}public void keyPressed(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_UP){moveFlag[0]=true;//按下上的时候0元素为true }if(e.getKeyCode()==KeyEvent.VK_LEFT){moveFlag[1]=true;//按下左的时候1元素为true}if(e.getKeyCode()==KeyEvent.VK_DOWN){moveFlag[2]=true;//按下下的时候2元素为true}if(e.getKeyCode()==KeyEvent.VK_RIGHT){moveFlag[3]=true;//按下右的时候3元素为true}}public void keyReleased(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_UP){moveFlag[0]=false;//按下上的时候0元素为true}if(e.getKeyCode()==KeyEvent.VK_LEFT){moveFlag[1]=false;//按下左的时候1元素为true}if(e.getKeyCode()==KeyEvent.VK_DOWN){moveFlag[2]=false;//按下下的时候2元素为true}if(e.getKeyCode()==KeyEvent.VK_RIGHT){moveFlag[3]=false;//按下右的时候3元素为true}}public void keyTyped(KeyEvent e){} }。
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)运⾏程序就可以了!。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
{
menu();
int i=0,j=0;
scr[21][pl]=1;
scr[0][5]=3;
while(1){if(kbhit())switch(getch())//控制左右移动和进入菜单
{case 'a':case 'A':if(pl>0)scr[21][pl]=0,scr[21][--pl]=1;break;
sw=1;
}
}
while(sw);
do
{
sw=0;
printf("\n请选择敌机密度:1.大2.中3.小>> ");
switch(getche())
{
case '0':density=10;
break;
case '1':density=20;
break;case '2':density=30;
break;case '3':density=40;break;
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define N 35
void print(int [][N]);//输出函数
void movebul(int [][N]);//子弹移动函数
void movepla(int [][N]);//敌机移动函数
case 'd':case 'D':if(pl<width-2)scr[21][pl]=0,scr[21][++pl]=1;
break;
case 'w':case 'W':scr[20][pl]=2;break;case 27 :setting();
break;
}
if(++j%density==0)//控制生产敌机的速度
void setting(void);//设置函数
void menu(void);//菜单函数
int scr[22][N]={0},pl=9,width=24,speed=3,density=30,score=0,death=0;//全局变量:界面、我机初始位、界面宽度、敌机速度、敌机密度、得分、死亡
case '3printf("\n错误,请重新选择...\n");
sw=1;
}
}
while(sw);
for(i=0;i<22;i++)
for(j=0;j<45;j++)
scr[i][j]=0;
scr[21][pl=9]=1;
printf("\n按任意键保存...");
getch();
}
void menu(void)
{
printf("说明:按A D控制我机左右飞行,W发射子弹\n设置:请按Esc\n开始游戏:任意键\n) by yan_xu");
if(getch()==27)setting();
}
if(a[i][j]==3)printf("\3"); //输出敌机符号
if(a[i][j]==4)printf("|");
if(i==0&&j==width-1)printf("得分:%d",score);//右上角显示得分
if(i==1&&j==width-1)printf("死亡:%d",death);
int i,j;
for(i=0;i<22;i++){a[i][width-1]=4;
for(j=0;j<width;j++){if(a[i][j]==0)printf(" ");
if(a[i][j]==1)printf("\5");//输出我机的符号
if(a[i][j]==2)printf(".");//子弹
{j=0;srand(time(NULL));
scr[0][rand()%width]=3;
}
if(++i%speed==0)//控制敌机移动速度,相对于子弹移动速度
movepla(scr);
movebul(scr);
print(scr);
if(i==30000)i=0;//以免i越界
}
}
void print(int a[][N]){system("cls");
if(i==2&&j==width-1)printf("设置:Esc");
if(i==3&&j==width-1)printf("Copyright:王攀");
}
printf("\n");
}
}
void movebul(int a[][N]){int i,j;
for(i=0;i<22;i++)
for(j=0;j<width;j++)
{
if(i==0&&a[i][j]==2)a[i][j]=0;if(a[i][j]==2)
{
if(a[i-1][j]==3)score+=10,printf("\7");
a[i][j]=0,a[i-1][j]=2;
}
}
}
void movepla(int a[][N])
{
int i,j;
for(i=21;i>=0;i--)//从最后一行往上是为了避免把敌机直接冲出数组。
default:printf("\n错误,请重新选择...\n");
sw=1;
}
}
while(sw);
do
{
sw=0;
printf("\n敌机的飞行速度:1.快2.中3.慢>> ");
switch(getche())
{
case '1':speed=2;
break;
case '2':speed=3;
break;
{
int sw=0,i,j;
system("cls");
do{sw=0;printf("\n游戏界面的大小:1.大2.小>> ");
switch(getche())
{
case '1':width=34;break;
case '2':width=24;break;
default:printf("\n错误,请重新选择...\n");
for(j=0;j<width;j++)
{
if(i==21&&a[i][j]==3)a[i][j]=0;//底行赋值0以免越界。
if(a[i][j]==3)a[i][j]=0,a[i+1][j]=3;
}
if(a[20][pl]==3&&a[21][pl]==1)death++;
}
void setting(void)