本文实例为大家分享了java实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下
1.封装贪吃蛇身体,抽象出贪吃蛇结点类Node,结点用ArrayList存储
import java.awt.*;
public class Node {
private int x;
private int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public Node(){
}
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 void drawNode(int i, Graphics g){
if(i==0){//头绘制成圆
g.fillOval(this.x,this.y,20-1,20-1);
}else{//身体绘制成矩形
g.fillRect(this.x,this.y,20-1,20-1);
}
}
}
2.主类
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class Snake extends frame implements KeyListener , ActionListener {
//初始蛇移动方向
String fx="right";
//碰撞判断
boolean is_attack=false;
private ArrayList body=new ArrayList();
{
body.add(new Node(160, 60));
body.add(new Node(140, 60));
body.add(new Node(120, 60));
int x=(int)(Math.random()*580);
int y=(int)(Math.random()*580);
body.add(new Node(x-x%20,y-y%20));
}
public Snake(){
//窗体标题
super.setTitle("贪吃蛇游戏");
//窗体位置
super.setLocation(100,100);
//窗体大小
super.setSize(600,600);
//背景颜色
super.setBackground(new Color(252,255, 208));
//设置窗体可见
super.setVisible(true);
// 窗体大小不可变
super.setResizable(false);
//给关闭按钮添加事件
super.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//获取聚焦
super.setFocusable(true);
//添加键盘监听
super.addKeyListener(this);
start();
}
public void start(){
while(!is_attack){
try{
Thread.sleep(200);
}catch (Exception e){
e.printStackTrace();
}
//碰撞检测
attack_check();
//刷新窗体,调用paint方法
repaint();
}
}
//碰撞检测
public void attack_check(){
//撞到身体检测
for(int i=1;i
运行图片
游戏结束
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



