用java的swing框架自己写贪吃蛇游戏

java是门高级语言,做游戏时适合做后台,但是用它也可以做游戏。闲来无事做的时候可以用来写点小游戏,练习练习预防早衰哈哈!

闲话不说了

下面是以前练习的作品,不怕大家笑话,那个时候用了一个礼拜才做出来的。

源码如下供大家学习。

使用的是java的 swing  Jframe Jpanel JButton   当然你也可以使用awt

package Tcs;
/**
 * 
 * 
 * 
 * @author tx
 */
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

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

public class Snack extends JPanel implements KeyListener {
	public JButton bt = new JButton("重新开始");
	public ArrayList<Treasure> bw = new ArrayList<Treasure>();
	public body[] b = new body[5];
	public String state = "";
	public ArrayList<point> p = new ArrayList<point>();
	public static int score;

	public Snack() {
		this.addKeyListener(this);
		shengc();

	}

	public void shengc() {
		for (int i = 0; i < b.length; i++) {
			b[i] = new body();
			b[i].x = 10 - i * 10;
			b[i].y = 150;

		}

	}

	public int x = 0, y = 0;

	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(new Color(165,41,10));//RGB定义颜色的方法
		g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
		for (int i = 0; i < b.length; i++) {
			body z1 = b[i];

			g.drawString("O", b[i].x, b[i].y);
		}
		g.setColor(Color.BLUE);
		g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
		g.drawString("SCORE:" + score, 30, 30);
		paintjs(g);
		paintbw(g);
	}

	public void paintjs(Graphics g) {
		g.setColor(Color.BLACK);
		if (state.length() > 1) {

			g.drawString(state, 140, 200);
		}

	}

	public void paintbw(Graphics g) {
		g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 25));
		g.setColor(Color.RED);
		for (int i = 0; i < bw.size(); i++) {
			g.drawString("o", bw.get(i).x, bw.get(i).y);

		}

	}

	public boolean yj() {

		if ((b[0].x < 400 && b[0].x > 0) && (b[0].y < 400 && b[0].y > 0)) {

			return false;
		} else {

			state = "GAME OVER";
			return true;
		}

	}

	public void stmove() {

		if (pzjc() == false && (yj() == false)) {
			b[0].speed = 19;
			b[0].move();

			p.add(new point(b[0].x, b[0].y, b[0].fx));
			if (p.size() > b.length) {

				p.remove(p.get(0));
				// System.out.println(p.size());
			}
		}
	}

	public int jl(body a, Treasure b) {
		int jl = 0;
		jl = (int) Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y)
				* (a.y - b.y));

		return jl;

	}// 暂时无用

	public void ssmove() {

		if (p.size() >= b.length) {

			for (int i = 0; i < b.length - 1; i++) {
				b[i + 1].fx = p.get(i).fx;

				b[i + 1].x = p.get(i).x;
				b[i + 1].y = p.get(i).y;

			}
		}
	}

	Random r = new Random();

	public void bzbw() {
		if (bw.size() < 1) {

			Treasure s = new Treasure();

			s.x = r.nextInt(300) + 50;
			s.y = r.nextInt(300) + 50;
			bw.add(s);
		}
	}

	public void bwxs() {
		Timer t = new Timer();
		t.schedule(new TimerTask() {

			public void run() {

			}
		}, 0, 8000);

	}

	public boolean pzjc() {
		for (int i = 1; i < p.size(); i++) {
			if (p.get(0).equals(p.get(i))) {
				state = "GAME OVER";
				return true;

			}
		}
		return false;
	}

	public void crush() {
		if (bw.size() > 0) {

			if (jl(b[0], bw.get(0)) < 8) {

				bw.remove(0);
				b = Arrays.copyOf(b, b.length + 1);
				b[b.length - 1] = new body();

				score += 10;

			}
		}

	}

	public void gameover() {
		MouseListener k = new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {

				super.mouseClicked(e);
				state = "";
				b = Arrays.copyOf(b, 5);
				p.clear();
				shengc();
				score = 0;
				bt.setVisible(false);
				

			}

		};
		if (state.length() > 1) {
			this.add(bt);
			bt.setVisible(true);
			
			bt.setBounds(150, 150, 100, 30);

			bt.addMouseListener(k);
		}
           if(bt.isVisible()==false){this.remove(bt);} 
		this.requestFocus();
     
	}

	public void zmAction() {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			public void run() {

				bzbw();// 生成宝物
				stmove();// 蛇头运动

				ssmove();// 蛇身运动
				crush();// 碰撞检测
				gameover();
				repaint();
			}
		}, 10, 83);

	}

	public static void main(String[] args) {
		JFrame jf = new JFrame("贪吃蛇");
		jf.setBounds(0, 0, 400, 400);
		jf.setVisible(true);
		jf.setLayout(null);
		Container c = new Container();
		c = jf.getContentPane();
		c.setBackground(Color.WHITE);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Snack s = new Snack();
		s.setVisible(true);
		s.setBounds(0, 0, 600, 600);
		s.setLocation(0, 0);
		s.setBackground(Color.ORANGE);
		jf.add(s);
		s.zmAction();

		s.requestFocus();
	}

	public void keyTyped(KeyEvent e) {
		

	}


	public void keyPressed(KeyEvent e) {
		int k = e.getKeyCode();
		switch (k) {
		case KeyEvent.VK_UP:
			if (b[0].fx != "sz" && b[0].fx != "xz") {
				b[0].fx = "sz";
			}
			break;
		case KeyEvent.VK_DOWN:
			if (b[0].fx != "sz" && b[0].fx != "xz") {
				b[0].fx = "xz";
			}
			break;
		case KeyEvent.VK_LEFT:
			if (b[0].fx != "zz" && b[0].fx != "yz") {
				b[0].fx = "zz";
			}
			break;
		case KeyEvent.VK_RIGHT:
			if (b[0].fx != "zz" && b[0].fx != "yz") {
				b[0].fx = "yz";
			}
			break;

		}
		repaint();

	}

	public void keyReleased(KeyEvent e) {

	}

}
body类

package Tcs;

public class body {
public int x=0;
public int y=0;
public int speed;
private String str;
public String fx;
public body(){
	fx="yz";
}
public int getX() {
	return x;
}
public void setX(int x) {
	this.x = x;
}
public int getY() {
	return y;
}
public void setY(int y) {
	this.y = y;
}
public String getStr() {
	return str;
}
public void setStr(String str) {
	this.str = str;
}
public void sz(){
	
	this.y+=-speed;
}
public void xz(){
	this.y+=speed;
}
public void zz(){
	this.x+=-speed;
}
public void yz(){
	this.x+=speed;
}
public void move(){
	if(fx=="xz"){
		xz();
	}
	if(fx=="sz"){
		sz();
	}
	if(fx=="zz"){
		zz();
	}
	if(fx=="yz"){
		yz();
	}
}
}
宝物类

package Tcs;

public class Treasure {
public int x;
public int y;
public String str;
}

point类

package Tcs;

public class point {
public int x;

public int y;
public String fx;
public point(int x,int y,String fx){
	this.x=x;
	this.y=y;
	this.fx=fx;
}

public boolean equals(Object o){
	if(o instanceof point){
		point p=(point)o;
		if(p.x==this.x&&p.y==this.y){
			return true;
		}
		
	}
	if(o==this){return true;}
	if(o==null){return false;}
	return false;}
}




  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,我来为您编一个简单的贪吃蛇游戏,使用 JavaSwing 框架。下面是代码: ```java import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class SnakeGame extends JPanel implements ActionListener, KeyListener { private static final long serialVersionUID = 1L; private static final int WIDTH = 500; private static final int HEIGHT = 500; private static final int DOT_SIZE = 10; private static final int ALL_DOTS = 900; private static final int RAND_POS = 29; private static final int DELAY = 140; private final int[] x = new int[ALL_DOTS]; private final int[] y = new int[ALL_DOTS]; private int dots; private int apple_x; private int apple_y; private boolean leftDirection = false; private boolean rightDirection = true; private boolean upDirection = false; private boolean downDirection = false; private boolean inGame = true; private Timer timer; private Random rand; public SnakeGame() { addKeyListener(this); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(WIDTH, HEIGHT)); initGame(); } private void initGame() { dots = 3; for (int z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } rand = new Random(); locateApple(); timer = new Timer(DELAY, this); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (inGame) { g.setColor(Color.red); g.fillOval(apple_x, apple_y, DOT_SIZE, DOT_SIZE); for (int z = 0; z < dots; z++) { if (z == 0) { g.setColor(Color.green); g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE); } else { g.setColor(new Color(45, 180, 0)); g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE); } } } else { gameOver(g); } } private void gameOver(Graphics g) { String msg = "Game Over"; g.setColor(Color.white); g.drawString(msg, (WIDTH - g.getFontMetrics().stringWidth(msg)) / 2, HEIGHT / 2); } private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } private void move() { for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[0] -= DOT_SIZE; } if (rightDirection) { x[0] += DOT_SIZE; } if (upDirection) { y[0] -= DOT_SIZE; } if (downDirection) { y[0] += DOT_SIZE; } } private void checkCollision() { for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if (!inGame) { timer.stop(); } } private void locateApple() { int r = rand.nextInt(RAND_POS); apple_x = ((r * DOT_SIZE)); r = rand.nextInt(RAND_POS); apple_y = ((r * DOT_SIZE)); } @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } } @Override public void keyReleased(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) {} public static void main(String[] args) { JFrame frame = new JFrame("Snake"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new SnakeGame()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } ``` 运行这个代码,你会看到一个简单的贪吃蛇游戏
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值