栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现简易贪吃蛇游戏

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现简易贪吃蛇游戏

本文实例为大家分享了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

运行图片

游戏结束

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129616.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号