-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDiceMock.js
89 lines (73 loc) · 1.97 KB
/
DiceMock.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Game params
const MIN_BET = 1
const MAX_BET = 10000
const MAX_PAYOUT = 990000
const BALANCE = 100000000
const ALL_RANGE = 100.0 // total range of possible dice numbers
const HOUSE_EDGE = 0.01 // casino's house edge
function randomizeInteger(min, max) {
if (max == null) {
max = min == null ? Number.MAX_SAFE_INTEGER : min
min = 0
}
min = Math.ceil(min) // inclusive min
max = Math.floor(max) // exclusive max
if (min > max - 1) {
throw new Error('Incorrect arguments.')
}
return min + Math.floor((max - min) * Math.random())
}
const checkBet = deposit => {
if (deposit < MIN_BET) {
throw new Error('deposit less than min bet')
}
if (deposit > MAX_BET) {
throw new Error('deposit greater than max bet')
}
}
const checkNumber = number => {
if (number < 0) {
throw new Error('number should be more than 0')
}
if (number > ALL_RANGE) {
throw new Error('number should be less than ' + ALL_RANGE)
}
}
const getWinCoefficient = num => {
return (ALL_RANGE / (ALL_RANGE - num)) * (1 - HOUSE_EDGE)
}
const getWinPayout = (bet, num) => {
const result = bet * getWinCoefficient(num)
return result < MAX_PAYOUT ? result : MAX_PAYOUT
}
const delay = (min, max) => new Promise((resolve) => setTimeout(resolve, randomizeInteger(min, max)))
export class DiceMock {
init() {
return {
balance: BALANCE,
betMin: MIN_BET,
betMax: MAX_BET,
maxPayout: MAX_PAYOUT,
}
}
async roll(bet, number) {
checkBet(bet)
checkNumber(number)
const randomNumber = randomizeInteger(ALL_RANGE)
const profit = getWinPayout(bet, number)
const isWin = randomNumber >= number
await delay(1200, 2000) // simulate network latency for realism
return {
randomNumber,
profit: isWin ? profit : profit * -1,
isWin,
}
}
emit(event, params) {
console.log('to frontend event', { event, params })
return Promise.resolve()
}
getBalance() {
return Promise.resolve(BALANCE)
}
}