MultiplayerMinesweeper/www/script.js
2022-04-20 14:53:36 -04:00

154 lines
3.2 KiB
JavaScript

// const perlinScale = 3;
const tileSize = 24;
var gridSize;
var cash = 99;
var world
var canvas = document.getElementById('canvas');
var hud = document.getElementById('hud');
var ctx = canvas.getContext('2d');
var hctx = hud.getContext('2d');
var socket = io.connect('http://127.0.0.1:8082/');
function joinGame(socket){
socket.emit('joinGame', {});
}
function leaveGame(socket){
socket.emit('leaveGame', {});
}
joinGame(socket);
window.onbeforeunload = function(){
socket.disconnect();
world = []
}
socket.on('gameVars', function(tank){
gridSize = tank.gridSize;
world = tank.world;
fill_canvas()
});
socket.on('playerList', function(data){
console.log(data)
});
socket.on('sync', function (sync){
world = sync.world;
render()
})
window.onload = function () {
// GET THE IMAGE.
var city = new Image();
city.src = 'img/city.png';
var rock = new Image();
rock.src = 'img/rock.png';
var grass = new Image();
grass.src = 'img/grass.png'
var sea = new Image();
sea.src = 'img/sea.png'
var hills = new Image();
hills.src = 'img/hills.png'
tiles = [grass,hills,sea,rock,city];
}
function fill_canvas() {
// CREATE CANVAS CONTEXT.
hud.addEventListener("mousedown", function(e)
{
getMousePosition(canvas, e);
});
canvas.width = tileSize*gridSize[0];
canvas.height = tileSize*gridSize[1];
hud.width = canvas.width
hud.height = canvas.height
render()
updateUI();
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function render() { // DRAW THE IMAGE TO THE CANVAS.
let x, y = 0
for(x = 0; x < gridSize[0]; x++){
for(y = 0; y < gridSize[1]; y++){
const xu = x*tileSize;
const yu = y*tileSize;
// Draw buildings
switch (world[x][y].type) {
case (0):
ctx.drawImage(tiles[0], xu,yu)
break;
case (1):
ctx.drawImage(tiles[2], xu,yu)
break;
case (2):
ctx.drawImage(tiles[1], xu,yu)
break;
}
// Draw Structures
switch (world[x][y].structure) {
case (1):
ctx.drawImage(tiles[3], xu,yu)
break;
case (2):
ctx.drawImage(tiles[4], xu,yu)
break;
}
// Draw Property overlays
if (world[x][y].owner != null){
ctx.beginPath();
ctx.fillStyle = world[x][y].owner;
ctx.rect(xu, yu, tileSize, tileSize)
ctx.globalAlpha = 0.5;
ctx.fill()
ctx.globalAlpha = 1;
}
}
}
console.log("image Rendered")
}
function updateUI(){
document.getElementById("cash").innerHTML = ("$" + cash +socket.id);
}
function getMousePosition(canvas, event) {
// Get mouse position on canvas
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const xu = Math.floor(x/tileSize)
const yu = Math.floor(y/tileSize)
// Convert canvas coordinates to usable coordinates within the coordinate system
console.log("Click!")
console.log(xu,yu)
socket.emit('clickCanvas', {tilePosition: [xu,yu], structure: 2});
// if (tile.type != 1 && tile.structure != 1 && cash > 10) {
// tile.structure = 2
// cash = cash - 10;
// }
}