Tilorswift levels can now be loaded into the running game

This commit is contained in:
Mal 2023-09-17 14:18:21 +02:00
parent 8f087d3dd3
commit 593d323aff
11 changed files with 348 additions and 204 deletions

View File

@ -17,6 +17,7 @@
} }
</style> </style>
<link rel="shortcut icon" type="image/png" href="favicon.png"> <link rel="shortcut icon" type="image/png" href="favicon.png">
<link rel="stylesheet" type="text/css" href="tilorswift/style.css">
<script type="module" src="js/module.js"></script> <script type="module" src="js/module.js"></script>
</head> </head>
<body> <body>

View File

@ -84,4 +84,15 @@ export default class Level
return level; return level;
} }
static createFromJson(json)
{
const data = JSON.parse(json);
const terrain = Terrain.createFromJson(data);
const level = new Level(terrain);
level.setGravity(data.gravity);
return level;
}
} }

View File

@ -44,15 +44,15 @@ export default class UrlParam
getInt(name) getInt(name)
{ {
let value = parseInt(this.get(name)); const value = parseInt(this.get(name));
return isNaN(value) ? undefined : value; return isNaN(value) ? 0 : value;
} }
getFloat(name) getFloat(name)
{ {
let value = parseFloat(this.get(name)); const value = parseFloat(this.get(name));
return isNaN(value) ? undefined : value; return isNaN(value) ? 0.0 : value;
} }
} }

View File

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

42
js/ui/LoadLevelDialog.js Normal file
View File

@ -0,0 +1,42 @@
import Dialog from "../../tilorswift/js/dialog/Dialog.js";
export class LoadLevelDialog extends Dialog
{
constructor() {
super();
this.setMessage('Level laden');
this.fileInput = this.createFileInput(['json']);
this.onClose = () => {};
this.onLoad = () => {};
this.buttonLoad = this.createButton('Laden');
this.buttonLoad.addEventListener(
'click',
() => {
if (this.fileInput.files.length === 0) {
return;
}
const reader = new FileReader();
reader.addEventListener(
'load',
(event) => {
this.onClose();
this.onLoad(event.target.result);
}
)
reader.readAsBinaryString(this.fileInput.files[0]);
}
);
this.buttonCancel = this.createButton('Abbrechen');
this.buttonCancel.addEventListener(
'click',
() => {
this.onClose();
}
);
}
}

View File

@ -4,11 +4,12 @@ import UserInterfaceElement from "./UserInterfaceElement.js";
export default class TextBox extends UserInterfaceElement export default class TextBox extends UserInterfaceElement
{ {
constructor(text, width, context) constructor(text, width, context, paused = false)
{ {
super(); super();
this.text = text; this.text = text;
this.width = width; this.width = width;
this.paused = paused;
this.colorText = 'red'; this.colorText = 'red';
this.colorShadow = 'black'; this.colorShadow = 'black';
this.colorBorder = 'black'; this.colorBorder = 'black';

View File

@ -2,9 +2,10 @@ import TextAlignment from "./TextAlignment.js";
export default class TextLine export default class TextLine
{ {
constructor(text) constructor(text, paused)
{ {
this.text = text; this.text = text;
this.paused = paused;
this.estimatedTextWidth = null; this.estimatedTextWidth = null;
this.colorText = 'red'; this.colorText = 'red';
this.colorShadow = 'black'; this.colorShadow = 'black';
@ -24,6 +25,10 @@ export default class TextLine
let process = setInterval( let process = setInterval(
() => { () => {
if (this.paused) {
return;
}
this.chars++; this.chars++;
if (this.chars === this.text.length) { if (this.chars === this.text.length) {

View File

@ -3,8 +3,8 @@ import GeometryPoint from "../geometry/GeometryPoint.js";
export default class TextMessage extends TextBox export default class TextMessage extends TextBox
{ {
constructor(text, context) { constructor(text, context, paused = false) {
super(text, window.innerWidth - 40, context); super(text, window.innerWidth - 40, context, paused);
this.update(); this.update();
this.context = context; this.context = context;
} }

View File

@ -126,8 +126,31 @@ export default class Dialog
return htmlElement; return htmlElement;
} }
createFileInput(types = [])
{
let input = document.createElement('input');
input.type = 'file';
if (types.length > 0) {
for (const t in types) {
types[t] = '.' + types[t]
}
input.accept = types.join(', ');
}
this.inputAreaElement.appendChild(input);
return input;
}
setMessage(message) setMessage(message)
{ {
this.messageElement.innerText = message; this.messageElement.innerText = message;
} }
close()
{
this.htmlElement.remove();
}
} }

View File

@ -236,6 +236,10 @@ body {
margin-bottom: 20px; margin-bottom: 20px;
} }
input[type="file"] {
margin-bottom: 20px;
}
.dialog-button { .dialog-button {
padding: 5px 20px; padding: 5px 20px;
background-color: grey; background-color: grey;