Created
August 28, 2014 20:11
-
-
Save sylvainmathieu/8e8efab0a2fd6ecf4acb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:html'; | |
import 'dart:math'; | |
import 'dart:async'; | |
var ctx; | |
List<Point> snake = [new Point(12, 10)]; | |
Point direction = new Point(1, 0); | |
Point food; | |
void main() { | |
CanvasElement canvas = querySelector("#game"); | |
ctx = canvas.context2D; | |
ctx.fillStyle = "black"; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
food = getNewFood(); | |
drawBlock(food); | |
new Timer.periodic(const Duration(milliseconds: 100), init); | |
document.addEventListener("keydown", (e) { | |
switch (e.keyCode) { | |
case 39: direction = new Point(1, 0); break; // right | |
case 40: direction = new Point(0, 1); break; // down | |
case 37: direction = new Point(-1, 0); break; // left | |
case 38: direction = new Point(0, -1); break; // up | |
} | |
}); | |
} | |
class Point { | |
int x; | |
int y; | |
Point(int x, int y) { | |
this.x = x; | |
this.y = y; | |
} | |
int get hashCode { | |
int result = 17; | |
result = 37 * result + x.hashCode; | |
result = 37 * result + y.hashCode; | |
return result; | |
} | |
bool operator==(other) { | |
if (other is! Point) return false; | |
Point point = other; | |
return (point.x == x && point.y == y); | |
} | |
} | |
void drawBlock(Point pos) { | |
ctx.strokeStyle = "rgba(255,255,255, 0.5)"; | |
ctx.strokeRect(pos.x * 10 + 0.5, pos.y * 10 + 0.5, 8, 8); | |
ctx.fillStyle = "rgba(255,255,255, 0.2)"; | |
ctx.fillRect(pos.x * 10 + 0.5, pos.y * 10 + 0.5, 8, 8); | |
} | |
void eraseBlock(Point pos) { | |
ctx.fillStyle = "black"; | |
ctx.fillRect(pos.x * 10, pos.y * 10, 10, 10); | |
} | |
int randomCoord() => new Random().nextInt(30); | |
Point getNewFood() { | |
return new Point(randomCoord(), randomCoord()); | |
} | |
bool isCollision(Point newHead) { | |
return snake.contains(newHead) || newHead.x < 0 || newHead.x > 30 || newHead.y < 0 || newHead.y > 30; | |
} | |
bool gameOver() => false; | |
bool game() { | |
var head = snake.first; | |
var newHead = new Point(head.x + direction.x, head.y + direction.y); | |
if (isCollision(newHead)) { | |
return gameOver(); | |
} | |
else if (newHead == food) { | |
food = getNewFood(); | |
snake = new List<Point>() | |
..add(newHead) | |
..addAll(snake); | |
drawBlock(newHead); | |
drawBlock(food); | |
} | |
else { | |
eraseBlock(snake.last); | |
snake = new List<Point>() | |
..add(newHead) | |
..addAll(snake.sublist(0, snake.length - 1)); | |
drawBlock(newHead); | |
} | |
return true; | |
} | |
void init(timer) { | |
if (!game()) { | |
timer.cancel(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment