首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

DOJA 平台貪食蛇遊戲完整原始碼

     編輯:Java 程式設計入門

針對 NTT DoCoMo 的 DOJA (i-mode Java) 平台開發的貪食蛇遊戲,包含主遊戲類別 GreedSnake、畫面框架 Grid、蛇物件 Snake、食物 Food、節點 Node 五個類別。展示行動裝置遊戲迴圈、按鍵處理、碰撞偵測與繪圖邏輯。

主遊戲類別:GreedSnake

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;
    private Food food;
    private Snake snake = new Snake();
    private boolean running;
    private int score, level, count, countMove, timeInterval = 200;

    public void start() {
        reset();
        grid = new Grid(GRID_WIDTH, GRID_HEIGHT, this);
        Display.setCurrent(grid);
        new Thread(this).start();
    }

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

    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; }
    public int getLevel() { return level; }

    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);
    }
}

其他類別摘要

  • Grid:繼承 Canvas,負責畫面繪製、食物/蛇的管理、遊戲結束顯示。
  • Snake:使用 Vector 儲存節點,提供移動、增長、自我碰撞檢查。
  • Food:隨機產生位置,確保不與蛇身重疊。
  • Node:簡單座標容器。

編譯需包含 com.nttdocomo.ui 套件(DOJA SDK)。適合初學者參考行動遊戲基本架構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved