Java簡單雷電遊戲程式碼
完整程式碼!!!
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Mhh {
public static void main(String args[]){
Frame w=new Frame();
w.setSize(430,500);
MyPanel9 mp=new MyPanel9();
w.add(mp);
w.addKeyListener(mp);
mp.addKeyListener(mp);
Thread t=new Thread(mp);
t.start();
w.show();
}
}
class MyPanel9 extends JPanel implements Runnable,KeyListener { int count=1000;//發射子彈的數目
int flag1=0;//標誌flag為1時發射子彈
int m=0; //記錄已發射子彈的數目
int max=2000;//記錄得分
int x=280;//下面飛機的座標
int y=420;
int x1[]=new int[15];//上面飛機的座標
int[] y1=new int[15];
int x2[]=new int[count];//發射子彈的座標
int[] y2=new int[count];
public MyPanel9(){//上面飛機隨即分佈
for(int i=0;i<15;i++){
x1[i]=(int)(Math.random()*400);
y1[i]=(int)(Math.random()*500);
}
}
public void paint(Graphics g){
super.paint(g); Image img2=new ImageIcon("1.jpg").getImage(); g.drawImage(img2,0,0,430,500,null); Image img1=new ImageIcon("2.jpg").getImage();//畫下面的飛機 g.drawImage(img1,x,y,30,40,null); if(max>0){ Font f=new Font("",Font.BOLD,16); g.setFont(f); g.setColor(Color.RED); g.drawString("成績是:"+max,20,20); for(int i=0;i<10;i++){ Image img3=new ImageIcon("4.jpg").getImage();//畫上面的飛機 g.drawImage(img3,x1[i],y1[i],30,40,null); } if(m==count) m=0; if(flag1==1){//畫新子彈的位置 x2[m]=x; y2[m]=y; m++; flag1=0; } for(int i=0;i<m;i++){ g.setColor(Color.RED); g.fillOval(x2[i]+5,y2[i],15,15); } } else{ Font ff=new Font("",Font.BOLD,36); g.setFont(ff); g.setColor(Color.RED); g.drawString("GAME OVER",100,200); } } public void run(){ while(true){ for(int i=0;i<10;i++){//飛機隨機下落 y1[i]++; if(y1[i]>500){ y1[i]=0; x1[i]=(int)(Math.random()*400); max-=50; }
}
for(int j=0;j<m;j++){//子彈移動的過程
y2[j]-=10;
}
for(int i=0;i<m;i++){ //子彈擊中飛機的過程
if(y2[i]>0){
for(int j=0;j<10;j++){
if(0<=(y2[i]-y1[j])&&(y2[i]-y1[j])<=10){
if(-15<=(x2[i]-x1[j])&&(x2[i]-x1[j])<=10){
max+=10;
y2[i]=-1;
x1[j]=(int)(Math.random()*400); y1[j]=0;
}
}
}
}
}
if(max<0){
return;
}
try{
Thread.sleep(35);
}catch(Exception e){}
repaint();
}
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {//控制下面飛機移動
if(e.getKeyCode()==KeyEvent.VK_LEFT){
x-=10;
if(x<0){
x=0;
}
}
if(e.getKeyCode()==KeyEvent.VK_UP){
y-=10;
if(y<0){
y=0;
}
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){ x+=10;
if(x>400){
x=400;
}
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){ y+=10;
if(y>420){
y=420;
}
}
repaint();
if(e.getKeyCode()==KeyEvent.VK_SPACE){ flag1=1;
}
}
public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub
}
}
java免費學習資料直播公開課群 175161984