Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Last active August 29, 2015 14:11
Show Gist options
  • Save Aleksey-Danchin/859d95e1a955aaf67e18 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/859d95e1a955aaf67e18 to your computer and use it in GitHub Desktop.
The game of splash.
<canvas id="canvasElement" style="border: 1px solid black;"></canvas>
<script>
setup(); loop(); setInterval(loop, 10);
/////////////////////////////////////////////////
var canvas, context, map, fieldSize, byX, byY, mouseX, mouseY;
/////////////////////////////////////////////////
function setup () {
canvas = document.getElementById('canvasElement');
context = canvas.getContext('2d');
canvas.width = canvas.height = 500;
fieldSize = 50; byX = 10; byY = 10;
map = [];
for (var i = 0; i < byX; i++) {
map.push([]);
for (var j = 0; j < byY; j++)
map[i][j] = 1 + Math.floor(Math.random() * 8);
}
colorMap = {
0: 'white', 1: 'black', 2: 'blue',
3: 'yellow', 4: 'red', 5: 'pink',
6: 'green', 7: 'gray', 8: 'SkyBlue'
};
document.addEventListener('mousemove', mousemoveHandler);
document.addEventListener('click', clickHandler);
}
/////////////////////////////////////////////////
function loop () {
clearCanvas();
drawMap();
}
/////////////////////////////////////////////////
function drawField (x, y, type) {
context.beginPath();
context.fillStyle = colorMap[type] ? colorMap[type] : 'black';
context.fillRect(x * fieldSize, y * fieldSize, fieldSize, fieldSize);
}
function drawMap () {
for (var i = 0; i < byX; i++)
for (var j = 0; j < byY; j++)
drawField(j, i, map[i][j]);
}
function clearCanvas () {
canvas.width = canvas.width;
}
function gameNewControlColorCode (newCode) {
var flag = true,
oldCode = map[0][0];
map[0][0] = true;
while (flag) {
flag = false;
for (var i = 0; i < byX; i++)
for (var j = 0; j < byY; j++)
if (isActivePosition(i, j, oldCode))
flag = map[i][j] = true;
}
for (var i = 0; i < byX; i++)
for (var j = 0; j < byY; j++)
if (map[i][j] === true)
map[i][j] = newCode;
}
function isActivePosition (i, j, code) {
if (map[i][j] !== code) return false;
if (i > 0 && map[i - 1][j] === true) return true;
if (i < byX -1 && map[i + 1][j] === true) return true;
if (j > 0 && map[i][j - 1] === true) return true;
if (j < byY -1 && map[i][j + 1] === true) return true;
return false;
}
/////////////////////////////////////////////////
function mousemoveHandler (event) {
var rect = canvas.getBoundingClientRect();
mouseX = event.clientX - rect.left;
mouseY = event.clientY - rect.top;
}
function clickHandler (event) {
var x = parseInt(mouseX / fieldSize),
y = parseInt(mouseY / fieldSize),
colorCode = map[y][x];
gameNewControlColorCode(colorCode);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment