-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.ts
55 lines (49 loc) · 1.52 KB
/
game.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import * as readline from "node:readline/promises";
import { match, P } from "ts-pattern";
import { read, Move } from "./model/move";
import { lastGame, logRes, closeDB } from "./sql/db";
import { results } from "./model/result";
export function generateComputerMove() {
return read(String(Math.round(Math.random() * 2)));
}
export function playLogic(userMove: Move, computerMove: Move) {
return match([userMove, computerMove])
.with(
["Rock", "Scissors"],
["Scissors", "Paper"],
["Paper", "Rock"],
() => "You Win!!!"
)
.with(
P.when(() => userMove === computerMove),
() => "It's a Draw!"
)
.otherwise(() => "You lose :< ");
}
export async function play(
input: NodeJS.ReadableStream,
output: NodeJS.WritableStream
) {
const rl = readline.createInterface({ input, output });
const computerMove = generateComputerMove();
const lastG = results.safeParse(await lastGame());
if (lastG.success) {
rl.write("Our last game timestamp is : " + lastG.data.log_game + "\n");
rl.write(
"and the game finished with this result : " + lastG.data.result + "\n"
);
} else {
rl.write("Welcome to the best RPS game ever! \n");
}
const userMove = read(
await rl.question(
"Wanna play? Your move (0: Rock, 1: Paper, 2: Scissors) \n"
)
);
const res = playLogic(userMove, computerMove);
logRes(res);
rl.write(`You chose: ${userMove}\nComputer chose: ${computerMove}\n`);
rl.write("The result is... " + res + " !\n");
rl.close();
closeDB();
}