Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,13 @@ module.exports = {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {},
rules: {
'no-unused-expressions': 'off',
'no-unused-vars': 'off',
'max-len': 'off',
camelcase: 'off',
'import/prefer-default-export': 'off',
'no-param-reassign': 'off',
'no-plusplus': 'off',
},
};
3 changes: 2 additions & 1 deletion public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
<div class="wrap">
<div class="logo"></div>
<div class="canvas-wrap">
<h3>Loading...</h3>
<canvas id='game' width="600" height="600"></canvas>
<h3 id='loading'>Loading...</h3>
<div class="border">
<div class="top-left"></div>
<div class="top"></div>
Expand Down
Binary file added src/assets/characters.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/assets/terrain.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions src/client/ClientCamera.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import MovableObject from '../common/MovableObject';

class ClientCamera extends MovableObject {
constructor(cfg) {
super(cfg);

Object.assign(
this,
{
cfg,
width: cfg.canvas.width,
height: cfg.canvas.height,
},
cfg,
);
}

focusAtGameObject(obj) {
const pos = obj.worldPosition(50, 50);
this.moveTo((pos.x = this.width / 2), pos.y - this.height / 2, false);
}
}

export default ClientCamera;
50 changes: 50 additions & 0 deletions src/client/ClientCell.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import PositionedObject from '../common/PositionedObject';
import ClientGameObject from './ClientGameObject';

class ClientCell extends PositionedObject {
constructor(cfg) {
super();
const { cellWidth, cellHeight } = cfg.world;

Object.assign(
this,
{
cfg,
objects: [],
x: cellWidth * cfg.cellCol,
y: cellWidth * cfg.cellRow,
width: cellWidth,
height: cellHeight,
},
cfg,
);

this.initGameObjects();
}

initGameObjects() {
const { cellCfg } = this;

this.objects = cellCfg[0].map((objCfg) => new ClientGameObject({ cell: this, objCfg }));
}

render(time) {
const { objects } = this;

objects.map((obj) => obj.render(time));
}

addGameObject(objToAdd) {
this.objects.push(objToAdd);
}

removeGameObject(objToRemove) {
this.objects = this.objects.filter((obj) => obj !== objToRemove);
}

findObjectsByType(type) {
return this.objects.filter((obj) => obj.type === type);
}
}

export default ClientCell;
77 changes: 77 additions & 0 deletions src/client/ClientEngine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* eslint-disable object-curly-newline */
import EventSourceMixin from '../common/EventSourceMixin';
import ClientCamera from './ClientCamera';
import ClientInput from './ClientInput';

class ClientEngine {
constructor(canvas) {
Object.assign(this, {
canvas,
ctx: null,
imageLoaders: [],
sprites: {},
images: {},
camera: new ClientCamera({ canvas, engine: this.engine }),
input: new ClientInput(canvas),
});

this.ctx = canvas.getContext('2d');

this.loop = this.loop.bind(this);
}

start() {
this.loop();
}

loop(timestamp) {
const { ctx, canvas } = this;
ctx.fillStyle = 'black';
ctx.clearRect(0, 0, canvas.width, canvas.height);

this.trigger('render', timestamp);
this.initNextFrame();
}

initNextFrame() {
window.requestAnimationFrame(this.loop);
}

loadSprites(spritesGroup) {
this.imageLoaders = [];
Object.keys(spritesGroup).forEach((groupName) => {
const group = spritesGroup[groupName];
this.sprites[groupName] = group;

Object.keys(group).forEach((spriteName) => {
const { img } = group[spriteName];
if (!this.images[img]) {
this.imageLoaders.push(this.loadImage(img));
}
});
});

return Promise.all(this.imageLoaders);
}

loadImage(url) {
return new Promise((resolve) => {
const i = new Image();
this.images[url] = i;
i.onload = () => resolve(i);
i.src = url;
});
}

renderSpriteFrame({ sprite, frame, x, y, w, h }) {
const spriteCfg = this.sprites[sprite[0]][sprite[1]];
const [fx, fy, fw, fh] = spriteCfg.frames[frame];
const img = this.images[spriteCfg.img];

this.ctx.drawImage(img, fx, fy, fw, fh, x, y, w, h);
}
}

Object.assign(ClientEngine.prototype, EventSourceMixin);

export default ClientEngine;
78 changes: 78 additions & 0 deletions src/client/ClientGame.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import ClientEngine from './ClientEngine';
import ClientWorld from './ClientWorld';

import sprites from '../configs/sprites';
import levelCfg from '../configs/world.json';
import gameObjects from '../configs/gameObjects.json';

class ClientGame {
constructor(cfg) {
Object.assign(this, {
cfg,
gameObjects,
player: null,
});

this.engine = this.createEngine();
this.initEngine();

this.world = this.createWorld();
}

setPlayer(player) {
this.player = player;
}

createEngine() {
return new ClientEngine(document.getElementById(this.cfg.tagId));
}

createWorld() {
return new ClientWorld(this, this.engine, levelCfg);
}

initEngine() {
this.engine.loadSprites(sprites).then(() => {
this.world.init();
this.engine.on('render', (_, time) => {
this.world.render(time);
});
this.engine.start();
this.initKeys();
});
}

initKeys() {
const canMovePlayer = (cell) => cell.findObjectsByType('grass').length;
this.engine.input.onKey({
ArrowLeft: (keydown) => {
if (keydown) {
this.player.moveByCellCoord(-1, 0, canMovePlayer);
}
},
ArrowRight: (keydown) => {
if (keydown) {
this.player.moveByCellCoord(1, 0, canMovePlayer);
}
},
ArrowUp: (keydown) => {
if (keydown) {
this.player.moveByCellCoord(0, -1, canMovePlayer);
}
},
ArrowDown: (keydown) => {
if (keydown) {
this.player.moveByCellCoord(0, 1, canMovePlayer);
}
},
});
}

static init(cfg) {
if (!ClientGame.game) {
ClientGame.game = new ClientGame(cfg);
}
}
}

export default ClientGame;
91 changes: 91 additions & 0 deletions src/client/ClientGameObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/* eslint-disable object-curly-newline */
import MovableObject from '../common/MovableObject';

class ClientGameObject extends MovableObject {
constructor(cfg) {
super();

const { x, y, width, height } = cfg.cell;

const { world } = cfg.cell;
const gameObjs = world.game.gameObjects;
const objCfg = typeof cfg.objCfg === 'string' ? { type: cfg.objCfg } : cfg.objCfg;

if (objCfg.player) {
world.game.setPlayer(this);
}

Object.assign(
this,
{
cfg,
x,
y,
width,
height,
spriteCfg: gameObjs[objCfg.type],
objectConfig: objCfg,
type: objCfg.type,
world,
},
cfg,
);
}

moveByCellCoord(dcol, drow, conditionCallback = null) {
const { cell } = this;
this.moveToCellCoord(cell.cellCol + dcol, cell.cellRow + drow, conditionCallback);
}

moveToCellCoord(dcol, drow, conditionCallback = null) {
const { world } = this;
const newCell = world.cellAt(dcol, drow);

if (!conditionCallback || conditionCallback(newCell)) this.setCell(newCell);
}

setCell(newCell) {
if (newCell) {
this.detouch();
this.cell = newCell;
newCell.addGameObject(this);

const { x, y, width, height } = newCell;
Object.assign(this, {
x,
y,
width,
height,
});
}
}

render(time) {
super.render(time);

const { x, y, width, height, world } = this;
const { engine } = world;

const { sprite, frame, states } = this.spriteCfg;

const spriteFrame = states ? states.main.frames[0] : frame;

engine.renderSpriteFrame({
sprite,
frame: spriteFrame,
x,
y,
w: width,
h: height,
});
}

detouch() {
if (this.cell) {
this.cell.removeGameObject(this);
this.cell = null;
}
}
}

export default ClientGameObject;
34 changes: 34 additions & 0 deletions src/client/ClientInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import EventSourceMixin from '../common/EventSourceMixin';

class ClientInput {
constructor(canvas) {
Object.assign(this, {
canvas,
keysPressed: new Set(), // клавиши, зажатые в данный момент
keyStateHandlers: {}, // обработчики, срабатывающие каждый рендер, если нажата клавиша
keyHandlers: {}, // обработчики при нажатии определенной клавиши
});
canvas.addEventListener('keydown', (e) => this.onKeyDown(e), false);
canvas.addEventListener('keyup', (e) => this.onKeyUp(e), false);
}

onKeyDown(e) {
this.keysPressed.add(e.code);
this.keyHandlers[e.code] && this.keyHandlers[e.code](true);
this.trigger('keydown', e);
}

onKeyUp(e) {
this.keysPressed.delete(e.code);
this.keyHandlers[e.code] && this.keyHandlers[e.code](false);
this.trigger('keyup', e);
}

onKey({ ...handlers }) {
this.keyHandlers = { ...this.keyHandlers, ...handlers };
}
}

Object.assign(ClientInput.prototype, EventSourceMixin);

export default ClientInput;
Loading