Move messages to Log class, use binding

This commit is contained in:
Tobias Berger 2021-09-27 13:25:44 +02:00
parent 2dbca10f6a
commit 79edd639c7
4 changed files with 34 additions and 20 deletions

View file

@ -2,42 +2,40 @@
import { Message, MessageType } from "../shark/Message";
import { SharkGame } from "../shark/SharkGame";
export function addMessage(
export let messages: Message[];
function addMessage(
message: string,
type: MessageType = MessageType.message
): void {
SharkGame.messages = [
...SharkGame.messages.slice(
-Math.max(...SharkGame.Settings.logLength.options)
),
new Message(message, type),
];
messageType: MessageType = MessageType.message
) {
messages = [...messages, new Message(message, messageType)];
}
$: logLength = SharkGame.Settings.logLength.current;
$: displaymessages = [...SharkGame.messages].slice(-logLength).reverse();
$: displaymessages = messages.slice(-logLength).reverse();
</script>
<div id="log">
<button
on:click={() => {
addMessage("message" + SharkGame.messages.length);
}}>Add Test Message</button
addMessage("message" + messages.length);
}}>Add Message</button
>
<button
on:click={() => {
addMessage("warn" + SharkGame.messages.length, MessageType.warning);
}}>Add Test Warning</button
addMessage("warn" + messages.length, MessageType.warning);
}}>Add Warning</button
>
<button
on:click={() => {
addMessage("error" + SharkGame.messages.length, MessageType.error);
}}>Add Test Error</button
addMessage("error" + messages.length, MessageType.error);
}}>Add Error</button
>
<button
on:click={() => {
Message.even = true;
SharkGame.messages = [new Message("Log cleared.")];
messages = [];
addMessage("Log cleared");
}}>Clear log</button
>
<ol>

View file

@ -1,4 +1,5 @@
<script lang="ts">
import { SharkGame } from "../shark/SharkGame";
import Log from "./Log.svelte";
import ResourceTable from "./ResourceTable.svelte";
</script>
@ -6,7 +7,7 @@
<main>
<div id="left-column">
<ResourceTable />
<Log />
<Log bind:messages={SharkGame.Log.messages} />
</div>
</main>

15
src/shark/Log.ts Normal file
View file

@ -0,0 +1,15 @@
import type { Message } from "./Message";
import { SharkGame } from "./SharkGame";
import { StaticClass } from "./StaticClass";
export class Log extends StaticClass {
static #messages: Message[] = [];
static get messages(): Message[] {
return this.#messages;
}
static set messages(messages: Message[]) {
this.#messages = messages.slice(
-Math.max(...SharkGame.Settings.logLength.options)
);
}
}

View file

@ -1,4 +1,4 @@
import { Message } from "./Message";
import { Log } from "./Log";
import { Settings } from "./Settings";
import { StaticClass } from "./StaticClass";
@ -54,7 +54,7 @@ export class SharkGame extends StaticClass {
static title: string;
static readonly Settings = Settings;
static messages: Message[] = [new Message("Welcome to Sharg!")];
static readonly Log = Log;
static init(): void {
for (const setting of Object.values(Settings)) {