browserloops-examples/lib/game/Game.dart

83 lines
2 KiB
Dart
Raw Normal View History

2018-07-20 09:58:11 +00:00
import 'dart:html';
2018-07-20 12:36:32 +00:00
import 'dart:math';
2018-07-20 12:05:48 +00:00
typedef void gridIterator(int x, int y);
2018-07-20 09:58:11 +00:00
class Game {
List<List<Color>> grid;
CanvasElement canvas;
CanvasRenderingContext2D ctx;
2018-07-20 12:36:32 +00:00
Random rng = new Random();
2018-07-20 09:58:11 +00:00
2018-07-20 12:36:32 +00:00
double _oscill = 0.1;
bool _oscillDir = true; // oscillate upwards (true) or downwards (false)
double _OSCILLSPEED = 0.05;
2018-07-20 09:58:11 +00:00
bool _fwd = true;
Game(CanvasElement this.canvas) {
2018-07-20 12:36:32 +00:00
grid = buildGrid(5, 5, new Color(255, 0, 255));
2018-07-20 09:58:11 +00:00
ctx = this.canvas.getContext('2d');
}
2018-07-20 12:36:32 +00:00
void update([num dt]) {
int ry = rng.nextInt(grid.length);
grid[ry][rng.nextInt(grid[ry].length)] = new Color(rng.nextInt(255), rng.nextInt(255), rng.nextInt(255));
}
2018-07-20 09:58:11 +00:00
void draw([num interp]) {
int brickW = (canvas.width ~/ grid[0].length);
int brickH = (canvas.height ~/ grid.length);
ctx.clearRect(0, 0, canvas.width, canvas.height);
2018-07-20 12:05:48 +00:00
grid_foreach((x, y) {
2018-07-20 12:36:32 +00:00
Color col = _oscillate(grid[y][x]);
ctx.setFillColorRgb(col.r, col.g, col.b);
2018-07-20 09:58:11 +00:00
ctx.fillRect(x*brickW, y*brickH, brickW, brickH);
2018-07-20 12:05:48 +00:00
});
2018-07-20 09:58:11 +00:00
}
2018-07-20 12:36:32 +00:00
Color _oscillate(Color col) {
if(_oscill >= 50.0 || _oscill <= -50.0) {
_oscillDir = !_oscillDir;
_oscill = max( min(_oscill, 49.0), -49.0);
}
else _oscillDir == true ? _oscill += _OSCILLSPEED : _oscill -= _OSCILLSPEED;
int o = _oscill.toInt();
return new Color(col.r + o, col.g + o, col.b + o);
}
2018-07-20 09:58:11 +00:00
2018-07-20 12:05:48 +00:00
void grid_foreach(gridIterator fun) {
for (int y = 0; y < grid.length; y++) {
for (int x = 0; x < grid[y].length; x++) {
fun(x, y);
}
}
2018-07-20 09:58:11 +00:00
}
List<List<Color>> buildGrid(int w, int h, Color col) {
List<List<Color>> grid = new List(h);
2018-07-20 12:05:48 +00:00
for (int y = 0; y < h; y++) {
2018-07-20 09:58:11 +00:00
grid[y] = new List(w);
2018-07-20 12:05:48 +00:00
for (int x = 0; x < w; x++) {
2018-07-20 09:58:11 +00:00
grid[y][x] = col;
}
}
return grid;
}
}
class Color {
final int r;
final int g;
final int b;
const Color(this.r, this.g, this.b);
}
// Create 2d array
// fill with random colors
// cycle colors
2018-07-20 12:05:48 +00:00
// set one color to random new one