-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
98 lines (83 loc) · 2.57 KB
/
game.js
File metadata and controls
98 lines (83 loc) · 2.57 KB
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
90
91
92
93
94
95
96
97
98
// Render Board Logic
function renderBoard() {
const boardBlocks = [
[20, 19, 18, 17],
[16, 15, 14, 13],
[9, 10, 11, 12],
[8, 7, 6, 5],
[1, 2, 3, 4]
]
const snakes = {
'7': '3',
'11': '2',
'14': '5',
'17': '1'
}
const ladders = {
'6': '13',
'9': '15'
}
const boardContent = boardBlocks.map((blockRow) =>
`<div class="row">
${
blockRow.map((blockValue) => {
const snakeTail = snakes[blockValue];
const ladderHead = ladders[blockValue];
return `
<div
class="col ${snakeTail ? 'snake' : ''} ${ladderHead ? 'ladder' : ''}"
data-block="${blockValue}"
${ snakeTail ? `data-snake-tail="${snakeTail}"` : ''}
${ ladderHead ? `data-ladder-head="${ladderHead}"` : ''}
>
<b>${blockValue}</b>
${snakeTail ? `<br/>🐍 to ${snakeTail}` : ''}
${ladderHead ? `<br/>🪜 to ${ladderHead}` : ''}
</div>
`
}).join('')
}
</div>`
).join('')
document.querySelector('#board').innerHTML = boardContent;
}
// Roll Dice Logic
function setPlayerPosition(blockValue) {
// Wins
if (blockValue >= 20) {
alert('Hurray!🎉 You won');
setPlayerPosition(1);
return;
}
const currentPlayerEl = document.querySelector('.col.player');
if (currentPlayerEl) {
currentPlayerEl.classList.remove('player');
}
const newPlayerEl = document.querySelector(`.col[data-block="${blockValue}"]`);
newPlayerEl.classList.add('player');
// Check if the new position where we moved has a snake
if (newPlayerEl.dataset.snakeTail) {
// If it has snake, set position to the tail of snake
alert('Oops!!🤯 You were eaten by the snake');
setPlayerPosition(parseInt(newPlayerEl.dataset.snakeTail))
}
if (newPlayerEl.dataset.ladderHead) {
alert('Yay! You got the ladder');
setPlayerPosition(parseInt(newPlayerEl.dataset.ladderHead));
}
}
function getPlayerPosition() {
const currentPlayerEl = document.querySelector('.col.player');
const currentPlayerPosition = currentPlayerEl.dataset.block;
return parseInt(currentPlayerPosition);
}
function rollDice() {
const diceNumber = Math.round(Math.random() * (6 - 1) + 1);
document.querySelector('#dice').innerText = diceNumber;
const currentPosition = getPlayerPosition();
setPlayerPosition(currentPosition + diceNumber);
}
// Main
renderBoard();
setPlayerPosition(1);
document.querySelector('#roll-dice').addEventListener('click', rollDice);