我的第一个Java小游戏(贪吃蛇)的编写

package com.oracle.Game;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class SnakeGame extends KeyAdapter implements Runnable {   
    private boolean start=false;
    private JFrame frame;
    private Thread timerThread;
    //-------------变量定义Start-------------
    int[] SnakeXs=new int[900];
    int[] SnakeYs=new int[900];
    //定义初始蛇的长度
    int len=6;
    //定义初始方向
    int diraction=4;
    //定义食物的X,Y坐标
    int a;
    int b;
    //定义一个分数
    int score;
    //定义一个变量记录吃了多少个
    int count;
    //是否Game Over
    boolean IsGameOver = false;
    //是否加速
    int time;
    boolean BiteWall ;
    //-------------变量定义End-------------
    
    
    /**
     * 构造方法,用于构造及初始化所需要的其它对象
     */
    public SnakeGame(){  
        //-------------构造&初始对象Start-------------
        for(int i=0;i<len;i++){
            SnakeXs[i]=(len-1-i)*20;SnakeYs[i]=0;
        }
        //初始化食物坐标
        a=100;
        b=100;
        //初始化分数
        score=0;
        //初始化时间
        time=400;
        //-------------构造&初始对象End-------------
        frame = new JFrame();
        frame.getContentPane().add(new Screen());
        frame.addKeyListener(this);   
        
        //-------------窗口大小设置  frame.setSize(宽, 高);
        frame.setSize(600+5*2+200, 600+25+5*2);
        
        frame.setVisible(true);
        frame.repaint();
    }


    /**
     * 键盘事件响应
     * @param evt
     *             按键事件
     */
    public void keyPressed(KeyEvent evt){
        switch(evt.getKeyCode()){    
            case KeyEvent.VK_ENTER:
                if(!start){
                    timerThread = new Thread(this);
                    timerThread.start();
                    start = true;
                }
                break;
            case KeyEvent.VK_ESCAPE:
                start = false;
                System.exit(1);
                break;
            case KeyEvent.VK_LEFT:
                //-------------按左方向键的事件响应Start-------------
                if(diraction==1||diraction==2)
                    {
                    diraction=3;
                    }
                //-------------按左方向键的事件响应End-------------
                break;
            case KeyEvent.VK_RIGHT:
                //-------------按右方向键的事件响应Start-------------
                if(diraction==1||diraction==2)
                    {
                    diraction=4;
                    }
                //-------------按右方向键的事件响应End-------------
                break;
            case KeyEvent.VK_DOWN:
                //-------------按下方向键的事件响应Start-------------
                if(diraction==3||diraction==4)
                   {
                    diraction=2;
                   }
                //-------------按下方向键的事件响应End-------------
                break;
            case KeyEvent.VK_UP:
                //-------------按上方向键的事件响应Start-------------
                if(diraction==3||diraction==4)
                   {
                    diraction=1;
                   }
                //-------------按上方向键的事件响应End-------------
                break;    
            case KeyEvent.VK_R:
                BiteWall=!BiteWall;
                break;
        }

        frame.repaint();
    }

    /**
     * 线程方法主体,主要用于在主线程展示窗体的同时在窗体中同时做其它任务
     */
    public void run(){
        while(true){
            try{ 
                //-------定时时间间隔  Thread.sleep(毫秒);-------
                Thread.sleep(time);
            }catch (InterruptedException e){  
                e.printStackTrace();
            }
            
            if(start==false)
                return;
            //-------------定时时间间隔事件任务Start-------------
            
            
            //-------------定时时间间隔事件任务End-------------
            frame.repaint();
        }
    }

    class Screen extends JComponent{   
        private static final long serialVersionUID = 1155019838145337862L;

        public void paint(Graphics g){
            Graphics2D g2d = (Graphics2D)g;
            //-------------画图处理Start-------------
//            g2d.drawOval(0, 0, 100, 100);
//            g2d.fillOval(100, 100, 200, 100);
//            g2d.setColor(Color.BLUE);
            
    //        g2d.drawString("今天是2018年1月4号", 0, 10);
            
            //画出背景板
            g2d.setColor(Color.orange);
            g2d.fillRect(0, 0, 800, 600);
            g2d.setColor(Color.black);
            g2d.fillRect(0, 0, 600, 600);
            
            //画出背景方格
        
            for(int i=0;i<30;i++){
                for(int j=0;j<30;j++){
            
                    g2d.setColor(Color.white);
                    g2d.drawRect(i*20,j*20 , 20,20);
                    
                  }
                }
               //画出初始位置的蛇身体
            
            for(int i=0;i<len;i++){
                 g2d.setColor(Color.green);
                g2d.fillRect(SnakeXs[i]+1,SnakeYs[i]+1,20-2,20-2);
            }
            
             //画出第一个食物的点
            
             g2d.setColor(Color.green);
             g2d.fillRect(a+1,b+1, 20-2, 20-2);
            if(SnakeXs[0]==a&&SnakeYs[0]==b){
                count++;
                len++;    //吃到食物身体变长一节
                score+=10;    //吃到食物分数增加10分
               
                //创造一个新的食物
                 a=(int)(Math.random()*30)*20; b=(int)(Math.random()*30)*20;
                 g2d.setColor(Color.green);
                g2d.fillRect(a+1,b+1, 20-2, 20-2);
                
            } 
            //判断是否撞墙停止游戏
            if(BiteWall==true){
                if(SnakeXs[0]<0){
                    SnakeXs[0] = 580;
                }else if(SnakeXs[0]>580){
                    SnakeXs[0] = 0;
                }
                if(SnakeYs[0]<0){
                    SnakeYs[0] = 580;
                }else if(SnakeYs[0]>580){
                    SnakeYs[0] = 0;
                }
            }else{
                //如果撞墙了则显示GameOver
                if(SnakeXs[0]<0 || SnakeXs[0]>580
                        ||SnakeYs[0]<0 || SnakeYs[0]>580){
                    IsGameOver = true;
                }
            }
            for(int i=1;i<len;i++){
                if(SnakeXs[0]==SnakeXs[i]&&SnakeYs[0]==SnakeYs[i]){
                    IsGameOver=true;
                    break;
                }
            }
            if(IsGameOver){
                g2d.setFont(new Font("宋体",Font.BOLD,80));
                g2d.setColor(Color.orange);
                g2d.drawString("Game Over!!", 80, 250);
                start=false;
            }
            
                //显示出分数
                g2d.setFont(new Font("宋体",Font.BOLD,20));
                g2d.setColor(Color.red);
                g2d.drawString("分数:"+score, 650, 200);
                g2d.drawString("吃了:"+count+"个", 650, 300);
                g2d.setColor(Color.blue);
                g2d.drawString("巨无霸恐怖贪吃蛇", 620, 100);
                //判断分数超过一定值之后加速
                switch(score/100){
                case 1:
                    time=300;
                    break;
                case 2:
                    time=200;
                    break;
                case 3:
                    time=100;
                    break;
                case 4:
                    time=50;
                    break;
                }
                
                //蛇身的移动
            for(int i=len-1;i>0;i--){
                SnakeXs[i]=SnakeXs[i-1];SnakeYs[i]=SnakeYs[i-1];
            }
            
                //蛇头的移动
            switch(diraction){
            case 1:
                SnakeYs[0]=SnakeYs[0]-20;
                break;
            case 2:
                SnakeYs[0]=SnakeYs[0]+20;
                break;
            case 3:
                SnakeXs[0]=SnakeXs[0]-20;
                break;
            case 4:
                SnakeXs[0]=SnakeXs[0]+20;
                break;
            
            }
            
            //-------------画图处理End-------------
        }
    }

    /**
     * 主方法用于启动窗体
     * @param args
     */
    public static void main(String[] args){
        //构造窗体对象用于展示
        new SnakeGame();
    }
} 

通过控制按键控制“蛇”的移动方向,同时利用 Math.random() 方法创建一个随机出生的“食物”,“吃到食物”后让“蛇”的身长增加并且记录“吃到一次食物”后的分数,当分数到达某一等级之后改变“蛇”的移动速度来增加游戏难度。另外还可以单独为“食物”,“蛇”创建单独的对象来实现更加方便的调用修改.具体结果界面如下:

转载于:https://www.cnblogs.com/FlashBear/p/FlashBear.html

import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class snate extends JFrame implements KeyListener,Runnable { JLabel j; Canvas j1; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; //SnakeModel se=null; //222222 // boolean[][] matrix; LinkedList nodeArray = new LinkedList();//表 Node food;//节点 int maxX; int maxY; int direction = 2; boolean running = false; int timeInterval = 200; double speedChangeRate = 0.75; boolean paused = false; int score = 0; int countMove = 0; // UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; snate() { super(); //setSize(500,400); Container c=getContentPane(); j=new JLabel("Score:"); c.add(j,BorderLayout.NORTH); j1=new Canvas(); j1.setSize(canvasWidth+1,canvasHeight+1); j1.addKeyListener(this); c.add(j1,BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JLabel j2; j2 = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); p1.add(j2, BorderLayout.NORTH); j2 = new JLabel("ENTER or R or S for start;", JLabel.CENTER); p1.add(j2, BorderLayout.CENTER); j2 = new JLabel("SPACE or P for pause",JLabel.CENTER); p1.add(j2, BorderLayout.SOUTH); c.add(p1,BorderLayout.SOUTH); addKeyListener(this); pack(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // begin(); // //2222222 // this.gs = gs; this.maxX = maxX; this.maxY = maxY; // initial matirx matrix = new boolean[maxX][]; for(int i=0; i<maxX; ++i){ matrix[i] = new boolean[maxY]; Arrays.fill(matrix[i],false); } // initial the snake int initArrayLength = maxX > 20 ? 10 : maxX/2; for(int i = 0; i < initArrayLength; ++i){ int x = maxX/2+i; int y = maxY/2; nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } food = createFood(); matrix[food.x][food.y] = true; } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { //se.changeDirection(SnakeModel.UP); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { //se.changeDirection(SnakeModel.DOWN); } if(e.getKeyCode()==KeyEvent.VK_LEFT) { //se.changeDirection(SnakeModel.LEFT); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { //se.changeDirection(SnakeModel.RIGHT); } if(e.getKeyCode()==KeyEvent.VK_R||e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_ENTER) { } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void repaint() { Graphics g = j1.getGraphics(); //背景 g.setColor(Color.red); g.fillRect(0,0,canvasWidth,canvasHeight); //蛇 //g.setColor(Color.BLUE); } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10,10,10,10); } // //222222 // public void changeDirection(int newDirection){ if (direction % 2 != newDirection % 2){ direction = newDirection; } } public boolean moveOn(){ Node n = (Node)nodeArray.getFirst(); int x = n.x; int y = n.y; switch(direction){ case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){ if (matrix[x][y]){ if(x == food.x && y == food.y){ nodeArray.addFirst(food); int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10; countMove = 0; food = createFood(); matrix[food.x][food.y] = true; return true; } else return false; } else{ nodeArray.addFirst(new Node(x,y)); matrix[x][y] = true; n = (Node)nodeArray.removeLast(); matrix[n.x][n.y] = false; countMove++; return true; } } return false; } public void run(){ running = true; while (running){ try{ Thread.sleep(timeInterval); } catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood(){ int x = 0; int y = 0; do{ Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); }while(matrix[x][y]); return new Node(x,y); } public void speedUp(){ timeInterval *= speedChangeRate; } public void speedDown(){ timeInterval /= speedChangeRate; } public void changePauseState(){ paused = !paused; } public String toString(){ String result = ""; for(int i=0; i<nodeArray.size(); ++i){ Node n = (Node)nodeArray.get(i); result += "[" + n.x + "," + n.y + "]"; } return result; } } class Node{ int x; int y; Node(int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) { //Graphics g=j1.getGraphics(); snate s=new snate(); //s.draw_something(g); //s.setVisible(true); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值