>  기사  >  Java  >  Java를 사용하여 잠수함 게임을 작성하는 방법은 무엇입니까?

Java를 사용하여 잠수함 게임을 작성하는 방법은 무엇입니까?

PHPz
PHPz앞으로
2023-04-22 09:46:17762검색

첫 번째는 메인 메소드에 정의된 창입니다. (이것들은 고정된 형식이므로 어떻게 하는지 모르셔도 괜찮습니다. Ctrl+c+v만 누르시면 기본적으로 데이터만 봐도 이해하실 수 있습니다.)

슈퍼 클래스를 작성하세요. 슈퍼 클래스에는 잠수함, 폭뢰, 지뢰, 전함의 폭과 높이뿐 아니라 등장 시 x, y 좌표와 이동 속도가 필요합니다. 모든 물체의 사진, 모든 물체의 이동 방법 및 충돌

그런 다음 파생 클래스를 작성합니다. 기뢰 잠수함을 격파하면 전함이 생명을 얻고 다른 잠수함을 격파하면 점수를 얻습니다. 따라서 두 가지 인터페이스를 정의해야 합니다. , 하나는 생명을 추가하는 데 사용되고 다른 하나는 포인트를 추가하는 데 사용됩니다

완전한 코드는 다음과 같습니다(사진을 직접 찾을 수 있으며 이미지 클래스와 각 개체의 너비와 높이를 변경하면 됩니다)

게임 월드 월드 클래스

package cn.tedu.sunarine;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//整个游戏世界
public class World extends JPanel {
    public static final int WIDTH = 641;
    public static final int HEIGHT = 479;
 
 
    public static final int RUNNING =0;
    public static final int GAME_OVER=1;
    private int state = RUNNING;
 
    //窗口所显示的对象
    private Battleship ship = new Battleship(); //战舰
    private SeaObject[] submarines = {}; //潜艇(侦察潜艇、鱼雷潜艇、水雷潜艇)
    private Mine[] mines = {}; //水雷
    private Bomb[] bombs = {}; //深水炸弹
 
 
    //随机生成潜艇
    public SeaObject nextSubmarine(){
        Random rand = new Random();
        int type = rand.nextInt(30);
        if(type<10){
            return new ObserveSubmarine();
        }else if(type<15){
            return new TorpedoSubmarine();
        }else{
            return new MineSubmarine();
        }
    }
 
    private int subEnterIndex = 0;
    //潜艇入场
    public void submarineEnterAction(){ //每10毫秒走一次
        subEnterIndex++;
        if(subEnterIndex%40==0){ //每40毫秒
            SeaObject obj = nextSubmarine();
            submarines = Arrays.copyOf(submarines,submarines.length+1);
            submarines[submarines.length-1] = obj;
        }
    }
 
    private int mineEnterIndex = 0;
    //鱼雷,水雷入场
    public void MineEnterAction(){
        mineEnterIndex++;
        if(mineEnterIndex%100==0){
            for (int i=0;i<submarines.length;i++){
                if (submarines[i] instanceof  MineSubmarine){
                    if (submarines[i].isLIVE()) {
                        MineSubmarine ms = (MineSubmarine) submarines[i];
                        Mine obj = ms.shootMine();
                        mines = Arrays.copyOf(mines, mines.length + 1);
                        mines[mines.length - 1] = obj;
                    }
                }
            }
        }
    }
 
    public void gameOver(){
        if (ship.getLife()<=0){
            state = GAME_OVER;
        }
    }
 
    //海洋对象移动
    public void moveAction(){
        for(int i=0;i<submarines.length;i++){
            submarines[i].move();
        }
        for(int i=0;i<mines.length;i++){
            mines[i].move();
        }
        for(int i=0;i<bombs.length;i++){
            bombs[i].move();
        }
    }
 
    //删除越界对象
    public void outOfBoundsAction(){
        for(int i=0;i<submarines.length;i++){
            if(submarines[i].isOutOfBounds()){
                submarines[i] = submarines[submarines.length-1];
                submarines = Arrays.copyOf(submarines,submarines.length-1);
            }
        }
 
        for(int i=0;i<mines.length;i++){
            if(mines[i].isOutOfBounds()){
                mines[i] = mines[mines.length-1];
                mines = Arrays.copyOf(mines,mines.length-1);
            }
        }
 
        for(int i=0;i<bombs.length;i++){
            if(bombs[i].isOutOfBounds()){
                bombs[i] = bombs[bombs.length-1];
                bombs = Arrays.copyOf(bombs,bombs.length-1);
            }
        }
    }
 
    private  int score = 0;
 
    public void BombsBangAction(){
//深水炸弹炸潜艇
        for (int i=0;i<bombs.length;i++){
            Bomb b =bombs[i];
            for (int j=0;j<submarines.length;j++){
                SeaObject s = submarines[j];
                if (b.isLIVE()&& s.isLIVE()&&s.isHit(b)){
                    b.goDead();
                    s.goDead();
                    if (s instanceof EnemyScore){
                        EnemyScore es = (EnemyScore) s;
                        score += es.getScore();
                    }
                    if (s instanceof EnemyLife){
                        EnemyLife ea = (EnemyLife) s;
                        int num = ea.getLife();
                        ship.addLife(num);
                    }
 
                }
            }
        }
    }
 
    public void mineBangAction(){
        for (int i=0;i<mines.length;i++){
            Mine m= mines[i];
            if (m.isLIVE()&& ship.isLIVE()&&m.isHit(ship)){
                m.goDead();
                ship.subtratLife();
            }
        }
    }
 
 
    /** 启动程序的运行 */
    public void action(){
        KeyAdapter k = new KeyAdapter(){
 
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_SPACE){
                    Bomb obj = ship.shoot(); //深水炸弹入场
                    bombs = Arrays.copyOf(bombs,bombs.length+1);
                    bombs[bombs.length-1] = obj;
                }
                if(e.getKeyCode() == KeyEvent.VK_LEFT){
                    ship.moveLeft();
                }
                if(e.getKeyCode() == KeyEvent.VK_RIGHT){
                    ship.moveRight();
                }
            }
        };
        this.addKeyListener(k);
 
        Timer timer = new Timer();
        int interval = 10;
        timer.schedule(new TimerTask() {
            public void run() {
                submarineEnterAction(); //潜艇(侦察、水雷、鱼雷)入场
                MineEnterAction();      //水雷入场
                moveAction();           //海洋对象移动
                BombsBangAction();      //深水炸弹和潜艇碰撞
                mineBangAction();       //水雷和战舰碰撞
                outOfBoundsAction();    //删除越界的对象
                gameOver();
                repaint();
            }
        }, interval, interval);
    }
 
    public void paint (Graphics g ){
        switch (state) {
            case GAME_OVER:
                Images.gameover.paintIcon(null,g,0,0);
                break;
            case RUNNING:
            Images.sea.paintIcon(null, g, 0, 0);
            ship.paintImage(g);
            for (int i = 0; i < submarines.length; i++) {
                submarines[i].paintImage(g);
            }
            for (int i = 0; i < mines.length; i++) {
                mines[i].paintImage(g);
            }
            for (int i = 0; i < bombs.length; i++) {
                bombs[i].paintImage(g);
            }
            g.drawString("SCORE" + score, 200, 50);
            g.drawString("LIFE" + ship.getLife(), 400, 50);
        }
    }
 
 
 
 
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        World world = new World();
        world.setFocusable(true);
        frame.add(world);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH, HEIGHT+19);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        world.action();
    }
}

SeaObject 클래스를 슈퍼 클래스(상위 클래스)로 정의한 후 다른 파생 클래스(하위 클래스)를 작성합니다.

package cn.tedu.sunarine;
 
import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.util.Random;
 
public abstract class SeaObject {
 
    public static final int LIVE = 0;
    public static final int DEAD = 1;
    protected int state=LIVE;
 
    protected int width;
    protected int height;
    protected int x;
    protected int y;
    protected int speed;
 
    //三个潜艇
    public SeaObject(int width, int height) {
        this.width = width;
        this.height = height;
        x =-width;
        Random rand = new Random();
        y = rand.nextInt(497 - height - 150 + 1) + 150;
        speed = rand.nextInt(3) + 1;
    }
//水雷,战舰,炸弹
    public SeaObject(int width, int height, int x, int y, int speed) {
        this.width = width;
        this.height = height;
        this.x = x;
        this.y = y;
        this.speed = speed;
    }
 
    public abstract void move();
 
    public abstract ImageIcon getImage();
 
    public boolean isLIVE(){
        return state ==LIVE;
    }
    public void paintImage(Graphics g){
        if (isLIVE()){
            this.getImage().paintIcon(null,g,this.x,this.y);
        }
    }
    public boolean isOutOfBounds(){
        return x>=World.WIDTH;
    }
    public boolean isHit(SeaObject other){
        int x1 = this.x-other.width;
        int x2 = this.x+this.width;
        int y1 = this.y-other.height;
        int y2 = this.y+this.height;
        int x=other.x;
        int y=other.y;
        return x>=x1 && x<=x2 && y>=y1 && y<=y2;
    }
 
    public void goDead(){
        state =DEAD;
    }
}

파생 클래스에서 슈퍼 클래스를 참조합니다.

어뢰 잠수함 클래스

package cn.tedu.sunarine;
import javax.swing.ImageIcon;
 
//鱼雷潜艇
public class TorpedoSubmarine extends SeaObject implements EnemyScore{
    TorpedoSubmarine(){
        super(64,20);
    }
 
    @Override
    public void move() {
        x+=speed;
    }
    public ImageIcon getImage(){
        return Images.torpedo;
    }
    public boolean isOutOfBounds() {
        return x>=World.WIDTH;
    }
    public int getScore(){
        return 20;
    }
}

잠수함 클래스를 만들었습니다

package cn.tedu.sunarine;
import javax.swing.ImageIcon;
 
//水雷潜艇
public class MineSubmarine extends SeaObject implements EnemyScore{
    MineSubmarine(){
       super(63,19);
    }
 
    @Override
    public void move() {
        x+=speed;
    }
    public ImageIcon getImage(){
        return Images.minesubm;
    }
    public Mine shootMine(){
        int x = this.x+(this.width/2);
        int y =this.y;
        return new Mine(x,y);
    }
    public boolean isOutOfBounds() {
        return x>=World.WIDTH;
    }
    public int getLife(){
        return 1;
    }
}

정찰잠수함급

package cn.tedu.sunarine;
import javax.swing.ImageIcon;
 
//侦察潜艇
public class ObserveSubmarine extends SeaObject implements EnemyScore{
    ObserveSubmarine(){
        super(63,19);
    }
 
    @Override
    public void move() {
        x+=speed;
    }
    public ImageIcon getImage(){
        return Images.observesubm;
    }
    public boolean isOutOfBounds() {
        return x>=World.WIDTH;
    }
    public int getScore(){
        return 10;
    }
}

어뢰급

package cn.tedu.sunarine;
//鱼雷
import javax.swing.ImageIcon;
public class Mine extends SeaObject{
        Mine(int x,int y){
            super(11,11,x,y,1);
        }
 
    @Override
    public void move() {
        y-=speed;
    }
 
    public ImageIcon getImage(){
            return Images.mine;
    }
    public boolean isOutOfBounds(){
            return y<=150-(height/2);
    }
}

심폭탄급

package cn.tedu.sunarine;
//深水炸弹
import javax.swing.ImageIcon;
public class Bomb extends SeaObject{
    Bomb(int x,int y){
        super(9,12,x,y,3);
    }
 
    @Override
    public void move() {
        y+=speed;
    }
    public ImageIcon getImage(){
        return Images.bomb;
    }
    public boolean isOutOfBounds(){
        return y>=World.HEIGHT;
    }
}

전함급

package cn.tedu.sunarine;
 
import javax.swing.*;
 
//战舰
public class Battleship extends SeaObject{
    int life;
    Battleship(){
       super(66,26,270,124,20);
       life=1;
    }
 
    @Override
    public void move() {
        System.out.println("战舰移动");
    }
    public ImageIcon getImage(){
        return Images.battleship;
    }
    public Bomb shoot(){
        return new Bomb(this.x,this.y+height);
    }
    //限制移动范围
    public void moveLeft(){
        x-=speed;
        x=Math.max(0,x);
    }
    public void moveRight(){
        x+=speed;
        x=Math.min(x,World.WIDTH-this.width);
    }
    public void addLife(int num){
        life+=num;
    }
    public int getLife(){
        return life;
    }
    public void subtratLife(){
        life--;
    }
}

생활 인터페이스 추가

package cn.tedu.sunarine;
 
public interface EnemyLife {
    public int getLife();
}

포인트 인터페이스 추가

package cn.tedu.sunarine;
 
public interface EnemyScore {
    public int getScore();
}

마지막으로, 이미지 클래스(사진에 따라 변경 가능)

package cn.tedu.sunarine;
import javax.swing.*;
public class Images {
    public static ImageIcon battleship;
    public static ImageIcon observesubm;
    public static ImageIcon mine;
    public static ImageIcon bomb;
    public static ImageIcon sea;
    public static ImageIcon torpedo;
    public static ImageIcon minesubm;
    public static ImageIcon gameover;
    static {
        battleship = new ImageIcon("./img/battleship.png");
        bomb = new ImageIcon("./img/bomb.png");
        gameover = new ImageIcon("./img/gameover.png");
        mine = new ImageIcon("./img/mine.png");
        minesubm = new ImageIcon("./img/minesubm.png");
        observesubm = new ImageIcon("./img/obsersubm.png");
        sea = new ImageIcon("./img/sea.png");
        torpedo = new ImageIcon("./img/torpesubm.png");
    }
 
    public static void main(String[] args) {
        System.out.println(battleship.getImageLoadStatus());
        System.out.println(observesubm.getImageLoadStatus());
        System.out.println(mine.getImageLoadStatus());
        System.out.println(battleship.getImageLoadStatus());
        System.out.println(bomb.getImageLoadStatus());
        System.out.println(gameover.getImageLoadStatus());
        System.out.println(minesubm.getImageLoadStatus());
        System.out.println(sea.getImageLoadStatus());
    }
}

위 내용은 Java를 사용하여 잠수함 게임을 작성하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제