使⽤javaswing实现贪吃蛇
贪吃蛇是⼀个⼤家⽿熟能详的⼩游戏,有很多语⾔的版本,游戏玩法很简单。
这⾥使⽤canvas画板实现。
⾸先定义⼀个Snake类,该类是⼀个列表,存放了蛇上的坐标点,以及蛇的节点的绘制、清除、蛇的移动⽅向等
class Snake extends Arraylist<Point>{
...........
}
接着创建画板GameCanvas类继承Canvas类,该类是程序主要构成,⼤部分操作放在该类中,包括监听键盘按键,游戏的开始、结束、暂停等操作
class GameCanvas extends Canvas{
...........
}
对于程序的窗⼝也需要⼀个类SnakeGame类,该类继承了JFrame,显⽰程序的主界⾯,同时显⽰开始按钮和分数提⽰等等信息,在窗体中把GameCanvas类添加到窗体中
public class SnakeFrame extends JFrame{
.......
public SnakeFrame(){
JPanel pane=new JPanel(null);
canvas = new GameCanvas(this);
pane.add(canvas);
}
}
运⾏效果图如下:
程序完整代码如下:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SnakeFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 2487843782670565160L;
static Color BGCOLOR =Color.BLACK;//定义背景⾊
static Color SNAKECOLOR =Color.BLUE;//定义蛇的颜⾊
static Color BEANCOLOR =Color.RED;//⾷物的颜⾊
static Color EATEDBEANCOLOR =Color.CYAN;//吃的时候⾷物的颜⾊
private String info="请使⽤键盘上的<;上下左右>按钮控制⽅向-空格暂停-ESC退出"; private JLabel helplab=new JLabel(info);
private JLabel scorelab=new JLabel("得分:0");
private JButton beginbnt=new JButton("开始游戏");
private GameCanvas canvas;
public void setLable(String str){
scorelab.setText(str);
}
public SnakeFrame() {
setTitle("-贪吃蛇-");//设置标题
this.setSize(600,400);//设置窗体⼤⼩
JPanel pane=new JPanel(null);//定义窗体⾯板
beginbnt.setBounds(430, 150, 100, 50);//设置开始按钮
pane.add(beginbnt);
beginbnt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
beginbnt.setFocusable(false);//按钮失去焦点
}
});
//设置帮助信息
helplab.setBounds(10, 320, 400, 30);
pane.add(helplab);
//设置分数显⽰标签
scorelab.setBounds(430, 250, 200, 30);
pane.add(scorelab);
//创建游戏⾯板
canvas = new GameCanvas(this);
canvas.setBounds(10, 10, 400, 300);
//添加到窗体
pane.add(canvas);
this.setResizable(false);
//居中
this.setLocationRelativeTo(null);
//关闭窗体程序结束
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SnakeFrame sFrame=new SnakeFrame();
sFrame.setVisible(true);
}
}
/**
*
* @author cslg.yao
*
*/
class GameCanvas extends Canvas{
/**
*
*/
private static final long serialVersionUID = 8444419077424283797L; private int horizontalCount,verticalCount;//明确横向和纵向⼤⼩
private int x,y;
private Snake snake;//蛇列表
private LinkedList<Point> eatedBean = new LinkedList<>();
private Iterator<Point> snakeSq;
public Timer timer;//定时器,⾃动移动
private int direction=2;//⽅向
private int score;//得分
private Point bean= new Point(), eatBean;
private boolean mark;
private Graphics2D g;
private boolean hasStoped =true;
private SnakeFrame game;
public GameCanvas(SnakeFrame gamefrm) {
this();
game=gamefrm;
}
public GameCanvas() {
//设置绘制的尺⼨范围
this.horizontalCount=25;
this.verticalCount=20;
this.x=400/25;
this.y=300/20;
this.addKeyListener(new KeyHandler());
//开始
timer = new Timer(180, new TimerHandler());
snake = new Snake();
hasStoped =false;
setBackground(SnakeFrame.BGCOLOR);
}
private class KeyHandler extends KeyAdapter{
public void keyPressed(KeyEvent e){
if (e.getKeyCode()==10) {
resetGame();
}else if (e.getKeyCode() == 27) {
timer.stop();
if (JOptionPane.showConfirmDialog(null, "你确定退出吗?")==0) {
timer.start();
}
else if (e.getKeyCode()==37 && snake.snakeDirection !=2) {
direction=4;
}
else if (e.getKeyCode()==39 && snake.snakeDirection !=4) {
direction=2;
}
else if (e.getKeyCode()==38 && snake.snakeDirection !=3) {
direction=1;
}
else if (e.getKeyCode()==40 && snake.snakeDirection !=1) {
direction=3;
}else if (e.getKeyCode()==32) {
if (!hasStoped) {
if (!mark) {
timer.stop();
mark=true;
}else {
timer.start();
mark=false;
}
}
}
}
}
private class TimerHandler implements ActionListener{
@Override
public synchronized void actionPerformed(ActionEvent e) {
Point temp=((snake.size()-1);
snakeSq=snake.iterator();
while (snakeSq.hasNext()) {
Point tempPoint = (();
if (temp.equals(tempPoint)&&snakeSq.hasNext()!=false) {
timer.stop();
stopGame();
JOptionPane.showMessageDialog(null,"游戏结束!");
}
}
//判断游戏结束
if ((temp.x ==0 &&direction==4)||(temp.x==horizontalCount-1 &&direction==2)||(temp.y==0&&direction==1)||(temp.y==verticalCount-1&&direction==3) ) {    timer.stop();
stopGame();
JOptionPane.showMessageDialog(null,"游戏结束!");
}
if (direction!=snake.snakeReDirection) {
moveSnake(direction);
}
snake.drawSnake(getGraphics(),x,y);
drawBeanAndEBean(getGraphics());
}
}
/**
* 游戏结束
*/
public void stopGame(){
this.hasStoped = true;
this.timer.stop();
Graphics2D g=(Graphics2D)Graphics();
javaswing实现购买g.setColor(SnakeFrame.BGCOLOR);
* 游戏开始
*/
public void resetGame(){
<();
this.hasStoped=false;
Graphics2D g=(Graphics2D)Graphics();
g.setColor(SnakeFrame.BGCOLOR);
super.paint(g);
this.snake = new Snake();
this.eatedBean.clear();
snake.drawSnake(getGraphics(),x,y);
this.timer.start();
this.direction=2;
this.score=0;
}
/**
* 蛇的移动
* @param direction
*/
private void moveSnake(int direction){
//判断是否吃到⾷物
if (snake.checkBeanIn(this.bean)) {
this.score+=100;
game.setLable("得分:"+this.score+" ");
//添加到吃过的⾷物列表
this.eatedBean.add(new Point(this.bean));
//创建⼀个新的⾷物
}
//
snake.changeDirection(((snake.size()-1),direction);
Point p=((0);
if (eatedBean.size()!=0) {
if (First().equals(p)) {
}else {
snake.clearEndSnakePiece(getGraphics(),p.x,p.y,x,y);
}
}else {
snake.clearEndSnakePiece(getGraphics(),p.x,p.y,x,y);
}
}
/**
* 绘制⾷物
* @param g
*/
private void drawBeanAndEBean(Graphics g){
//设置⾷物的颜⾊
g.setColor(SnakeFrame.BEANCOLOR);
this.drawPiece(g,this.bean.x,this.bean.y);
//设置正在吃的⾷物颜⾊
g.setColor(SnakeFrame.EATEDBEANCOLOR);
snakeSq =eatedBean.iterator();
while (snakeSq.hasNext()) {
Point tempPoint = (Point) ();
this.drawPiece(g,tempPoint.x,tempPoint.y);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。