Loading of levels is working now

This commit is contained in:
Mal 2023-09-18 22:33:55 +02:00
parent 349792f916
commit aeece9731c
11 changed files with 347 additions and 271 deletions

View File

@ -10,7 +10,7 @@
"name": "Moon",
"tileset": "moon.jpg",
"tiles": 2,
"backgroundColor": "black",
"backgroundImage": null
"backgroundColor": "#000000",
"backgroundImage": "background_earth.jpg"
}
]

236
js/Game.js Normal file
View File

@ -0,0 +1,236 @@
import MrCroc from "./MrCroc.js";
import Gisela from "./Gisela.js";
import RetroArchitecture from "./retro/RetroArchitecture.js";
import Camera from "./Camera.js";
import TextMessageMrCroc from "./ui/TextMessageMrCroc.js";
import TextMessageGisela from "./ui/TextMessageGisela.js";
import UserInterface from "./ui/UserInterface.js";
import Key from "./Key.js";
import Setting from "./Setting.js";
import {EventBus} from "./events/EventBus.js";
import InterfaceEvent from "./events/InterfaceEvent.js";
import FrameRateMeasurer from "./FrameRateMeasurer.js";
export class Game
{
static GAME_SPEED = 1
constructor(level) {
this.level = level;
this.fps = 0;
this.frameDuration = 0;
this.lastRendered = undefined;
this.lastTimestamp = undefined;
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.mrCroc = new MrCroc();
this.gisela = new Gisela();
this.architecture = RetroArchitecture.createFromData(this.level);
const cameraPosition = this.architecture.getStartPosition();
this.camera = new Camera(cameraPosition.x, cameraPosition.y);
this.gameFinished = false;
this.hasPlayerLeftArchitecture = false;
this.textBoxGameStart = new TextMessageMrCroc('Mr. Croc: "Where is Gisela? I have to find her!"', this.context);
this.textBoxGameFinished = new TextMessageGisela(
'Gisela: "Thanks for showing up, Mr. Croc, but I\'m not in danger."',
this.context
);
this.userInterface = new UserInterface();
this.isPaused = true;
this.KeyLeft = new Key('ArrowLeft');
this.KeyRight = new Key('ArrowRight');
this.KeyJump = new Key('Space');
this.KeyLoad = new Key('KeyL');
}
render(timestamp)
{
if (timestamp - this.lastRendered < this.frameDuration) {
return;
}
if (this.gisela.currentAnimation !== 'LOOK_LEFT' && this.mrCroc.position.x < this.gisela.position.x) {
this.gisela.currentAnimation = 'LOOK_LEFT';
} else if (this.gisela.currentAnimation !== 'LOOK_RIGHT' && this.mrCroc.position.x >= this.gisela.position.x) {
this.gisela.currentAnimation = 'LOOK_RIGHT';
}
this.context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.architecture.draw(this.context, this.camera);
this.mrCroc.draw(this.context, this.camera);
this.gisela.draw(this.context, this.camera);
this.userInterface.draw(this.context);
this.lastRendered = timestamp;
}
canBeFinished()
{
return (
!this.gameFinished &&
this.mrCroc.isJumping === false &&
this.architecture.isMovableInsideTargetPosition(this.mrCroc)
);
}
handlePhysics(delta, timestamp)
{
const ceilingHeight = Math.max(
this.architecture.getCeilingHeight(this.mrCroc.getPositionHeadLeft()),
this.architecture.getCeilingHeight(this.mrCroc.getPositionHeadRight()),
);
const groundHeight = Math.min(
this.architecture.getGroundHeight(this.mrCroc.getPositionFootLeft()),
this.architecture.getGroundHeight(this.mrCroc.getPositionFootRight())
);
/* Handle falling */
this.mrCroc.position.y += this.mrCroc.fallSpeed;
this.mrCroc.fallSpeed += this.level.gravity * delta;
/* Handle ground collision */
if (this.mrCroc.position.y > groundHeight && this.mrCroc.fallSpeed > 0) {
this.mrCroc.position.y = groundHeight;
this.mrCroc.fallSpeed = 0;
}
/* Handle ceiling collision */
if (this.mrCroc.position.y - this.mrCroc.getHeight() <= ceilingHeight) {
this.mrCroc.fallSpeed = 0;
this.mrCroc.position.y = ceilingHeight + this.mrCroc.getHeight() + 1;
}
this.handlePlayerMovement(delta, timestamp, groundHeight);
}
updateCamera()
{
this.camera.focusPosition(
this.mrCroc.position.x - this.mrCroc.getWidth() * 0.5,
this.mrCroc.position.y - this.mrCroc.getHeight() * 0.5,
20
);
this.camera.lockCameraIntoBorders();
}
handlePlayerMovement(delta, timestamp, groundHeight)
{
/* Jumping */
if (!this.mrCroc.isJumping && this.mrCroc.fallSpeed === 0 && this.mrCroc.position.y === groundHeight && this.KeyJump.isPressed()) {
this.mrCroc.jump();
} else if (!this.KeyJump.isPressed()) {
this.mrCroc.isJumping = false;
}
/* Movement left and right */
if (!this.hasPlayerLeftArchitecture && this.KeyLeft.isPressed()) {
const lastWallLeft = Math.min(
this.architecture.getWallLeft(this.mrCroc.getPositionHeadLeft()),
this.architecture.getWallLeft(this.mrCroc.getPositionFootLeft())
);
this.mrCroc.moveLeft(timestamp, delta);
if (this.mrCroc.position.x <= lastWallLeft + this.mrCroc.getWidth() * 0.5) {
this.mrCroc.position.x = lastWallLeft + this.mrCroc.getWidth() * 0.5 + 1;
}
} else if (!this.hasPlayerLeftArchitecture && this.KeyRight.isPressed()) {
const lastWallRight = Math.max(
this.architecture.getWallRight(this.mrCroc.getPositionHeadRight()),
this.architecture.getWallRight(this.mrCroc.getPositionFootRight())
);
this.mrCroc.moveRight(timestamp, delta);
if (this.mrCroc.position.x >= lastWallRight - this.mrCroc.getWidth() * 0.5) {
this.mrCroc.position.x = lastWallRight - this.mrCroc.getWidth() * 0.5 - 1;
}
}
if (!this.hasPlayerLeftArchitecture && !this.architecture.isInsideArchitecture(this.mrCroc.position)) {
this.hasPlayerLeftArchitecture = true;
setTimeout(
() => {
this.architecture.setMovableToStartPosition(this.mrCroc);
this.hasPlayerLeftArchitecture = false;
}, 2000
);
}
}
finish()
{
this.gameFinished = true;
this.KeyLeft.pressed = false;
this.KeyRight.pressed = false;
this.KeyJump.pressed = false;
this.lastTimestamp = undefined;
this.lastRendered = undefined;
this.textBoxGameFinished.updateLines(window.innerWidth - 40, this.context);
this.textBoxGameFinished.animate(75);
this.userInterface.addTextBox(this.textBoxGameFinished);
}
init(loopFunction) {
if (this.isChromeBrowser()) {
this.canvas.width = window.innerWidth - 1;
this.canvas.height = window.innerHeight - 1;
}
this.canvas.style.backgroundAttachment = 'fixed';
this.canvas.style.backgroundSize = 'cover';
this.canvas.style.backgroundPosition = 'center center';
if (this.level.getBackgroundImage() !== undefined) {
this.canvas.style.backgroundImage = "url("+ Setting.GRAPHICS_LOCATION + this.level.getBackgroundImage() + ")";
} else {
this.canvas.style.backgroundImage = 'none';
}
this.canvas.style.backgroundColor = this.level.getBackgroundColor();
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
EventBus.addEventListener(
'resize',
function () {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
);
this.textBoxGameStart.animate(75, 1000);
this.textBoxGameStart.show(1000);
this.textBoxGameStart.hide(10000);
this.userInterface.addTextBox(this.textBoxGameStart);
this.camera.borderRight = this.architecture.columns * this.architecture.tileWidth;
this.camera.borderBottom = this.architecture.rows * this.architecture.tileHeight;
this.architecture.setMovableToStartPosition(this.mrCroc);
this.architecture.setMovableToTargetPosition(this.gisela);
EventBus.addEventListener(
InterfaceEvent.FRAME_RATE_MEASURED,
(event) => {
this.isPaused = false;
this.fps = event.frameRate;
this.frameDuration = 1000.0 / this.fps;
window.requestAnimationFrame(loopFunction);
}
);
new FrameRateMeasurer();
}
isChromeBrowser()
{
return navigator.userAgent.match('Chrome') !== null;
}
}

View File

@ -10,6 +10,12 @@ export default class ImageLoader
if (this.numberImagesLoaded === this.images.length) {
window.dispatchEvent(new Event('imagesloaded'));
}
}
isComplete()
{
return this.numberImagesLoaded === this.images.length;
}
getCurrentProgress()
@ -19,14 +25,19 @@ export default class ImageLoader
addImage(imagePath)
{
let image = new Image();
image.src = imagePath;
image.addEventListener(
'load', () => {
this.update();
}
);
this.images.push(imagePath);
}
this.images.push(image);
load()
{
for (const imagePath of this.images) {
let image = new Image();
image.src = imagePath;
image.addEventListener(
'load', () => {
this.update();
}
);
}
}
}

View File

@ -1,11 +1,12 @@
import {EventBus} from "./events/EventBus.js";
export default class Key
{
constructor(name)
{
this.name = name;
this.pressed = false;
window.addEventListener(
EventBus.addEventListener(
'keydown',
(event) => {
if (event.code === this.name) {
@ -13,8 +14,7 @@ export default class Key
}
}
);
window.addEventListener(
EventBus.addEventListener(
'keyup',
(event) => {
if (event.code === this.name) {

25
js/events/EventBus.js Normal file
View File

@ -0,0 +1,25 @@
export class EventBus
{
static listeners = []
static addEventListener(eventName, callback)
{
EventBus.listeners.push({eventName, callback});
window.addEventListener(eventName, callback, false);
}
static dispatchEvent(event)
{
window.dispatchEvent(event);
}
static clear()
{
for (const listener of EventBus.listeners) {
window.removeEventListener(listener.eventName, listener.callback, false);
}
EventBus.listeners = [];
}
}

View File

@ -1,235 +1,14 @@
'use strict';
import Key from "./Key.js";
import MrCroc from "./MrCroc.js";
import RetroArchitecture from "./retro/RetroArchitecture.js";
import Camera from "./Camera.js";
import Gisela from "./Gisela.js";
import Setting from "./Setting.js";
import FrameRateMeasurer from "./FrameRateMeasurer.js";
import GraphicSet from "./GraphicSet.js";
import ImageLoader from "./ImageLoader.js";
import Level from "./Level.js";
import InterfaceEvent from "./events/InterfaceEvent.js";
import UrlParam from "./UrlParam.js";
import UserInterface from "./ui/UserInterface.js";
import TextMessageGisela from "./ui/TextMessageGisela.js";
import TextMessageMrCroc from "./ui/TextMessageMrCroc.js";
import {LoadLevelDialog} from "./ui/LoadLevelDialog.js";
import {EventBus} from "./events/EventBus.js";
import {Game} from "./Game.js";
class Game
{
static GAME_SPEED = 1
constructor(level) {
this.level = level;
this.fps = 0;
this.frameDuration = 0;
this.lastRendered = undefined;
this.lastTimestamp = undefined;
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.mrCroc = new MrCroc();
this.gisela = new Gisela();
this.architecture = RetroArchitecture.createFromData(this.level);
this.camera = new Camera();
this.gameFinished = false;
this.hasPlayerLeftArchitecture = false;
this.textBoxGameStart = new TextMessageMrCroc('Mr. Croc: "Where is Gisela? I have to find her!"', this.context);
this.textBoxGameFinished = new TextMessageGisela(
'Gisela: "Thanks for showing up, Mr. Croc, but I\'m not in danger."',
this.context
);
this.userInterface = new UserInterface();
this.isPaused = false;
this.KeyLeft = new Key('ArrowLeft');
this.KeyRight = new Key('ArrowRight');
this.KeyJump = new Key('Space');
this.KeyLoad = new Key('KeyL');
this.loader = new ImageLoader();
this.loader.addImage(Setting.GRAPHICS_LOCATION + 'mr-croc-walk-right.png');
this.loader.addImage(Setting.GRAPHICS_LOCATION + 'mr-croc-walk-left.png');
this.loader.addImage(Setting.TILESET_LOCATION + GraphicSet[this.level.getTilesetId()].tileset);
this.loader.addImage(Setting.GRAPHICS_LOCATION + 'gisela-right.png');
this.loader.addImage(Setting.GRAPHICS_LOCATION + 'gisela-left.png');
new FrameRateMeasurer();
}
render(timestamp)
{
if (timestamp - this.lastRendered < this.frameDuration) {
return;
}
if (this.gisela.currentAnimation !== 'LOOK_LEFT' && this.mrCroc.position.x < this.gisela.position.x) {
this.gisela.currentAnimation = 'LOOK_LEFT';
} else if (this.gisela.currentAnimation !== 'LOOK_RIGHT' && this.mrCroc.position.x >= this.gisela.position.x) {
this.gisela.currentAnimation = 'LOOK_RIGHT';
}
this.context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.architecture.draw(this.context, this.camera);
this.mrCroc.draw(this.context, this.camera);
this.gisela.draw(this.context, this.camera);
this.userInterface.draw(this.context);
this.lastRendered = timestamp;
}
canBeFinished()
{
return (
!this.gameFinished &&
this.mrCroc.isJumping === false &&
this.architecture.isMovableInsideTargetPosition(this.mrCroc)
);
}
handlePhysics(delta, timestamp)
{
let ceilingHeight = Math.max(
this.architecture.getCeilingHeight(this.mrCroc.getPositionHeadLeft()),
this.architecture.getCeilingHeight(this.mrCroc.getPositionHeadRight()),
);
let groundHeight = Math.min(
this.architecture.getGroundHeight(this.mrCroc.getPositionFootLeft()),
this.architecture.getGroundHeight(this.mrCroc.getPositionFootRight())
);
/* Handle falling */
this.mrCroc.position.y += this.mrCroc.fallSpeed;
this.mrCroc.fallSpeed += this.level.gravity * delta;
/* Handle ground collision */
if (this.mrCroc.position.y > groundHeight && this.mrCroc.fallSpeed > 0) {
this.mrCroc.position.y = groundHeight;
this.mrCroc.fallSpeed = 0;
}
/* Handle ceiling collision */
if (this.mrCroc.position.y - this.mrCroc.getHeight() <= ceilingHeight) {
this.mrCroc.fallSpeed = 0;
this.mrCroc.position.y = ceilingHeight + this.mrCroc.getHeight() + 1;
}
this.handlePlayerMovement(delta, timestamp, groundHeight);
}
updateCamera()
{
this.camera.focusPosition(
this.mrCroc.position.x - this.mrCroc.getWidth() * 0.5,
this.mrCroc.position.y - this.mrCroc.getHeight() * 0.5,
20
);
this.camera.lockCameraIntoBorders();
}
handlePlayerMovement(delta, timestamp, groundHeight)
{
/* Jumping */
if (!this.mrCroc.isJumping && this.mrCroc.fallSpeed === 0 && this.mrCroc.position.y === groundHeight && this.KeyJump.isPressed()) {
this.mrCroc.jump();
} else if (!this.KeyJump.isPressed()) {
this.mrCroc.isJumping = false;
}
/* Movement left and right */
if (!this.hasPlayerLeftArchitecture && this.KeyLeft.isPressed()) {
let lastWallLeft = Math.min(
this.architecture.getWallLeft(this.mrCroc.getPositionHeadLeft()),
this.architecture.getWallLeft(this.mrCroc.getPositionFootLeft())
);
this.mrCroc.moveLeft(timestamp, delta);
if (this.mrCroc.position.x <= lastWallLeft + this.mrCroc.getWidth() * 0.5) {
this.mrCroc.position.x = lastWallLeft + this.mrCroc.getWidth() * 0.5 + 1;
}
} else if (!this.hasPlayerLeftArchitecture && this.KeyRight.isPressed()) {
let lastWallRight = Math.max(
this.architecture.getWallRight(this.mrCroc.getPositionHeadRight()),
this.architecture.getWallRight(this.mrCroc.getPositionFootRight())
);
this.mrCroc.moveRight(timestamp, delta);
if (this.mrCroc.position.x >= lastWallRight - this.mrCroc.getWidth() * 0.5) {
this.mrCroc.position.x = lastWallRight - this.mrCroc.getWidth() * 0.5 - 1;
}
}
if (!this.hasPlayerLeftArchitecture && !this.architecture.isInsideArchitecture(this.mrCroc.position)) {
this.hasPlayerLeftArchitecture = true;
setTimeout(
() => {
this.architecture.setMovableToStartPosition(this.mrCroc);
this.hasPlayerLeftArchitecture = false;
}, 2000
);
}
}
finish()
{
this.gameFinished = true;
this.KeyLeft.pressed = false;
this.KeyRight.pressed = false;
this.KeyJump.pressed = false;
this.lastTimestamp = undefined;
this.lastRendered = undefined;
this.textBoxGameFinished.updateLines(window.innerWidth - 40, this.context);
this.textBoxGameFinished.animate(75);
this.userInterface.addTextBox(this.textBoxGameFinished);
}
init(loopFunction) {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.canvas.style.backgroundAttachment = 'fixed';
this.canvas.style.backgroundSize = 'cover';
this.canvas.style.backgroundPosition = 'center center';
if (GraphicSet[this.level.getTilesetId()].backgroundImage !== null) {
this.canvas.style.backgroundImage = 'url("' + Setting.GRAPHICS_LOCATION + GraphicSet[this.level.getTilesetId()].backgroundImage +'")';
}
this.canvas.style.backgroundColor = this.level.getBackgroundColor();
window.addEventListener(
'resize',
function () {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
);
this.textBoxGameStart.animate(75, 1000);
this.textBoxGameStart.show(1000);
this.textBoxGameStart.hide(10000);
this.userInterface.addTextBox(this.textBoxGameStart);
this.camera.borderRight = this.architecture.columns * this.architecture.tileWidth;
this.camera.borderBottom = this.architecture.rows * this.architecture.tileHeight;
this.architecture.setMovableToStartPosition(this.mrCroc);
this.architecture.setMovableToTargetPosition(this.gisela);
window.addEventListener(
InterfaceEvent.FRAME_RATE_MEASURED,
(event) => {
this.fps = event.frameRate;
this.frameDuration = 1000.0 / this.fps;
window.requestAnimationFrame(loopFunction);
}
);
}
}
function mainLoop(timestamp)
{
@ -261,8 +40,8 @@ function mainLoop(timestamp)
window.requestAnimationFrame(mainLoop);
}
dialog.onLoad = (data) => {
game = new Game(Level.createFromJson(data));
game.init();
EventBus.clear();
loadLevel(Level.createFromJson(data));
}
game.isPaused = true;
@ -271,6 +50,34 @@ function mainLoop(timestamp)
window.requestAnimationFrame(mainLoop);
}
function loadLevel(level)
{
const loader = new ImageLoader();
loader.addImage(Setting.GRAPHICS_LOCATION + 'mr-croc-walk-right.png');
loader.addImage(Setting.GRAPHICS_LOCATION + 'mr-croc-walk-left.png');
loader.addImage(Setting.GRAPHICS_LOCATION + 'gisela-right.png');
loader.addImage(Setting.GRAPHICS_LOCATION + 'gisela-left.png');
loader.addImage(Setting.GRAPHICS_LOCATION + 'gisela-left.png');
for (const graphicSet of GraphicSet) {
loader.addImage(Setting.TILESET_LOCATION + graphicSet.tileset);
if (graphicSet.backgroundImage !== null) {
loader.addImage(Setting.GRAPHICS_LOCATION + graphicSet.backgroundImage);
}
}
loader.load();
EventBus.addEventListener(
'imagesloaded',
() => {
game = new Game(level);
game.init(mainLoop);
}
);
}
const LEVEL = [
'level01.json',
'moon.json',
@ -278,19 +85,13 @@ const LEVEL = [
'terrain8.json',
];
let game;
const urlGetter = new UrlParam();
const levelIndex = urlGetter.getInt('level');
const level = Level.createFromFile(
Setting.LEVELS_LOCATION + LEVEL[levelIndex < 0 || levelIndex >= LEVEL.length ? 0 : levelIndex]
loadLevel(
Level.createFromFile(
Setting.LEVELS_LOCATION + LEVEL[levelIndex < 0 || levelIndex >= LEVEL.length ? 0 : levelIndex]
)
);
let game = new Game(level);
window.addEventListener(
'imagesloaded',
() => {
game.init(mainLoop);
}
);

View File

@ -204,10 +204,10 @@ export default class RetroArchitecture
draw(context, camera = new Camera())
{
let viewX = parseInt(Math.floor(Math.max(0, camera.position.x) / this.tileWidth));
let viewWidth = parseInt(Math.min(Math.ceil(camera.width), this.columns));
let viewY = parseInt(Math.floor(Math.max(0, camera.position.y)) / this.tileHeight);
let viewHeight = parseInt(Math.min(Math.ceil(camera.height), this.rows));
const viewX = parseInt(Math.floor(Math.max(0, camera.position.x) / this.tileWidth));
const viewWidth = parseInt(Math.min(Math.ceil(camera.width), this.columns));
const viewY = parseInt(Math.floor(Math.max(0, camera.position.y)) / this.tileHeight);
const viewHeight = parseInt(Math.min(Math.ceil(camera.height), this.rows));
for (let y = viewY; y < viewHeight; y++) {
for (let x = viewX; x < viewWidth; x++) {
@ -235,6 +235,11 @@ export default class RetroArchitecture
);
}
getStartPosition()
{
return new GeometryPoint(this.startX * this.tileWidth, this.startY * this.tileHeight);
}
static createFromData(level)
{
let graphicSet = GraphicSet[level.getTilesetId()];

View File

@ -82,7 +82,7 @@ export default class RetroSprite
canvasTemp.width = this.image.width * this.scale;
canvasTemp.height = this.image.height * this.scale;
let contextTemp = canvasTemp.getContext('2d');
let contextTemp = canvasTemp.getContext('2d', {willReadFrequently: true});
contextTemp.drawImage(this.image, 0, 0);
this.canvas.width = this.image.width * this.scale;

View File

@ -7,13 +7,8 @@ export class LoadLevelDialog extends Dialog
this.setMessage('Level laden');
this.fileInput = this.createFileInput(['json']);
this.onClose = () => {};
this.onLoad = () => {};
this.buttonLoad = this.createButton('Laden');
this.buttonLoad.addEventListener(
'click',
this.fileInput.addEventListener(
'change',
() => {
if (this.fileInput.files.length === 0) {
return;
@ -29,7 +24,9 @@ export class LoadLevelDialog extends Dialog
)
reader.readAsBinaryString(this.fileInput.files[0]);
}
);
)
this.onClose = () => {};
this.onLoad = () => {};
this.buttonCancel = this.createButton('Abbrechen');
this.buttonCancel.addEventListener(

View File

@ -187,6 +187,7 @@ export default class Terrain
let tileset = new Tileset(levelData.tileset);
let terrain = new Terrain(tileset, levelData.columns, levelData.rows, graphicSet.backgroundColor);
terrain.backgroundImage = graphicSet.backgroundImage ?? undefined;
for (let y = 0; y < levelData.rows; y++) {
for (let x = 0; x < levelData.columns; x++) {