Skip to content

Commit

Permalink
add message bar
Browse files Browse the repository at this point in the history
  • Loading branch information
soryy708 committed May 22, 2023
1 parent 2672b31 commit 4246b2b
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/front/game/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Cross } from './piece/cross';
import { Nought } from './piece/nought';
import { GamePiece } from './piece/interface';
import { WinChecker } from './win';
import { showMessageBar } from './message-bar';

type Player = 'player1' | 'player2';

Expand Down Expand Up @@ -93,7 +94,7 @@ export class Game {
private advanceTurn(): void {
const win = this.winChecker.getWinner();
if (win) {
console.log(`${this.currentPlayer} wins`);
showMessageBar(`${this.currentPlayer} wins!`);
this.reset();
return;
}
Expand Down
60 changes: 60 additions & 0 deletions src/front/game/message-bar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const elementId = 'message-bar';

let timeout: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any

export function showMessageBar(text: string): void {
assertElement();
setContent(text);
setTimeout(() => {
showElement();
scheduleHiding();
}, 1);
}

function assertElement(): void {
const exists = getElement();
if (!exists) {
const node = document.createElement('div');
node.id = elementId;
node.style.position = 'fixed';
node.style.left = '0';
node.style.bottom = '0';
node.style.width = '100%';
node.style.padding = '0.5em';
node.style.textAlign = 'center';
node.style.opacity = '0';
node.style.transition = 'opacity 0.3s';
node.style.color = '#fff';
node.style.fontFamily = 'sans-serif';
node.style.fontSize = '2em';
node.style.backgroundColor = '#202020';
node.style.boxShadow = '0 -1px 8px #000';
document.body.append(node);
}
}

function getElement(): HTMLDivElement {
return document.getElementById(elementId) as HTMLDivElement;
}

function setContent(text: string): void {
getElement().innerText = text;
}

function showElement(): void {
getElement().style.opacity = '1';
}

function scheduleHiding(): void {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(() => {
hideElement();
}, 5000);
}

function hideElement(): void {
getElement().style.opacity = '0';
}

0 comments on commit 4246b2b

Please sign in to comment.