-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.ts
41 lines (37 loc) · 1.08 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
import * as readline from "node:readline/promises";
import { match, P } from "ts-pattern";
import { read, Move } from "./model/move";
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 userMove = read(
await rl.question(
"Wanna play? Your move (0: Rock, 1: Paper, 2: Scissors) \n"
)
);
output.write(`You chose: ${userMove}\nComputer chosed: ${computerMove}\n`);
output.write(
"The result is... " + playLogic(userMove, computerMove) + " !\n"
);
rl.close();
}