在开始编写代码之前,先来看看游戏的整体结构。如下的伪代码描述了程序需要做什么:

Set up the canvas

Set score to zero

Create snake

Create apple

Every 100 milliseconds {

    Clear the canvas

    Draw current score on the screen

    Move snake in current direction

    If snake collides with wall or itself {

        End the game

    } Else If snake eats an apple {

        Add one to score

        Move apple to new location

        Make snake longer

    }

    For each segment of the snake {

        Draw the segment

    }

    Draw apple

    Draw border

}

When the user presses a key {

    If the key is an arrow {

        Update the direction of the snake

    }

}

学习完本章和下一章之后,我们将能够编写代码来执行这些步骤中的每一步。下面先来看看程序的主要组成部分,并且规划出开发它们所需要的一些JavaScript工具。