자바 간단 한 뱀 먹 기 게임 실현

9671 단어 자바탐식 사
본 논문 의 사례 는 자바 가 간단 한 뱀 잡 아 먹 기 게임 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
1.프로그램 구성
프로그램 구성 도:

2.프로 그래 밍 아이디어
2.1 데이터 클래스
역할:statics 폴 더 를 연결 하여 정적 자원 패키지 의 그림 을 아이콘 으로 바 꾸 어 패 널 에 쉽게 그립 니 다.
구현:class.getResource(String path)방법 을 사용 합 니 다.
코드 는 다음 과 같 습 니 다:

package com.snake;
import javax.swing.*;
import java.net.URL;
public class Data {
    //     
    public static URL upUrl = Data.class.getResource("/statics/up.png");
    public static ImageIcon up = new ImageIcon(upUrl);
    public static URL downUrl = Data.class.getResource("/statics/down.png");
    public static ImageIcon down = new ImageIcon(downUrl);
    public static URL leftUrl = Data.class.getResource("/statics/left.png");
    public static ImageIcon left = new ImageIcon(leftUrl);
    public static URL rightUrl = Data.class.getResource("/statics/right.png");
    public static ImageIcon right = new ImageIcon(rightUrl);
    //     
    public static URL bodyUrl = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyUrl);
    //  
    public static URL foodUrl = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodUrl);
}
2.2 StartGame 클래스
역할:게임 창 을 만 들 고 창 에 게임 패 널 을 추가 합 니 다.
구현:JFrame 클래스 를 사용 하여 게임 창 을 만 들 고 add()방법 으로 GamePanel 클래스 의 실례 화 대상 을 추가 합 니 다.
코드 는 다음 과 같 습 니 다:

package com.snake;
import javax.swing.*;
import java.awt.*;
public class StartGame {
    public static void main(String[] args){
        //      
        JFrame frame = new JFrame("Java-      ");//  
        frame.setSize(900,720);//    
        frame.setLocationRelativeTo(null);//        
        frame.setResizable(false);//      
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//        
        frame.add(new GamePanel());//      
        frame.setVisible(true);//      
    }
}
2.3 GamePanel 클래스
역할:게임 의 동적 페이지 를 실현 합 니 다.
실현:
(1)init()방법:작은 뱀 위 치 를 초기 화 합 니 다.
(2)eat()방법:무 작위 씨앗 으로 무 작위 음식의 위 치 를 판정 하고 음식의 위 치 는 작은 뱀 위치 와 겹 치지 않 는 다.
(3)JPanel 클래스 를 계승 하여 paintComponent(Graphics g)방법 을 다시 작성 하고 방법 에 제목 표시 줄,작은 뱀의 위치(direction 작은 뱀의 머리 방향 변수 에 따라 작은 뱀의 머리 를 그립 니 다),작은 뱀의 몸,포인트 표시 줄,게임 알림 항목 과 실패 판단 항목 을 그립 니 다.
(4)KeyListener 인터페이스 에 있 는 keypressed(KeyEvent e)방법 을 실현 하고 키보드 입력 을 가 져 오 며 키보드 입력 에 따라 게임 상태 나 뱀 머리 방향 direction 변 수 를 변경 합 니 다.
(5)ActionListener 인터페이스 에 있 는 actionPerformed(ActionEvent e)방법 을 실현 하고 게임 상태 와 direction 변수 에 따라 뱀 이동 조작(직접 되 돌리 기 사용 하지 않 음)을 하여 음식 판정 과 사망 판정 을 실시한다.타이머 타 이 머 를 사용 하여 게임 의 동 태 를 변화 시 키 고 repaint()방법 으로 실시 간 으로 인터페이스 를 업데이트 합 니 다.
코드 는 다음 과 같 습 니 다:

package com.snake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

public class GamePanel extends JPanel implements KeyListener, ActionListener {
    int[] snakeX = new int[500];//      
    int[] snakeY = new int[500];//      
    int foodX;//     
    int foodY;//      
    int length;//      
    String  direction;//      
    int score;//  
    Random r = new Random();
    Timer timer = new Timer(100,this);
    boolean isStart;
    boolean isFail;
    //    
    public GamePanel(){
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }
    private void init(){
        length=3;
        snakeX[0]=100;snakeY[0]=100;
        snakeX[1]=75;snakeY[1]=100;
        snakeX[2]=50;snakeY[2]=100;
        direction = "R";
        eat(foodX,foodY);
        isStart = false;
        isFail = false;
        score = 0;

    }
    private void eat(int x,int y){
        x= 25 + 25*r.nextInt(34);
        y= 75 + 25*r.nextInt(24);
        for (int i = 0; i < length; i++) {
            if(snakeX[i]==x&&snakeY[i]==y){
                x = 25 + 25*r.nextInt(34);
                y = 75 + 25*r.nextInt(24);
            }
        }
        foodX = x;foodY = y;
    }
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.white);//        
        //   
        g.setColor(Color.GREEN);
        g.setFont(new Font("  ",Font.BOLD,50));
        g.drawString("     ",300,60);
        //      
        g.setColor(Color.GRAY);
        g.fillRect(25,75,850,600);
        //      
        if(direction=="R"){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="L"){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(direction=="U"){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="D"){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //   
        for (int i = 1; i < length ; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }
        //   
        Data.food.paintIcon(this,g,foodX,foodY);
        //     
        g.setColor(Color.BLACK);
        g.setFont(new Font("  ",Font.BOLD,20));
        g.drawString("  :"+length,730,30);
        g.drawString("  :"+score,730,60);
        //      
        if(isStart==false){
            g.setColor(Color.BLACK);
            g.setFont(new Font("  ",Font.BOLD,40));
            g.drawString("        ",300,300);
        }
        //    
        if(isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("  ",Font.BOLD,40));
            g.drawString("    ,        ",300,300);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//       
        //    
        if(keyCode==KeyEvent.VK_SPACE){
            if(isFail){
                isFail = false;
                init();
            }
            else{
                isStart = !isStart;
            }
            repaint();
        }
        //    
        if(keyCode==KeyEvent.VK_LEFT&&direction!="R"){
            direction = "L";
        }
        else if(keyCode==KeyEvent.VK_RIGHT&&direction!="L"){
            direction = "R";
        }
        else if(keyCode==KeyEvent.VK_UP&&direction!="D"){
            direction = "U";
        }
        else if(keyCode==KeyEvent.VK_DOWN&&direction!="U"){
            direction = "D";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
    @Override
    public void keyTyped(KeyEvent e) {
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        //      
        if(isStart&&!isFail){
            //    
            for (int i = length-1; i > 0 ; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }
            //    
            if(direction=="R"){
                snakeX[0] += 25;
                if(snakeX[0]>850){
                    snakeX[0] = 25;
                }
            }
            else  if(direction=="L"){
                snakeX[0] -= 25;
                if(snakeX[0]<25){
                    snakeX[0] = 850;
                }
            }
            else  if(direction=="U"){
                snakeY[0] -= 25;
                if(snakeY[0]<75){
                    snakeY[0] = 650;
                }
            }
            else  if(direction=="D"){
                snakeY[0] += 25;
                if(snakeY[0]>650){
                    snakeY[0] = 75;
                }
            }
            //   
            if(snakeX[0]==foodX&&snakeY[0]==foodY){
                length++;
                score += 10;
                eat(foodX,foodY);
            }
            //    
            for (int i = 1; i < length; i++) {
                if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                    isFail=true;
                }
            }
            repaint();
        }
        timer.start();
    }
}
3.게임 전시

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기