Skip to content

Instantly share code, notes, and snippets.

@devoncarew
Forked from kasperpeulen/index.html
Created March 12, 2015 22:08
Show Gist options
  • Save devoncarew/af19a7b30086697e7ba0 to your computer and use it in GitHub Desktop.
Save devoncarew/af19a7b30086697e7ba0 to your computer and use it in GitHub Desktop.
<div id="score" class="score"></div>
<canvas id="myCanvas" width="500" height="500"></canvas>
// Copyright 2014 David Kopec
// Created for Dart for Absolute Beginners, an Apress title
// MIT License, see https://github.com/davecom/Dart-for-Absolute-Beginners/blob/master/license.txt
import 'dart:html';
import 'dart:async'; // for Timer
import 'dart:math'; // for Random
const int BOX_WIDTH = 100;
const int BOX_HEIGHT = 50;
int boxX, boxY, score = 0, speed;
CanvasElement myCanvas;
Element get scoreElement => querySelector('#score');
/// Called by a Timer 60 times per second
void update(Timer t) {
boxX += speed; //update box's location
// get a new box when the last one has gone off screen
if (boxX < (-BOX_WIDTH) || boxX > myCanvas.width){
newRandomBox();
}
draw();
}
/// Draw a background, the box, and the score
void draw() {
CanvasRenderingContext2D myCanvasContext = myCanvas.context2D;
//draw the background
myCanvasContext.setFillColorRgb(255, 255, 255); // Blue
myCanvasContext.fillRect(0, 0, 500, 500); // 0x, 0y, 500 width, 500 height
//draw the score in black at the top right of the screen
String scoreText = "Score: $score";
//myCanvasContext.fillText(scoreText, myCanvas.width-100, 30); // string, x, y
scoreElement.text = scoreText;
myCanvasContext.setFillColorRgb(0, 0, 0); // Black
//draw the box
myCanvasContext.fillRect(boxX,boxY,BOX_WIDTH,BOX_HEIGHT);
}
/// Sets up a new box at a random location
void newRandomBox() {
// if it's 1 it will go right, otherwise left
Random rand = new Random();
speed = rand.nextInt(10) + 5; // random speed 5 to 14 pixels/frame
boxY = rand.nextInt(myCanvas.height - BOX_HEIGHT); // random y
int leftOrRight = rand.nextInt(2);
if (leftOrRight == 1) { // going from left to right
boxX = 0;
} else { //going from right to left
boxX = myCanvas.width - BOX_WIDTH;
speed = -speed; // move left not right
}
}
/// When the canvas is clicked, we need to check if the user hit a box
void clickHappened(MouseEvent me) {
//check if click was within the box's space
int clickX = me.offset.x;
int clickY = me.offset.y;
if (clickX > boxX && clickX < boxX + BOX_WIDTH
&& clickY > boxY && clickY < boxY + BOX_HEIGHT) { // we have a hit
score++;
newRandomBox();
}
}
void main() {
myCanvas = querySelector("#myCanvas");
myCanvas.onClick.listen(clickHappened);
newRandomBox();
// TODO: We should we requestAnimationFrame here.
// This Timer will call update() approximately 60 times a second
new Timer.periodic(const Duration(milliseconds:17), update);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment