DOJA开发贪吃蛇的代码

公司准备做手机游戏方面的项目,第一次做DOJA相关的项目,练习了“贪吃蛇”这个游戏,现把自己做的源代码发布出来,希望给才接触DOJA的新手一点提示和帮助。也欢迎大家提出改正。

//主运行类

package greedSnake;
import com.nttdocomo.ui.Display;
import com.nttdocomo.ui.IApplication;
public class GreedSnake extends IApplication implements Runnable{
public static final int GRID_WIDTH = 20;
public static final int GRID_HEIGHT = 24;
public static final int NODE_SIZE  = 10;
private Grid      grid = null;
private Food   food = null;
private Snake      snake = new Snake();;
private boolean     running;
private int    score;
private int       level;
private int       count;
private int    countMove;
private int    timeInterval;

  //----------------------------------------
  /** Set up game. */
  public void start() {
  reset();
grid = new Grid(GRID_WIDTH, GRID_HEIGHT, this);
Display.setCurrent(grid);
Thread runner = new Thread(this);
runner.start();

  }
private void reset() {
 running = false;
 score = 0;
 level = 0;
 count = 0;
 countMove = 6;
 timeInterval = 200;
}

  /** Runnable interface. */
  public void run() {
 food=grid.addFood();
 grid.addSnake(snake);
 grid.repaint();
 for(;;) {
if (food == null) {
   food=grid.addFood();
   continue;
}
try {
  Thread.sleep(timeInterval);
} catch (Exception e) {
  break;
}

if (!running) {
  snake.move();
  Node head = snake.getHead();
  if (grid.overlapsWith(head)||(snake.ptInSnake(head))){
running = true;
continue;
  }
  if((head.x==food.getX())&&(head.y==food.getY())){
int scoreGet=(10000-200*countMove)/timeInterval;
score+=scoreGet>0 ? scoreGet : 0;
countMove=0;
snake.eatFood(food);
grid.reduceFood(food);
food=null;

if( ++count%5 == 0){
   level++;
}

  }else{
countMove++;
  }

grid.repaint();

}else{
  grid.setGameOver();
  break;
}
 }

grid.repaint();

  }

public int getScore() {
 return score;
}

/** Get the current level of the game. */
  public int getLevel() {
  return level;
  }
/** Key event handler. */
  public void keyPressed(int key) {

 if (key == Display.KEY_SELECT) {
grid.setGameOver();
 }
if (key == Display.KEY_LEFT) {
snake.setDirection(Snake.LEFT);
  }
if (key == Display.KEY_RIGHT) {
snake.setDirection(Snake.RIGHT);
  }
if (key == Display.KEY_DOWN) {
snake.setDirection(Snake.DOWN);
  }
  if (key == Display.KEY_UP) {
snake.setDirection(Snake.UP);
  }
}
}
//画面框架类
package greedSnake;
import com.nttdocomo.ui.Canvas;
import com.nttdocomo.ui.Display;
import com.nttdocomo.ui.Font;
import com.nttdocomo.ui.Frame;
import com.nttdocomo.ui.Graphics;
//---------------------
/**
* This class represents the grid box that catches
* the pieces dropping from above. If a dropped piece
* fills up one or more horizontal lines in the grid,
* these lines will be removed from it.
*/
public class Grid extends Canvas {
private int    width;
private int    height;
private GreedSnake  listener;
private Snake      snake;
private Food  food;
private String   pad = "0000";
private Font    score_font;
private Font    game_over_font;
private boolean  blDisplay;
private boolean  game_over;
static final int  SOFT_LEFT = Frame.SOFT_KEY_1;
static final int  SOFT_RIGHT = Frame.SOFT_KEY_2;

/**
 * Create a new instance of this class.
 * @param witdth the width (in tiles) of this grid
 * @param height the height (in tiles) of this grid
 * @param score the score object to keep track of the score
 * @param listener a reference to the owning tetris object
 */
public Grid(int width, int height, GreedSnake listener) {
this.width  = width;
 this.height  = height;
 this.listener = listener;
 reset();
 setSoftLabel(SOFT_LEFT, "New");
 setSoftLabel(SOFT_RIGHT, "Quit");
 score_font  = Font.getFont(Font.FACE_MONOSPACE | Font.SIZE_SMALL);
 game_over_font = Font.getFont(Font.FACE_PROPORTIONAL | Font.SIZE_LARGE | Font.STYLE_BOLD);
}
/** Remove all pieces from this instance */
private void reset() {

 synchronized (this) {
food = null;
snake= null;
 }
 game_over = false;
 blDisplay = false;
}

public void setGameOver() {
 snake = null;
 food = null;
 game_over = true;
}
/** Get the width (in tiles) of this instance. */
public int getGridWidth() {
 return width;
}
/** Get the height (in tiles) of this instance. */
public int getGridHeight() {
 return height;
}

/** Add the specified piece to this instance. */
public Food addFood() {
 blDisplay= false;
 int gs = GreedSnake.GRID_WIDTH;
 if(snake == null){
this.food =Food.createRandomFood(gs,gs);
 }else{
for(;;){
  this.food =Food.createRandomFood(gs,gs);
  Node newNode = new Node(food.getX(),food.getY());
  if(snake.ptInSnake(newNode)){
this.food = null;
continue;
  }else{
break;
  }
}
 }
 return this.food;
}

public void addSnake(Snake snake) {

 this.snake=snake;
 Node head=(Node)snake.getHead();
}
/**
 * Returns <code>true</code> if the specified
 * piece overlaps with any tile in this instance,
 * <code>false</code> otherwise.
 */
public boolean overlapsWith(Node node) {
 if ((node.x<0) || (node.x>getGridWidth()-1)
  || (node.y<0) || (node.y>getGridHeight()-1)) {

return true;
 }
 return false;
}

public void reduceFood(Food food) {
 blDisplay = true;
}

private String format(int n) {
String raw = "" + n;
return pad.substring(0, 4 - raw.length()) + raw;
}
/** Paint this instance onto the specified graphics context. */
public synchronized void paint(Graphics g) {
 g.lock();
 g.setColor(Graphics.getColorOfName(Graphics.BLACK));
 g.fillRect(0, 0, getWidth(), getHeight());
 g.setColor(Graphics.getColorOfName(Graphics.WHITE));
 g.drawLine(0, 0, 0, getHeight());
 g.drawLine(201, 0, 201, getHeight());
 g.drawLine(0, getHeight(), 201, getHeight());
if ((food != null)&& (!blDisplay)) {
food.paint(g);
 }

 if (snake != null) {
snake.paint(g);
 }

 g.setColor(Graphics.getColorOfName(Graphics.SILVER));
 g.setFont(score_font);
 g.drawString("LEVEL", 203, 40);
 g.drawString(String.valueOf(listener.getLevel()), 220, 70);
 g.drawString("SCORE", 202, 100);
 g.drawString(format(listener.getScore()), 208, 130);

 if (game_over) {
g.setColor(0x00ffff);
g.setFont(game_over_font);
g.drawString("GAME", 70, 110);
g.drawString("OVER", 70, 140);
 }
 g.unlock(true);
}
/** Process key events. */
public void processEvent(int type, int param) {
if (type == Display.KEY_PRESSED_EVENT) {
listener.keyPressed(param);
 }
}
}
//蛇对象类
package greedSnake;
import java.util.Random;
import java.util.Vector;
import java.util.Enumeration;
import com.nttdocomo.ui.Graphics;
public class Snake {
public final static int UP = 1;
public final static int DOWN  = 3;
public final static int LEFT  = 2;
public final static int RIGHT = 4;
private int direction;
//  private Grid          grid;
private Node node;
private Vector snakeData = null;
private static Random rnd= new Random();
/** Private internal constructor. */
public Snake() {
 snakeData = new Vector();
 Node node = new Node(4,0);
 snakeData.addElement(node);
 node = new Node(3,0);
 snakeData.addElement(node);
 node = new Node(2,0);
 snakeData.addElement(node);
 node = new Node(1,0);
 snakeData.addElement(node);
 node = new Node(0,0);
 snakeData.addElement(node);
 setDirection(Snake.DOWN);
}

public int getDirection() {
 return direction;
}

public void setDirection(int dir) {
 if(direction%2!=dir%2){
direction = dir;
 }
}
public Node getHead() {
 return (Node) snakeData.elementAt(0);
}

public Node getNextHead() {
 Node node = (Node) snakeData.elementAt(0);
 node = new Node(node.x,node.y);
 switch(this.direction) {
case Snake.UP:
  node.y--;
  break;
case Snake.DOWN:
   node.y++;
   break;
   case Snake.LEFT:
   node.x--;
   break;
   case Snake.RIGHT:
   node.x++;
   break;
  }
  return node;
  }

  public void move() {
 Node node= (Node)snakeData.elementAt(0);
 Node newNode = this.getNextHead();
  for (int i =snakeData.size()-1 ; i>0; i--) {
Node node1 = (Node) snakeData.elementAt(i);
Node node2 = (Node) snakeData.elementAt(i-1);
   node1.x = node2.x;
   node1.y = node2.y;
  }
  node.x = newNode.x;
  node.y = newNode.y;

  }

public void addNode() {
 Node node = (Node) snakeData.lastElement();
 Node newNode = new Node(node.x,node.y);
 snakeData.addElement(newNode);
}

  public void paint(Graphics g) {
  int SnakeColor= 0xff0000;
  int gn = GreedSnake.NODE_SIZE;
 Enumeration e = snakeData.elements() ;
 while(e.hasMoreElements()){
Node node = (Node)e.nextElement() ;
g.setColor(SnakeColor);
g.fillRect(node.x * gn, node.y * gn, gn, gn);
  }
  }
public void eatFood(Food food) {

 this.addNode();

}
public boolean ptInSnake(Node node) {
 for (int i = 1; i<snakeData.size(); i++) {
Node nodeInSnake = (Node) snakeData.elementAt(i);
if ((nodeInSnake.x == node.x)&&(nodeInSnake.y == node.y)) {
  return true;
}
 }
 return false;
}
}
//食物对象类
package greedSnake;
import java.util.Random;
import com.nttdocomo.ui.Graphics;
public class Food {
private int x;
private int y;
private static Random rnd = new Random();

private Food(int x,int y) {
  this.x   = x;
  this.y   = y;
}

public static Food createRandomFood(int width,int height) {
   return createFood( getRandomInt(width),getRandomInt(height));
}

private static int getRandomInt(int limit) {
   return Math.abs(rnd.nextInt() % limit);
}

private static Food createFood(int x,int y) {
 return new Food(x,y);
}
/**
 * Get the x coordinate of the base
 * location of this instance.
 */
public int getX() {
 return x;
}
/**
 * Get the y coordinate of the base
 * location of this instance.
 */
public int getY() {
 return y;
}
/** Paint this instance onto the specified Graphics context. */
public synchronized void paint(Graphics g) {
 int gn = GreedSnake.NODE_SIZE;
 int FoodColor= 0x0000ff;
 g.setColor(FoodColor);
 g.fillRect(this.getX()* gn,this.getY()* gn,gn,gn);
}
}

//节点对象类
/package greedSnake;
public class Node {
public int x;
public int y;
/** Create a new instance of this class. */
public Node(int x, int y) {
 this.x = x;
 this.y = y;
}

}

时间: 2024-08-03 07:07:54

DOJA开发贪吃蛇的代码的相关文章

编程-求大神帮助。从网上找了个贪吃蛇的代码,但是总是运行错误,求帮助,刚刚开始学习c++。

问题描述 求大神帮助.从网上找了个贪吃蛇的代码,但是总是运行错误,求帮助,刚刚开始学习c++. http://yun.baidu.com/share/link?shareid=2570961242&uk=3424030372 解决方案 那就再找一个呗.google上有的是

javascript 贪吃蛇实现代码_javascript技巧

在习作的过程中尝试着贪吃蛇游戏用JS实现了.竟然成功了. 思路:使用10px*10px的div层担当"像素",然后使用40*40矩阵160个"像素"构成了游戏的界面. 下面是代码: 复制代码 代码如下: // JavaScript Document alert("键盘的方向键控制方向,空格键暂停.\nLIFE制作\nhttp://blog.csdn.net/anhulife"); // 添加基本的图形块,即160个10 * 10的层组成的二维矩阵

基于C语言实现的贪吃蛇游戏完整实例代码_C 语言

本文以实例的形式讲述了基于C语言实现的贪吃蛇游戏代码,这是一个比较常见的游戏,代码备有比较详细的注释,对于读者理解有一定的帮助. 贪吃蛇完整实现代码如下: #include <graphics.h> #include <conio.h> #include <stdlib.h> #include <dos.h> #define NULL 0 #define UP 18432 #define DOWN 20480 #define LEFT 19200 #defi

Android开发之经典游戏贪吃蛇_Android

前言 这款游戏实现的思路和源码参考了Google自带的Snake的例子,其中修改了一些个人认为还不够完善的地方,加入了一些新的功能,比如屏幕上的方向操作盘,暂停按钮,开始按钮,退出按钮.另外,为了稍微增加些用户体验,除了游戏的主界面,本人自己新增了5个界面,分别是登陆界面,菜单界面,背景音乐设置界面,难度设置界面,还有个关于游戏的介绍界面.个人觉得在新手阶段,参考现成的思路和实现方式是难以避免的.重要的是我们需要有自己的理解,读懂代码之后,需要思考代码背后的实现逻辑,形成自己的思维.这样在下次开

Python 实现 贪吃蛇大作战 代码分享_python

感觉游戏审核新政实施后,国内手游市场略冷清,是不是各家的新游戏都在排队等审核.媒体们除了之前竞相追捧<Pokemon Go>热闹了一把,似乎也听不到什么声音了.直到最近几天,突然听见好几人都提到同一个游戏,网上还有人表示朋友圈被它刷屏了.(不过现在微信已经悍然屏蔽了它的分享) 这个游戏就是现在iOS免费榜排名第一的<贪吃蛇大作战>.一个简单到不行的游戏,也不知道怎么就火了.反正一款游戏火了,各路媒体.专家总能说出种种套路来,所以我就不发表意见了.不过这实在是一个挺好实现的游戏,于是

Android开发之经典游戏贪吃蛇

前言 这款游戏实现的思路和源码参考了Google自带的Snake的例子,其中修改了一些个人认为还不够完善的地方,加入了一些新的功能,比如屏幕上的方向操作盘,暂停按钮,开始按钮,退出按钮.另外,为了稍微增加些用户体验,除了游戏的主界面,本人自己新增了5个界面,分别是登陆界面,菜单界面,背景音乐设置界面,难度设置界面,还有个关于游戏的介绍界面.个人觉得在新手阶段,参考现成的思路和实现方式是难以避免的.重要的是我们需要有自己的理解,读懂代码之后,需要思考代码背后的实现逻辑,形成自己的思维.这样在下次开

html5贪吃蛇游戏使用63行代码完美实现

以前也很少关注html5,感觉选择html已经慢慢成为趋势,想了解下.就找了个游戏学习了,写完这个游戏感觉html5和js结合很紧密,如果js不 是特别好.估计需要先补习下js,这个只是个人的建议,不一定准确.还有一个就是,思维和逻辑要特别清楚,不然写游戏可能很痛苦. 贪吃蛇,最主要的功能点: 1,蛇的移动 2,改变蛇的方向 3,放置食物 4,增加舍身 5,怎么挂的. 第一次写游戏,第一次写html5 感觉还是很吃力的.写完了,给大家分享下.互相交流.............不懂的或者有建议的,

50行代码实现贪吃蛇(具体思路及代码)_python

最近一直在准备用来面试的几个小demo,为了能展现自己,所以都是亲自设计并实现的,其中一个就是在50行代码内来实现一个贪吃蛇,为了说明鄙人自己练习编程的一种方式--把代码写短,为了理解语言细节. 复制代码 代码如下: <SPAN style="FONT-SIZE: 14px">import sys, pygame from pygame.locals import * from random import randrange up =lambda x:(x[0]-1,x[1

贪吃蛇游戏C++命令行版实例代码_C 语言

本文实例讲述了贪吃蛇游戏C++命令行版的实现代码,是非常经典的游戏.分享给大家供大家参考.具体实现方法如下: 众所周知,贪吃蛇游戏是经典的计算机游戏. 游戏描述如下: 1. 贪吃蛇可以自动直线前进,或者玩家可以通过方向键操纵贪吃蛇上下左右前进,每次前进一格. 2. 贪吃蛇在规定的区域内活动,当: ①贪吃蛇触碰到墙壁时: ②贪吃蛇的蛇头触碰到蛇身或者蛇尾时: ③玩家的键盘输入不是方向键时: 命令行显示"Game Over!"并且退出游戏. 3. 贪吃蛇活动的区域内每次随机产生一颗&quo