강동현

WordDatabase 구현

import { assert } from "console";
const Database = require("better-sqlite3");
export class WordDatabase {
private words: string[] = [];
constructor(db_path: string) {
const db = new Database("./database.db", {
readonly: true,
});
db.prepare(`SELECT * FROM words`)
.all()
.forEach((w: any) => {
this.words.push(w["word"]);
});
if (this.words.length < 3) {
throw new Error("Not enough words.");
}
}
public getWords(count: number): string[] {
let words: string[] = [];
let temp = this.words.slice();
for (let i = 0; i < count; i++) {
const idx = Math.floor(Math.random() * temp.length);
words.push(temp[idx]);
temp.splice(idx, 1);
}
return words;
}
}
......@@ -228,7 +228,7 @@ export class Game {
}
private pickWords(): string[] {
return ["장난감", "백화점", "파티"];
return this.room.roomManager.wordDatabase.getWords(3);
}
private startTimer(timeLeftMillis: number): void {
......
{
"dependencies": {
"@types/better-sqlite3": "^5.4.1",
"@types/express": "^4.17.11",
"@types/node": "^15.3.1",
"@types/socket.io": "^3.0.2",
"@types/socket.io-client": "^3.0.0",
"@types/uuid": "^8.3.0",
"better-sqlite3": "^7.4.1",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"runtypes": "^6.3.0",
......
import { RoomDescription } from "../../common/dataType";
import { WordDatabase } from "../database/WordDatabase";
import { User } from "../user/User";
import { Room } from "./Room";
export class RoomManager {
private rooms: Map<string, Room>;
public wordDatabase: WordDatabase;
constructor() {
this.rooms = new Map<string, Room>();
this.wordDatabase = new WordDatabase("./database.db");
}
public create(name: string, maxConnections: number, admin?: User): Room {
......
import { expect } from "chai";
import { WordDatabase } from "../database/WordDatabase";
describe("단어 데이터베이스", () => {
it("랜덤한 단어를 반환합니다", () => {
const wordDatabase = new WordDatabase("./database.db");
expect(wordDatabase.getWords(3).length).eq(3);
});
});
This diff is collapsed. Click to expand it.