-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtn.ts
More file actions
302 lines (245 loc) · 7.58 KB
/
tn.ts
File metadata and controls
302 lines (245 loc) · 7.58 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import * as readline from 'readline'
enum Movement
{
Up = 'up',
Left = 'left',
Right = 'right',
Down = 'down'
}
type Difficulty = 'easy' | 'medium' | 'high' | 'custom'
type Position = [number, number]
type Eaten = keyof IPowerUps | 'apple'
type Range = 'exact' | 'expanded'
interface IIcons
{
target?: string
body?: string
backgorund?: string
magnet?: string
slowmo?: string
bonus?: string
}
interface IOptions
{
updateTime?: number
scorePerApple?: number
difficulty?: Difficulty | null
icons?: IIcons
powerUps?: IPowerUps
expandedRange?: number
board?: IBoard
}
interface ISpeeds
{
easy: number
medium: number
high: number
}
interface IPowerUps
{
magnet: { enable: boolean, probability: number }
slowmo: { enable: boolean, probability: number }
bonus: { enable: boolean, probability: number }
}
interface IPowerUp
{
position: Position
type: keyof IPowerUps
}
interface IBoard
{
width: number
height: number
}
export class Snake
{
private board: IBoard = { height: 20, width: 20 }
private snake: Position[] = [[10, 10]]
private apple: Position = this.getRandomIndex()
private direction: Position = [0, -1]
private updateTime: number = 0
private score: number = 0
private scorePerApple: number = 5
private difficulty: Difficulty = 'easy'
private speeds: ISpeeds = { easy: 1000, medium: 250, high: 70 }
private icons: IIcons = { backgorund: '⬜️', body: '🐍', target: '🍎', bonus: '🍐', magnet: '🧲', slowmo: '🧊' }
private powerUps: IPowerUps = { magnet: { enable: false, probability: 0.4 }, slowmo: { enable: false, probability: 0.2 }, bonus: { enable: false, probability: 0.5 } }
private powerUpsOnBoard: IPowerUp[] = []
private range: Range = 'exact'
private expandedRange: number = 1
private intervalId: Timer | null = null
constructor()
{ }
initialize(options?: IOptions)
{
console.clear()
this.board = options?.board || this.board
this.expandedRange = options?.expandedRange || this.expandedRange
this.icons = { ...this.icons, ...(options?.icons || this.icons) }
this.powerUps = options?.powerUps || this.powerUps
this.scorePerApple = options?.scorePerApple || this.scorePerApple
this.difficulty = options?.difficulty || this.difficulty
this.updateTime = this.difficulty !== 'custom'
? this.speeds[this.difficulty]
: options?.updateTime
?? 1000
readline.emitKeypressEvents(process.stdin)
if (process.stdin.isTTY) process.stdin.setRawMode(true)
process.stdin.on('keypress', (_, key) =>
{
switch (key.name)
{
case Movement.Up:
if (this.direction[1] !== 1 || this.snake.length === 1) this.direction = [0, -1]
break
case Movement.Down:
if (this.direction[1] !== -1 || this.snake.length === 1) this.direction = [0, 1]
break
case Movement.Left:
if (this.direction[0] !== 1 || this.snake.length === 1) this.direction = [-1, 0]
break
case Movement.Right:
if (this.direction[0] !== -1 || this.snake.length === 1) this.direction = [1, 0]
break
case 'c':
if (key.ctrl) process.exit()
break
}
})
this.intervalId = setInterval(() => this.update(), this.updateTime)
}
update()
{
const head = this.snake[0].slice() as Position
head[0] = (head[0] + this.direction[0] + this.board.width) % this.board.width
head[1] = (head[1] + this.direction[1] + this.board.height) % this.board.height
for (let i = 1; i < this.snake.length; i++)
{
if (this.snake[i][0] === head[0] && this.snake[i][1] === head[1])
{
console.log('¡You Lose!')
process.exit()
}
}
const eatenApple = this.isInRange(this.apple) ? 'apple' : undefined
const eatenPowerUp = this.powerUpsOnBoard.find((powerUp) => this.isInRange(powerUp.position))?.type
if (eatenApple) this.onEat(eatenApple)
else if (eatenPowerUp) this.onEat(eatenPowerUp)
else this.snake.pop()
this.snake.unshift(head)
this.draw()
}
onEat(eaten?: Eaten)
{
const oldBackgroundIcon = this.icons.backgorund
const oldScorePerApple = this.scorePerApple
if (eaten !== 'apple') this.deletePowerUp(eaten as keyof IPowerUps)
switch (eaten)
{
case 'apple':
this.score += this.scorePerApple
this.apple = this.getRandomIndex()
const random = Math.random()
for (const powerUpType of Object.keys(this.powerUps) as Array<keyof IPowerUps>)
{
const powerUp = this.powerUps[powerUpType]
if (powerUp.enable && random < powerUp.probability) this.addPowerUp(powerUpType)
}
break
case 'magnet':
this.range = 'expanded'
setTimeout(() =>
{
this.range = 'exact'
}, 2000)
break
case 'slowmo':
clearInterval(this.intervalId as Timer)
this.intervalId = setInterval(() => this.update(), this.updateTime + 200)
setTimeout(() =>
{
clearInterval(this.intervalId as Timer)
this.intervalId = setInterval(() => this.update(), this.updateTime)
}, 2000)
break
case 'bonus':
const intervalId = setInterval(() =>
{
this.icons.backgorund = this.icons.backgorund === '🟦' ? '⬜' : '🟦'
this.scorePerApple = 15
this.draw()
}, this.updateTime)
setTimeout(() =>
{
clearInterval(intervalId)
this.icons.backgorund = oldBackgroundIcon
this.scorePerApple = oldScorePerApple
this.draw()
}, 2000)
break
default:
break
}
}
addPowerUp(type: keyof IPowerUps)
{
const existingPowerUp = this.powerUpsOnBoard
.find((powerUp) => powerUp.type === type)
if (existingPowerUp) return
const position = this.getRandomIndex()
this.powerUpsOnBoard.push({ position, type })
}
deletePowerUp(type: keyof IPowerUps)
{
this.powerUpsOnBoard = this.powerUpsOnBoard.filter((powerUp) => powerUp.type !== type)
}
getRandomIndex()
{
return [Math.floor(Math.random() * this.board.width), Math.floor(Math.random() * this.board.height)] as Position
}
isInRange(position: Position): boolean
{
if (this.range === 'exact')
{
return this.snake[0][0] === position[0] && this.snake[0][1] === position[1]
}
else if (this.range === 'expanded')
{
const [x, y] = this.snake[0]
return Math.abs(x - position[0]) <= this.expandedRange && Math.abs(y - position[1]) <= this.expandedRange
}
return false
}
draw()
{
let board = ''
for (let i = 0; i < this.board.height; i++)
{
let row = ''
for (let j = 0; j < this.board.width; j++)
{
let icon = this.icons.backgorund
if (this.apple[0] === j && this.apple[1] === i)
icon = this.icons.target
const powerUp = this.powerUpsOnBoard.find((powerUp) => powerUp.position[0] === j && powerUp.position[1] === i)
if (powerUp) icon = this.icons[powerUp.type]
const snakePart = this.snake.find((part) => part[0] === j && part[1] === i)
if (snakePart) icon = this.icons.body
row += icon
}
board += row + '\n'
}
process.stdout.write('\x1b[H')
process.stdout.write(board + '\n')
console.log('Difficulty:', this.difficulty.charAt(0).toUpperCase() + this.difficulty.slice(1))
console.log('Score:', this.score)
}
}
const snake = new Snake()
const options: IOptions =
{
scorePerApple: 8,
difficulty: 'high',
icons: { backgorund: '⬛', body: '🗿' }
}
snake.initialize(options)