haslflafjl 2022-05-27 14:45 采纳率: 80%
浏览 124
已结题

java贪吃蛇程序的问题

?未解决:
全部代码在下,如何实现在gameover时候(running=false)按R键可以重开游戏


-----------------------------------
//主程序
public class Main extends GamePanel{

    public static void main(String[] args) {
        new GameFrame();
    }

}
-----------------------------------
//在新的GameFrame中创建GamePanel 
import javax.swing.JFrame;
public class GameFrame extends JFrame{
    GameFrame(){
        
        this.add(new GamePanel());
        this.setTitle("Snake Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.pack();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
    }
}
-----------------------------------
//图像绘制,游戏操作代码
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

public class GamePanel extends JPanel implements ActionListener{

    static final int SCREEN_WIDTH=600;
    static final int SCREEN_HEIGHT=600;
    static final int UNIT_SIZE=25;
    static int GAMA_GROUND=(SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
    static final int DELAY=140;
    final int x[]=new int[GAMA_GROUND];
    final int y[]=new int [GAMA_GROUND];
    int snake=5;
    int applesEaten;
    int appleX;
    int appleY;
    char direction='R';
    public boolean running=false;
    Timer timer;
    Random random;
    
    GamePanel(){
        this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
        this.setFocusable(true);
        this.addKeyListener(new KAdapter());
        this.setBackground(Color.black);
        random=new Random();
        gameStart();
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        draw(g);
    }
    
    public void draw(Graphics g) {
        if(running) {
            //Draw apple
            g.setColor(Color.white);
            g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
            
            //Draw Snake
            for(int i=0;i<snake;i++) {
                //Head of Snake
                if(i==0) {
                    g.setColor(Color.white);
                    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
                }
                //Body of Snake
                else {
                    g.setColor(Color.gray);
                    g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
                }
            }
        }
        else {
            gameEnd(g);
        }
    }
    
    public void gameStart() {
        running=true;
        createApple();
        timer=new Timer(DELAY,this);
        timer.start();
    }
    
    public void createApple() {
        //Set apple random location
        appleX=random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
        appleY=random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
    }
    
    public void checkApple() {
        //Make apple Edible
        if((x[0]==appleX)&&(y[0]==appleY)){
            snake++;
            applesEaten++;
            createApple();
        }
    }
    
    public void move() {
     //借助char变量“direction”进行方向判断和移动
        for(int i=snake;i>0;i--) {
            x[i]=x[i-1];
            y[i]=y[i-1];
        }
        switch(direction) {
        case 'U':
            y[0]=y[0]-UNIT_SIZE;
            break;
        case 'D':
            y[0]=y[0]+UNIT_SIZE;
            break;
        case 'L':
            x[0]=x[0]-UNIT_SIZE;
            break;
        case 'R':
            x[0]=x[0]+UNIT_SIZE;
            break;
        }
    }
    
    public void checkCollision() {
        for(int i=snake;i>0;i--) {
            //Game end when head touching body
            if((x[0]==x[i])&&(y[0]==y[i])){
                running=false;
            }
            //Game end when head spanned the game field
            if((x[0]<0)||(x[0]>SCREEN_WIDTH)||(y[0]<0)||(y[0]>SCREEN_HEIGHT)) {
                running=false;
            }
        }
    }
    
    private void gameEnd(Graphics g) {
        
        this.setBackground(Color.gray);
        g.setColor(Color.black);
        //"Greedy Snake"
        g.setFont(new Font("Impact",Font.BOLD,30));
        g.drawString("Greedy Snake"+applesEaten,SCREEN_WIDTH/3, g.getFont().getSize());
        //"Score - "
        g.setFont(new Font(null,Font.BOLD,25));
        g.drawString("Score - "+applesEaten,SCREEN_WIDTH/6, 100);

        g.setFont(new Font(null,Font.ROMAN_BASELINE,15));
        g.drawString("press 'R' to restart ", SCREEN_WIDTH/6, 170);
        g.drawString("press 'ESC' to quit ", SCREEN_WIDTH/6,195);
    }
    

    @Override
    public void actionPerformed(ActionEvent e) {
        if(running) {move();checkApple();checkCollision();}
        repaint();
    }
    
    public class KAdapter extends KeyAdapter{
        @Override
        public void keyPressed(KeyEvent e) {
            switch(e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    if(direction!='R') {
                        direction='L';
                    }
                    break;
                case KeyEvent.VK_RIGHT:
                    if(direction!='L') {
                        direction='R';
                    }
                    break;
                case KeyEvent.VK_UP:
                    if(direction!='D') {
                        direction='U';
                    }
                    break;
                case KeyEvent.VK_DOWN:
                    if(direction!='U') {
                        direction='D';
                    }
                    break;
                case KeyEvent.VK_R:
                    if(!running) {
                              //需要解决的地方.实现按R键重开游戏
                    }
                case KeyEvent.VK_ESCAPE:
                    if(!running) {
                        System.exit(0);
                    }
            }
        }
    }
    
}
  • 写回答

2条回答 默认 最新

  • 不会写代码的猴子 Android领域优质创作者 2022-05-27 15:35
    关注
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.Random;
     
    import javax.swing.JPanel;
    import javax.swing.Timer;
     
    public class GamePanel extends JPanel implements ActionListener{
     
        static final int SCREEN_WIDTH=600;
        static final int SCREEN_HEIGHT=600;
        static final int UNIT_SIZE=25;
        static int GAMA_GROUND=(SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
        static final int DELAY=140;
        int x[]=new int[GAMA_GROUND];
        int y[]=new int [GAMA_GROUND];
        int snake=5;
        int applesEaten;
        int appleX;
        int appleY;
        char direction='R';
        public boolean running=false;
        Timer timer;
        Random random;
        
        GamePanel(){
            init();
        }
        
        private void init(){
            x =new int[GAMA_GROUND];
            y =new int [GAMA_GROUND];
            snake=5;
            applesEaten = 0;
            appleX = 0;
            appleY = 0;
            direction='R';
            running=false;
            this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
            this.setFocusable(true);
            this.addKeyListener(new KAdapter());
            this.setBackground(Color.black);
            random=new Random();
            gameStart();
        }
        
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            draw(g);
        }
        
        public void draw(Graphics g) {
            if(running) {
                //Draw apple
                g.setColor(Color.white);
                g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
                
                //Draw Snake
                for(int i=0;i<snake;i++) {
                    //Head of Snake
                    if(i==0) {
                        g.setColor(Color.white);
                        g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
                    }
                    //Body of Snake
                    else {
                        g.setColor(Color.gray);
                        g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
                    }
                }
            }
            else {
                gameEnd(g);
            }
        }
        
        public void gameStart() {
            running=true;
            createApple();
            timer=new Timer(DELAY,this);
            timer.start();
        }
        
        public void createApple() {
            //Set apple random location
            appleX=random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
            appleY=random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
        }
        
        public void checkApple() {
            //Make apple Edible
            if((x[0]==appleX)&&(y[0]==appleY)){
                snake++;
                applesEaten++;
                createApple();
            }
        }
        
        public void move() {
         //借助char变量“direction”进行方向判断和移动
            for(int i=snake;i>0;i--) {
                x[i]=x[i-1];
                y[i]=y[i-1];
            }
            switch(direction) {
            case 'U':
                y[0]=y[0]-UNIT_SIZE;
                break;
            case 'D':
                y[0]=y[0]+UNIT_SIZE;
                break;
            case 'L':
                x[0]=x[0]-UNIT_SIZE;
                break;
            case 'R':
                x[0]=x[0]+UNIT_SIZE;
                break;
            }
        }
        
        public void checkCollision() {
            for(int i=snake;i>0;i--) {
                //Game end when head touching body
                if((x[0]==x[i])&&(y[0]==y[i])){
                    running=false;
                }
                //Game end when head spanned the game field
                if((x[0]<0)||(x[0]>SCREEN_WIDTH)||(y[0]<0)||(y[0]>SCREEN_HEIGHT)) {
                    running=false;
                }
            }
        }
        
        private void gameEnd(Graphics g) {
            this.setBackground(Color.gray);
            g.setColor(Color.black);
            //"Greedy Snake"
            g.setFont(new Font("Impact",Font.BOLD,30));
            g.drawString("Greedy Snake"+applesEaten,SCREEN_WIDTH/3, g.getFont().getSize());
            //"Score - "
            g.setFont(new Font(null,Font.BOLD,25));
            g.drawString("Score - "+applesEaten,SCREEN_WIDTH/6, 100);
     
            g.setFont(new Font(null,Font.ROMAN_BASELINE,15));
            g.drawString("press 'R' to restart ", SCREEN_WIDTH/6, 170);
            g.drawString("press 'ESC' to quit ", SCREEN_WIDTH/6,195);
            if(timer != null) {
                timer.stop();
                timer = null;
            }
        }
        
     
        @Override
        public void actionPerformed(ActionEvent e) {
            if(running) {
                move();
                checkApple();
                checkCollision();
            }
            repaint();
        }
        
        public class KAdapter extends KeyAdapter{
            @Override
            public void keyPressed(KeyEvent e) {
                switch(e.getKeyCode()) {
                    case KeyEvent.VK_LEFT:
                        if(direction!='R') {
                            direction='L';
                        }
                        break;
                    case KeyEvent.VK_RIGHT:
                        if(direction!='L') {
                            direction='R';
                        }
                        break;
                    case KeyEvent.VK_UP:
                        if(direction!='D') {
                            direction='U';
                        }
                        break;
                    case KeyEvent.VK_DOWN:
                        if(direction!='U') {
                            direction='D';
                        }
                        break;
                    case KeyEvent.VK_R:
                        if(!running) {
                            init();
                        }
                    case KeyEvent.VK_ESCAPE:
                        if(!running) {
                            System.exit(0);
                        }
                }
            }
        }
        
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月4日
  • 已采纳回答 5月27日
  • 创建了问题 5月27日

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题