Wednesday, October 21, 2015

Snake Game Design

2. 设计贪吃蛇
怎么定义蛇, 怎么移动, 怎么吃, 怎么判断时候活着, 怎么定义游戏版
Design a snake game function played in nokia mobiles

Different score strategies
The engine is responsible for updating the game at fixed intervals, in response to events, or a combination of the two. In the case of the Snake Game, we need to update the game at regular intervals, and accept user input from the Keyboard. 

To start, we're going to create a new class and name it Engine. This class will be responsible for handling most of the game's logic, the game loop, and window creation. We will return to this class throughout the tutorial as we add functionality to the game.
The next step in creating the Snake Game is to create the world. In the case of the Snake Game, the world will be an array of tiles, each with a type, which we can make use of when writing the game's logic.
we need to get working on the player. In the case of the Snake Game, the player assumes the role of the Snake. A majority of the game's logic goes into updating the snake, as it has the many more physical properties and updates than anything else in the game.

Finally, we're on to the meat of the class, the update method. Here is where we move update the snake's position, and determine whether or not we ate a fruit.
Controller Input
In the Snake Game, the snake can not go in a direction opposite it's current direction.

why there are two variables for the direction of the snake. It's quite simple really; our game runs on one thread, and user input runs on another. This means that we have to poll the direction every time we update the snake. Otherwise, we run the risk of breaking the game by pressing more than one key per update. For example, assume the snake is travelling in the UP direction. Before the game's loop executes, the user presses LEFT, and then DOWN. This would set the direction to DOWN, even though the last direction the snake moved was UP, causing us to lose the game. This is perfectly legal as the last direction that was set was LEFT, and not UP. With two variables, we're able to track the true direction of the snake, and only change it when the game updates.
Fruit and Scoring
we need to introduce the scoring system, and a steadily increasing difficulty.
The main goals for this chapter are to spawn fruit randomly around the board, increment the score by 10 points each time, and to increase the length of the snake by one each round.
  • Improved scoring system (Was 100 points each, now decreases depending on how long it takes to reach it).
Every time that the snake "head" tries to get into the same "slot" as a piece of food, its body will get longer and the movement speed will increase a bit as well.
public class Cell {

    final static int CELL_TYPE_EMPTY = 0, CELL_TYPE_FOOD = 10, CELL_TYPE_SNAKE_NODE = 20;
    final int row, col;
    int type;

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;

This class only keeps row and column numbers. Also some constant integers to determine the types of cells.
Our second class is Board.javaThis class will allow us to identify the area where snake navigates (like a chessboard). 

public class Board {

    final int ROW_COUNT, COL_COUNT;
    Cell[][] cells;

    public Board(int rowCount, int columnCount) {
        ROW_COUNT = rowCount;
        COL_COUNT = columnCount;

        cells = new Cell[ROW_COUNT][COL_COUNT];
        for (int row = 0; row < ROW_COUNT; row++) {
            for (int column = 0; column < COL_COUNT; column++) {
                cells[row][column] = new Cell(row, column);

    public void generateFood() {
        int row = (int) (Math.random() * ROW_COUNT);
        int column = (int) (Math.random() * COL_COUNT);

        cells[row][column].type = Cell.CELL_TYPE_FOOD;

Our third class is 

public class Snake {

    LinkedList<Cell> snakePartList = new LinkedList<>();
    Cell head;

    public Snake(Cell initPos) {
        head = initPos;

    public void grow() {

    public void move(Cell nextCell) {
        Cell tail = snakePartList.removeLast();
        tail.type = Cell.CELL_TYPE_EMPTY;

        head = nextCell;

    public boolean checkCrash(Cell nextCell) {
        for (Cell cell : snakePartList) {
            if (cell == nextCell) {
                return true;

        return false;

Finally, our last class

public class Router {

    public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1, DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2;
    private Snake snake;
    private Board board;
    private int direction;
    private boolean gameOver;

    public Router(Snake snake, Board board) {
        this.snake = snake;
        this.board = board;

    public void setDirection(int direction) {
        this.direction = direction;

    public void update() {
        if (!gameOver) {
            if (direction != DIRECTION_NONE) {
                Cell nextCell = getNextCell(snake.head);

                if (snake.checkCrash(nextCell)) {
                    gameOver = true;
                } else {
                    if (nextCell.type == Cell.CELL_TYPE_FOOD) {

    private Cell getNextCell(Cell currentPosition) {
        int row = currentPosition.row;
        int col = currentPosition.col;

        if (direction == DIRECTION_RIGHT) {
        } else if (direction == DIRECTION_LEFT) {
        } else if (direction == DIRECTION_UP) {
        } else if (direction == DIRECTION_DOWN) {

        Cell nextCell = board.cells[row][col];

        return nextCell;
Snake game implementation with design patterns
The Composite Pattern
Group components Create containment
hierarchies of objects
No differences between objects

If the count of apple is multiple of ten a bonus appears
To die: The snake eat himself or hit a wall



Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts