java简单贪吃蛇

学Java后第一个小游戏
效果图如下效果
有空做个双蛇版
package snake;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SnakeV_1 {

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

}

class Snake extends JPanel{

private static final long serialVersionUID = 1L; 

LinkedList<Point> snake = new LinkedList<Point>();

Point food;

public int WIDTH = 50;//格子数

public int HEIGHT =30;

public int CELLHEIGHT = 20;//格子高

public int CELLWIDTH = 20;

private boolean [][] background = new boolean[HEIGHT][WIDTH];

boolean isGameOver = false;
boolean runing = false;//运行

//蛇蛇当前方向方向
public final int UP_DIRECTION = 1;
public final int DOWN_DIRECTION = -1;
public final int LEFT_DIRECTION = 2;
public final int RIGHT_DIRECTION = -2;

//蛇当前方向,默认向右
private int currentDrection = -2;

JFrame frame = new JFrame("贪吃 1.0");

public Snake() {
	super();
	initBackground();
	initSnake();
	CreateFood();
	CreateWall();
	frame.add(this);
	initFrame(WIDTH*CELLWIDTH+20, HEIGHT*CELLHEIGHT+70);
	frame.addKeyListener(new KeyAdapter() {
		@Override
		public void keyPressed(KeyEvent e) {
			int code = e.getKeyCode();
			switch (code) {
			case KeyEvent.VK_UP:
				changeDirection(UP_DIRECTION);
				break;
			case KeyEvent.VK_DOWN:
				changeDirection(DOWN_DIRECTION);
				break;
			case KeyEvent.VK_LEFT:
				changeDirection(LEFT_DIRECTION);
				break;
			case KeyEvent.VK_RIGHT:
				changeDirection(RIGHT_DIRECTION);
				break;
			case KeyEvent.VK_SPACE://暂停功能带实现
				runing = false;
				break;
			case KeyEvent.VK_S://开始
				runing = true;
				break;
			case KeyEvent.VK_R://开始
				frame.dispose();
				new Snake();
				break;
			default:
				break;
			}								
		}
	});	
	new Thread() {
		public void run() {
			while(true) {
				int time =300;
				try {
					Thread.sleep(time - 10 *snake.size());
				} catch (InterruptedException e) {			
					e.printStackTrace();
				}
				move();
				isGameover();
				  if(isGameOver == true) { 
					  runing = false; 
				}				
			}
		}
	 }.start();
}

@Override
public void paint(Graphics g) {	
	super.paint(g);
	g.setColor(Color.RED);
	g.drawString("按s开始游戏,空格暂停 r从来",0,HEIGHT*CELLHEIGHT+20);
		
	for(int rows = 0;rows < background.length; rows++) {
		for (int cols = 0; cols < background[rows].length; cols++) {
			//石头
			if(background[rows][cols]) {
				g.setColor(Color.GRAY);
			}else {
				g.setColor(Color.PINK);
			}
			g.fill3DRect(cols*CELLWIDTH, rows*CELLHEIGHT, CELLWIDTH, CELLHEIGHT, true);
		}
	}
	
	g.setColor(Color.BLUE);//
	for (int i = 1; i < snake.size(); i++) {
		Point body = snake.get(i);
		g.fill3DRect(body.x*CELLWIDTH, body.y*CELLHEIGHT, CELLWIDTH, CELLHEIGHT, true);
	}
	
	Point head = snake.getFirst();
	g.setColor(Color.RED);
	g.fill3DRect(head.x*CELLWIDTH, head.y*CELLHEIGHT, CELLWIDTH, CELLHEIGHT, true);
	
	g.setColor(Color.GREEN);
	g.fill3DRect(food.x*CELLWIDTH, food.y*CELLHEIGHT, CELLWIDTH, CELLHEIGHT, true);
	if(isGameOver == true) {	
		g.setColor(Color.RED);
		g.drawString("GAMEOVER",WIDTH*CELLWIDTH/2,HEIGHT*CELLHEIGHT/2);	
	}
}

public void initFrame(int width,int height) {
	Toolkit toolkit = Toolkit.getDefaultToolkit();//获取与系统相关的工具类对象
	Dimension d = toolkit.getScreenSize();//分辨率
	frame.setBackground(Color.blue);
	frame.setBounds((d.width-width)/2, (d.height- height)/2, width, height);			
	frame.setVisible(true);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}	

public void initBackground() {//初始化地图
	for(int rows = 0;rows < background.length; rows++) {
		for (int cols = 0; cols < background[rows].length; cols++) {
			if(rows == 0 || rows == HEIGHT-1) {
				background[rows][cols] = true; 
			}
		}
	}				
}

public void initSnake() {
	int x = WIDTH/2;
	int y = HEIGHT/2;
	snake.addFirst(new Point(x-1,y));
	snake.addFirst(new Point(x,y));
	snake.addFirst(new Point(x+1,y));
}

public void CreateFood() {
	Random random = new Random();
	while(true) {
		int x = random.nextInt(WIDTH-2)+1;
		int y = random.nextInt(HEIGHT-2)+1;
		if(background[y][x] != true) {
			food = new Point(x,y);
			break;
		}
	}		
}

public void CreateWall() {
	for (int i = 0; i < 10; i++) {
		Random random = new Random();
		while(true) {
			int x = random.nextInt(WIDTH-2)+1;
			int y = random.nextInt(HEIGHT-2)+1;
			if(background[y][x] != true) {
				background[y][x] = true;
				break;
			}
		}		
	}	
}

public void CleanWall() {
	for(int rows = 1;rows < background.length-1; rows++) {
		for (int cols = 0; cols < background[rows].length; cols++) {
			//if(rows != 0 || rows != HEIGHT-1) {
				background[rows][cols] = false; 
			//}
		}
	}
}

public boolean eatfood() {
	Point head = snake.getFirst();
	if(head.equals(food)) {
		return true;
	}
	return false;
}

public void move() {
	if(runing) {
		Point head = snake.getFirst();
		switch (currentDrection) {
		case UP_DIRECTION:
			snake.addFirst(new Point(head.x,head.y-1));
			break ;
		case DOWN_DIRECTION:
			snake.addFirst(new Point(head.x,head.y+1));
			break ;
		case LEFT_DIRECTION:
			if(head.x == 0) {
				snake.addFirst(new Point(WIDTH-1,head.y));
			}else {
				snake.addFirst(new Point(head.x-1,head.y));
			}
			break ;
		case RIGHT_DIRECTION:
			if(head.x == WIDTH-1) {
				snake.addFirst(new Point(0,head.y));
			}else {
				snake.addFirst(new Point(head.x+1,head.y));
			}
			break ;
		default:
			break;
		}
		if(eatfood()) {				
			CleanWall();
			CreateFood();
			CreateWall();
		}else {
			snake.removeLast();
		}
		repaint();
	}
}

public void changeDirection(int newDirection) {
	//判断是否相反	//改变方向
	if(newDirection + currentDrection != 0) {
		this.currentDrection = newDirection;
	}
}

public void isGameover() {
	//撞墙
	Point head = snake.getFirst();
	if(background[head.y][head.x] == true) {
		isGameOver = true;
	}
	//咬自己
	for (int i = 1; i < snake.size(); i++) {
		Point body = snake.get(i);
		if(head.equals(body)) {
			isGameOver = true;
		}
	}
}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值