browserloops-examples/lib/game/Game.dart

80 lines
2 KiB
Dart

import 'dart:html';
import 'dart:math';
typedef void gridIterator(int x, int y);
class Game {
List<List<Color>> grid;
CanvasElement canvas;
Random rng = new Random();
double _oscill = 0.1;
bool _oscillDir = true; // oscillate upwards (true) or downwards (false)
double _OSCILLSPEED = 0.1;
bool _fwd = true;
Game(CanvasElement this.canvas) {
grid = _buildGrid(5, 5, new Color(255, 0, 255));
}
// In-World Logic Updates
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));
}
// Render Pipeline
void draw([num interp]) {
CanvasRenderingContext2D ctx = this.canvas.context2D;
int brickW = (canvas.width ~/ grid[0].length);
int brickH = (canvas.height ~/ grid.length);
ctx.clearRect(0, 0, canvas.width, canvas.height);
_grid_foreach((x, y) {
Color col = _oscillate(grid[y][x]);
ctx.setFillColorRgb(col.r, col.g, col.b);
ctx.fillRect(x*brickW, y*brickH, brickW, brickH);
});
}
// Slightly oscillating colors to highlight rendering updates
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);
}
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);
}
}
}
List<List<Color>> _buildGrid(int w, int h, Color col) {
List<List<Color>> grid = new List(h);
for (int y = 0; y < h; y++) {
grid[y] = new List(w);
for (int x = 0; x < w; x++) {
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);
}