import 'dart:html';
import 'dart:math';
import 'dart:async';
import 'dart:collection';
const int HORIZONTAL_TILES = 40;
const int VERTICAL_TILES = 40;
const int TILE_WIDTH = 15;
const String CANVAS_BACKGROUND="#EEE";
const int SPEED = 100; // in milliseconds
const String FRUIT_COLOR = "black";
const String SNAKE_COLOR = "green";
const int INIT_SNAKE_SIZE = 6;
CanvasElement canvas = query('#canvas');
CanvasRenderingContext2D ctx = canvas.getContext('2d');
Tile fruit;
Snake snake;
Direction snakeDirection;
Random randomGenerator = new Random();
Timer timer;
void main() {
canvas.width=HORIZONTAL_TILES*TILE_WIDTH;
canvas.height=VERTICAL_TILES*TILE_WIDTH;
ctx.fillStyle = CANVAS_BACKGROUND;
ctx.fillRect(0, 0, HORIZONTAL_TILES*TILE_WIDTH, VERTICAL_TILES*TILE_WIDTH);
snake = new Snake(INIT_SNAKE_SIZE);
snakeDirection = Direction.DOWN;
initTimer();
initKeyBoardListener();
generateFruit();
}
void initTimer(){
void moveSnake(Timer timer){
bool hasMoved = true;
switch (snakeDirection) {
case Direction.RIGHT:
hasMoved = snake.moveRight(); break;
case Direction.LEFT:
hasMoved = snake.moveLeft(); break;
case Direction.UP:
hasMoved = snake.moveUp(); break;
case Direction.DOWN:
hasMoved = snake.moveDown(); break;
}
if(!hasMoved){ timer.cancel(); }
}
timer = new Timer.periodic(const Duration(milliseconds: SPEED), moveSnake);
}
void initKeyBoardListener(){
void processKeyEvent(Direction direction, Direction opposite){
if(snakeDirection != opposite)
snakeDirection = direction;
}
void keyboardListener(Event event){
if(event is KeyboardEvent){
KeyboardEvent kEvent = event as KeyboardEvent;
switch(kEvent.keyCode){
case KeyCode.UP:
processKeyEvent(Direction.UP, Direction.DOWN); break;
case KeyCode.DOWN:
processKeyEvent(Direction.DOWN, Direction.UP); break;
case KeyCode.LEFT:
processKeyEvent(Direction.LEFT, Direction.RIGHT); break;
case KeyCode.RIGHT:
processKeyEvent(Direction.RIGHT, Direction.LEFT); break;
}
}
}
window.onKeyDown.listen(keyboardListener);
}
void generateFruit(){
int x = randomGenerator.nextInt(HORIZONTAL_TILES);
int y = randomGenerator.nextInt(VERTICAL_TILES);
fruit = new Tile(x, y);
fruit.paint(FRUIT_COLOR);
}
/* --------------------
* SNAKE CLASS
* -------------------- */
class Snake {
var queue = new Queue();
Snake(int initSize){
int x = randomGenerator.nextInt(HORIZONTAL_TILES-initSize*2);
int y = 0; // start at the top
for(int i=0; i [LEFT, RIGHT, UP, DOWN];
final int value;
const Direction._(this.value);
}