Skip to content

Instantly share code, notes, and snippets.

@mrowdy
Last active August 29, 2015 13:56
Show Gist options
  • Save mrowdy/9080544 to your computer and use it in GitHub Desktop.
Save mrowdy/9080544 to your computer and use it in GitHub Desktop.
part of minefield;
class Field{
final int index;
final Point position;
bool isOpen = false;
bool isMine = false;
bool isFlagged = false;
int surroundingMines = 0;
Field(this.index, this.position);
}
library minefield;
import 'dart:html';
part 'field.dart';
class Minefield {
int _width; // Width of canvas
int _height; // Height of canvas
int _rows; // Numer of rows
int _cols; // Number of columns
int _mines; // Number of mines
List<Field> _fields;
Element _container;
CanvasElement _canvas;
CanvasRenderingContext2D _ctx;
double _fieldWidth;
double _fieldHeight;
Map<String, String> _colors = {
'background': '#395D33',
'closed': '#4DBD33',
'open': '#734523',
'numbers': '#ffffff',
'flag': '#ffffff',
'mine': '#ff0000'
};
Minefield(this._container, [this._width = 320, this._height = 320, this._rows = 10, this._cols = 10, this._mines = 10]){
_setupCanvas();
setup();
}
void _setupCanvas(){
_canvas = new CanvasElement(width: _width, height: _height );
_ctx = _canvas.getContext('2d');
_fieldWidth = _width / _cols;
_fieldHeight = _height / _rows;
_container.style.width = '${_width}px';
_container.append(_canvas);
}
void setup(){
_setupFields();
_render();
}
void _setupFields(){
_fields = new List<Field>();
int fieldCount = _rows * _cols;
for(int i = 0; i < fieldCount; i++){
// Create two dimensional position based on list index
Point position = new Point(
i % _cols,
(i / _cols).floor()
);
Field field = new Field(i, position);
_fields.add(field);
}
}
void _render(){
_ctx..fillStyle = _colors['background']
..fillRect(0, 0, _width, _height);
_fields.forEach((field) => _renderField(field));
}
void _renderField(Field field){
String color = _colors['closed'];
_ctx..fillStyle = color
..fillRect(
field.position.x * _fieldWidth + 1,
field.position.y * _fieldHeight + 1,
_fieldWidth - 2,
_fieldHeight - 2
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment