Good enough for now

This commit is contained in:
A Bass 2022-04-20 23:23:51 -04:00
parent ef376178df
commit 9f1bf7eb4d
10 changed files with 287 additions and 69 deletions

Binary file not shown.

183
index.js
View file

@ -1,24 +1,153 @@
var express = require('express'); var express = require('express');
const worldgen = require("./worldgen.js") const worldgen = require("./worldgen.js")
const data = require("./tileinfo.js")
const util = require("./util.js") const util = require("./util.js")
const gridSize = [18, 18];
const perlinScale = 3; const perlinScale = 3;
class Player { class Player {
constructor(id, color) { constructor(id, color, name) {
this.name = name
this.id = id; this.id = id;
this.color = color; this.color = color;
this.buildings = [0,0,0,0,0,0,0,0,0,0,0,0,0]
this.gold = 100
this.power = 100 + util.randomNumber(2,50)
} }
kill(client) {
if(game.players.length < 2){
for(let x = 0; x < game.gridSize[0]; x++) {
for(let y = 0; y < game.gridSize[1]; y++) {
if (game.world.map[x][y].owner == this.id) {
game.world.map[x][y].owner = null
game.world.map[x][y].color = null
}
}
}
} else {
console.log("KILL")
let playerList = game.players.filter(obj => obj.id != this.id);
while (playerList > 1) {
for (let i = 1; i < playerList.length-1; i++) {
if (playerList[util.randomNumber(0,i)].gold < playerList[i].gold) {
delete playerList[i];
}
}
playerlist = playerList.filter(obj => obj != null)
}
var player2 = playerList[0]
this.transfer(player2)
}
sendMap(client)
game.removePlayer(this.id);
}
transfer(player2) {
player2.gold += this.gold
player2.power += this.power
for(let x = 0; x < game.gridSize[0]; x++) {
for(let y = 0; y < game.gridSize[1]; y++) {
if (game.world.map[x][y].owner == this.id) {
game.world.map[x][y].owner = player2.id
game.world.map[x][y].color = player2.color
}
}
}
for (i = 0; i < this.buildings.length; i++) {
player2.buildings[i] += this.buildings[i]
}
}
}
class World {
constructor(gridSize, perlinScale) {
console.log(gridSize)
this.map = worldgen.generateWorld(gridSize, perlinScale)
}
// Determine what method of clicking is to be used by player
click(structure, x, y, client){
const player = game.getPlayerByID(client.id);
//Build Mode
if (this.map[x][y].owner == player.id) {
this.placeStructure(structure, x, y, player, client)
}
//Claim Mode
if (this.map[x][y].owner == null) {
this.claimLand(x, y, player, client)
}
if (this.map[x][y].owner != null && this.map[x][y].owner != player.id) {
//Attack Mode
}
}
// Function for placing buildings on land
placeStructure(structure, x, y, player, client) {
// Get info for the structure desired to be built from databank
const strucInfo = data.structureTypes[structure]
// Get the tile object the structure is to be built upon
const tileOfInterest = this.map[x][y];
// get info for the tile the structure is to be built upon from databank
const tileInfo = data.tileTypes[tileOfInterest.type]
const cost = strucInfo.buildPrice + tileInfo.buildPrice;
if (
// Check if the structure is valid to be built
strucInfo.buildable == true
// Check if player is still under building limit for structure
&& player.buildings[structure] < strucInfo.maxQuantity
// Ensure no other builings are already built in this tile
&& tileOfInterest.structure == 0
// Check to see if the structure can be built on the type of tile
&& strucInfo.buildableOn.includes(tileOfInterest.type)
// Check if player has enough gold to build this
&& player.gold > cost
) {
// Update tile on map
this.map[x][y].structure = structure
// Increment building count for this structure
player.buildings[structure] ++;
// Charge player for cost of structure
player.gold -= cost;
sendMap(client)
}
}
claimLand(x, y, player, client) {
const tileOfInterest = this.map[x][y];
if (data.structureTypes[tileOfInterest.structure].claimable == true) {
this.map[x][y].owner = player.id
this.map[x][y].color = player.color
sendMap(client)
}
}
}
function sendMap(client) {
client.broadcast.emit('sync',{world: game.world.map})
client.emit('sync',{world: game.world.map})
} }
class Game { class Game {
constructor() { constructor(gridSize) {
this.players = []; this.players = [];
this.world = worldgen.generateWorld(gridSize, perlinScale); this.world = new World(gridSize, perlinScale);
this.gridSize = gridSize
} }
addPlayer(id) { addPlayer(id, name) {
var color var color
switch(util.randomNumber(1,4)) { switch(util.randomNumber(1,4)) {
case 1: case 1:
@ -37,8 +166,9 @@ class Game {
color = "yellow"; color = "yellow";
break; break;
} }
const player = new Player(id, color); const player = new Player(id, color, name);
this.players.push(player); this.players.push(player);
console.log(player.name)
} }
removePlayer(id) { removePlayer(id) {
@ -47,14 +177,12 @@ class Game {
} }
getPlayerByID(id) { getPlayerByID(id) {
console.log(this.players)
console.log(id)
const player = this.players.filter(obj => obj.id == id)[0] const player = this.players.filter(obj => obj.id == id)[0]
return player return player
} }
} }
var game = new Game(); var game = new Game([18, 18]);
var app = express() //Static resources server var app = express() //Static resources server
@ -66,35 +194,38 @@ app.use(express.static(__dirname + '/www/'));var server = app.listen(8082, funct
var io = require('socket.io')(server);/* Connection events */ var io = require('socket.io')(server);/* Connection events */
io.on('connection', function(client) { io.on('connection', function(client) {
console.log('User connected'); console.log('User connected');
client.emit('gameVars', {gridSize: game.gridSize, world: game.world.map})
client.on('disconnect', function(){ client.on('disconnect', function(){
console.log(client.id + ' disconnected.') console.log(client.id + ' disconnected.')
game.removePlayer(client.id) game.getPlayerByID(client.id).kill(client)
client.broadcast.emit('playerList', game.players) // client.broadcast.emit('playerList', game.players)
}) })
client.on('joinGame', function(tank){ client.on('joinGame', function(data){
game.addPlayer(client.id); console.log(game.players)
console.log(client.id + ' joined the game'); console.log(client.id + ' joined the game');
client.emit('gameVars', {gridSize: gridSize, world: game.world}) game.addPlayer(client.id, data.name);
client.broadcast.emit('playerList', game.players) // client.broadcast.emit('playerList', game.players)
client.emit('playerList', game.players) // client.emit('playerList', game.players)
}) })
client.on('leaveGame', function(tank){ client.on('leaveGame', function(tank){
console.log(client.id + ' disconnected.') console.log(client.id + ' disconnected.')
game.removePlayer(client.id) // game.getPlayerByID(cliend.id).kill()
client.broadcast.emit('playerList', game.players) game.getPlayerByID(client.id).kill(client)
// client.broadcast.emit('playerList', game.players)
}) })
client.on('clickCanvas', function(data){ client.on('clickCanvas', function(data){
const xu = data.tilePosition[0] const xu = util.clamp(data.tilePosition[0], 0, game.gridSize[0])
const yu = data.tilePosition[1] const yu = util.clamp(data.tilePosition[1], 0, game.gridSize[1])
game.world[xu][yu].structure = data.structure // game.world.map[xu][yu].structure = data.structure
game.world[xu][yu].owner = game.getPlayerByID(client.id).color; game.world.click(data.structure, xu, yu, client)
// console.log(world[xu][yu].owner = game.getPlayerbyID(client.id)) // game.world.map[xu][yu].owner = game.getPlayerByID(client.id).color;
// client.broadcast.emit('sync',{world: game.world.map})
client.broadcast.emit('sync',{world: game.world}) // client.emit('sync',{world: game.world.map})
client.emit('sync',{world: game.world})
}) })

0
net.js Normal file
View file

18
tileinfo.js Normal file
View file

@ -0,0 +1,18 @@
const tileTypes =
[
{name: "Grass", textureID: 0, buildPrice: 20, capturePrice:10, capturePower: 10, captureTime: 2, sellPrice:5, recapturePrice: 15, recapturePower: 100, recaptureTime: 10},
{name: "Hills", textureID: 1, buildPrice: 20, capturePrice:10, capturePower: 10, captureTime: 2, sellPrice:5, recapturePrice: 15, recapturePower: 100, recaptureTime: 10},
{name: "Sea", textureID: 2, buildPrice: 20, capturePrice:10, capturePower: 10, captureTime: 2, sellPrice:5, recapturePrice: 15, recapturePower: 100, recaptureTime: 10}
];
const structureTypes =
[
{name: "Air", textureID:null, claimable: true, buildable: false, destroyable: false, maxQuantity:null, buildPrice: null, sellPrice: null, buildableOn: null},
{name: "Rock", textureID:4, claimable: false, buildable: false, destroyable: false, maxQuantity:null, buildPrice: null, sellPrice: null, buildableOn: [0,1]},
{name: "Town", textureID:32, claimable: false, buildable: true, destroyable: true, maxQuantity:10, buildPrice: 10, sellPrice: 5, buildableOn: [0,2]},
{name: "City", textureID:33, claimable: false, buildable: true, destroyable: true, maxQuantity:10, buildPrice: 20, sellPrice: 10, buildableOn: [0,2]},
{name: "Capitol", textureID:34, claimable: false, buildable: true, destroyable: false, maxQuantity:1, buildPrice: 30, sellPrice: 20, buildableOn: [0,2]},
]
module.exports = {tileTypes, structureTypes}

View file

@ -1,5 +1,7 @@
function randomNumber(min, max) { function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min); return Math.floor(Math.random() * (max - min) + min);
} }
function clamp(number, min, max) {
module.exports = {randomNumber} return Math.max(min, Math.min(number, max));
}
module.exports = {randomNumber, clamp}

View file

@ -7,7 +7,7 @@ function generateWorld(gridSize, perlinScale){
let tempWorld = Array.from(Array(gridSize[0]), () => new Array(gridSize[1])); let tempWorld = Array.from(Array(gridSize[0]), () => new Array(gridSize[1]));
for (x = 0; x < gridSize[0]; x++){ for (x = 0; x < gridSize[0]; x++){
for (y = 0; y < gridSize[1]; y++){ for (y = 0; y < gridSize[1]; y++){
tempWorld[x][y] = {type: 0, structure: 0, owner: null} tempWorld[x][y] = {type: 0, structure: 0, color: null, owner: null}
} }
} }
@ -32,7 +32,7 @@ function generateWorld(gridSize, perlinScale){
y = util.randomNumber(0,gridSize[1]); y = util.randomNumber(0,gridSize[1]);
if (tempWorld[x][y].type != 1) { if (tempWorld[x][y].type != 1) {
i++; i++;
tempWorld[x][y].structure = 1 tempWorld[x][y].structure = util.randomNumber(1,4)
} }
} }
return tempWorld; return tempWorld;

View file

@ -7,22 +7,28 @@
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
</head> </head>
<body> <body>
<h1>Uber Secret Project</h1> <div class="container" id="container" style="display: none;">
<div class="container"> <h1>No Longer Secret Project</h1>
<canvas class="" id="spritejank" width=24 height=24></canvas>
<canvas class="hidden" id="spriteJank" width=24 height=24></canvas>
<div class="wrapper"> <div class="wrapper">
<div class="canvasStack"> <div class="canvasStack">
<canvas class="canvas1" id="canvas" width=0 height=0></canvas> <canvas oncontextmenu="return false;" class="canvas1" id="canvas" width=0 height=0></canvas>
<canvas class="canvas2" id="hud" width="0" height="0"></canvas> <canvas oncontextmenu="return false;" class="canvas2" id="hud" width="0" height="0"></canvas>
</div> </div>
</div> </div>
<div class="right"> <div class="right">
<p>Info</p><br>
<p id="cash">$0</p> <p id="cash">$0</p>
</div> </div>
</div> </div>
<div class="menu" id="menu">
<form id="form">
<input type="text" id="room" value="room">
<input type="submit" id="join" value="join">
</form>
</div> </div>
</body> </body>
<script src='script.js'></script> <script src='script.js'></script>

View file

@ -3,19 +3,34 @@ const tileSize = 24;
var gridSize; var gridSize;
var cash = 99; var cash = 99;
var world var world
var tiles = []
var canvas = document.getElementById('canvas'); var canvas = document.getElementById('canvas');
var hud = document.getElementById('hud'); var hud = document.getElementById('hud');
var ctx = canvas.getContext('2d'); var ctx = canvas.getContext('2d');
var hctx = hud.getContext('2d'); var hctx = hud.getContext('2d');
var socket = io.connect('http://127.0.0.1:8082/'); var socket = io.connect('http://127.0.0.1:8082/');
function joinGame(socket){ function joinGame(socket, room, nick){
socket.emit('joinGame', {}); socket.emit('joinGame', {room, nick});
} }
function leaveGame(socket){ function leaveGame(socket){
socket.emit('leaveGame', {}); socket.emit('leaveGame', {});
} }
joinGame(socket);
class Cursor {
constructor(){
this.x = 0
this.y = 0
this.xold = 0
this.yold = 0
}
}
var cursor = new Cursor();
window.onbeforeunload = function(){ window.onbeforeunload = function(){
socket.disconnect(); socket.disconnect();
@ -38,20 +53,43 @@ socket.on('sync', function (sync){
render() render()
}) })
window.onload = function () { function loadSprites(){
var spriteJank = document.getElementById('spriteJank');
var ctxj = spriteJank.getContext('2d');
var spriteSheet = new Image();
// GET THE IMAGE. spriteSheet.src = '/sheet.png'
var city = new Image(); spriteSheet.onload = function() {
city.src = 'img/city.png';
var rock = new Image();
rock.src = 'img/rock.png'; for (y = 0; y < 16; y++) {
var grass = new Image(); for (x = 0; x < 16; x++) {
grass.src = 'img/grass.png' ctxj.drawImage(spriteSheet, -x*24,-y*24)
var sea = new Image(); var tmp = new Image();
sea.src = 'img/sea.png' tmp.src = spriteJank.toDataURL();
var hills = new Image(); ctxj.clearRect(0, 0, 24, 24);
hills.src = 'img/hills.png' tiles.push(tmp)
tiles = [grass,hills,sea,rock,city]; }
}
}
}
function submit(event) {
document.getElementById('menu').style = "display: none;"
document.getElementById('container').style = ""
const room = document.getElementById("room").value
event.preventDefault();
joinGame(socket, {room: room, name: "bob"})
}
window.onload = function () {
const form = document.getElementById('form');
form.addEventListener('submit', submit);
loadSprites()
@ -59,7 +97,9 @@ window.onload = function () {
function fill_canvas() { function fill_canvas() {
// CREATE CANVAS CONTEXT. // CREATE CANVAS CONTEXT.
hud.addEventListener('mousemove', e => {
mouseMoved(e)
});
hud.addEventListener("mousedown", function(e) hud.addEventListener("mousedown", function(e)
{ {
getMousePosition(canvas, e); getMousePosition(canvas, e);
@ -70,7 +110,6 @@ function fill_canvas() {
hud.height = canvas.height hud.height = canvas.height
render()
updateUI(); updateUI();
} }
@ -103,22 +142,26 @@ function render() { // DRAW THE IMAGE TO THE CANVAS.
// Draw Structures // Draw Structures
switch (world[x][y].structure) { switch (world[x][y].structure) {
case (1): case (1):
ctx.drawImage(tiles[3], xu,yu)
break;
case (2):
ctx.drawImage(tiles[4], xu,yu) ctx.drawImage(tiles[4], xu,yu)
break; break;
case (2):
ctx.drawImage(tiles[32], xu,yu)
break;
case (3):
ctx.drawImage(tiles[33], xu,yu)
break;
case (4):
ctx.drawImage(tiles[34], xu,yu)
break;
} }
// Draw Property overlays // Draw Property overlays
if (world[x][y].owner != null){ if (world[x][y].color != null){
ctx.beginPath(); ctx.beginPath();
ctx.fillStyle = world[x][y].owner; ctx.fillStyle = world[x][y].color;
ctx.rect(xu, yu, tileSize, tileSize) ctx.rect(xu, yu, tileSize, tileSize)
ctx.globalAlpha = 0.5; ctx.globalAlpha = 0.6;
ctx.fill() ctx.fill()
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
} }
@ -136,18 +179,27 @@ function getMousePosition(canvas, event) {
const rect = canvas.getBoundingClientRect(); const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left; const x = event.clientX - rect.left;
const y = event.clientY - rect.top; const y = event.clientY - rect.top;
const xu = Math.floor(x/tileSize) // const xu = Math.floor(x/tileSize)
const yu = Math.floor(y/tileSize) // const yu = Math.floor(y/tileSize)
const xu = cursor.x
const yu = cursor.y
// Convert canvas coordinates to usable coordinates within the coordinate system // Convert canvas coordinates to usable coordinates within the coordinate system
console.log("Click!") console.log("Click!")
console.log(xu,yu) console.log(xu,yu)
socket.emit('clickCanvas', {tilePosition: [xu,yu], structure: 2}); socket.emit('clickCanvas', {tilePosition: [xu,yu], structure: 2});
// if (tile.type != 1 && tile.structure != 1 && cash > 10) {
// tile.structure = 2
// cash = cash - 10;
// }
} }
function mouseMoved(event) {
const x = Math.floor(event.offsetX/tileSize)
const y = Math.floor(event.offsetY/tileSize)
if (cursor.xold != x || cursor.yold != y) {
cursor.x = x
cursor.y = y
hctx.clearRect(cursor.xold*tileSize, cursor.yold*tileSize, tileSize, tileSize)
hctx.drawImage(tiles[80], x*tileSize,y*tileSize)
cursor.xold = x
cursor.yold = y
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

View file

@ -1,4 +1,9 @@
canvas { canvas {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
-o-user-select: none;
user-select: none;
image-rendering: -moz-crisp-edges; image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges; image-rendering: -webkit-crisp-edges;
image-rendering: pixelated; image-rendering: pixelated;
@ -9,6 +14,10 @@ canvas {
/* margin: auto; */ /* margin: auto; */
} }
.hidden {
display: none;
}
.canvas1{ .canvas1{
z-index: 0; z-index: 0;
position: fixed; position: fixed;