강동현

WordDatabase 구현

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