-
Notifications
You must be signed in to change notification settings - Fork 1
/
Engine.swift
327 lines (256 loc) · 8.56 KB
/
Engine.swift
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//
// Engine.swift
// Tetris Engine
//
// Created by Martin Kiss on 16 Jan 2017.
// https://github.com/Tricertops/TetrisEngine
//
// The MIT License (MIT)
// Copyright © 2017 Martin Kiss
//
import Foundation
public final class Engine {
public let width: Int
public let height: Int
public init(width: Int, height: Int, interval: TimeInterval) {
assert(width >= 4)
assert(height >= 10)
self.width = width
self.height = height
initialInterval = interval
board = Board(width: width, height: height + 5)
currentBlock = Block(shape: .T)
nextBlock = Block(shape: .T)
state = .initialized
}
public internal (set) var score: Int = 0
public let initialInterval: TimeInterval
public var interval: TimeInterval {
// Decrease asymptotically to zero.
// Half of the initial time is around score 70, quarter around 210.
let exponent = 1 / (Double(score) / 100 + 1)
return initialInterval * pow(2, exponent) - 1
}
public enum State {
case initialized
case running
case paused
case stopped
}
public internal(set) var state: State
public func start() {
resetState()
callback?(.startGame)
callback?(.newBlock)
state = .running
scheduleTick()
}
public func pause() {
cancelTick()
state = .paused
}
public func resume() {
scheduleTick()
state = .running
}
public func stop() {
cancelTick()
state = .stopped
}
public func moveLeft() {
if state != .running { return }
if currentBlock.canMoveLeft(in: board) {
currentBlock.moveLeft()
callback?(.moveLeft)
}
}
public func moveRight() {
if state != .running { return }
if currentBlock.canMoveRight(in: board) {
currentBlock.moveRight()
callback?(.moveRight)
}
}
public func drop(in time: TimeInterval = 0) {
if state != .running { return }
cancelTick()
var distance = 0
while currentBlock.isFalling && currentBlock.canFall(in: board) {
currentBlock.fall()
distance += 1
}
callback?(.drop(by: distance))
scheduleTick(in: time)
}
public func rotate() {
if state != .running { return }
if currentBlock.isFalling {
if currentBlock.rotate(in: board) {
callback?(.rotate)
}
}
}
public internal(set) var currentBlock: Block {
willSet {
let oldBlock = currentBlock
if oldBlock.isFalling {
for position in oldBlock.absolutePositions {
board.set(cell: .empty, at: position)
}
}
}
didSet {
let newBlock = currentBlock
let cell: Cell = newBlock.cell
for position in newBlock.absolutePositions {
board.set(cell: cell, at: position)
}
}
}
public internal(set) var nextBlock: Block
public func cellAt(x: Int, y: Int) -> Cell {
return board.cell(at: Position(x: x, y: y))
}
public var isGameOver: Bool {
return board.isFrozen(above: height)
}
public var shouldContinueAfterRestoration: Bool {
return isGameOver.not && blockCount > 0
}
public enum Event {
case startGame
case newBlock
case fall
case drop(by: Int)
case moveLeft
case moveRight
case rotate
case freeze
case completed(lines: IndexSet)
case gameOver
}
public typealias Callback = (Event) -> Void
public var callback: Callback?
var timer: Timer?
var dateStarted: Date = .distantFuture
var recentShapes: [Block.Shape] = []
var board: Board
var blockCount: Int = 0
}
extension Engine {
func resetState() {
score = 0
blockCount = 0
board.clear()
recentShapes = []
dateStarted = Date()
currentBlock = generateNextBlock().placed(above: height, in: board)
nextBlock = generateNextBlock()
}
func scheduleTick(in time: TimeInterval? = nil) {
cancelTick()
let interval = time ?? self.interval
let date = Date(timeIntervalSinceNow: interval)
timer = Timer(fire: date, interval: interval, repeats: no) {
[unowned self] _ in
self.tick()
}
RunLoop.main.add(timer!, forMode: .common)
}
func cancelTick() {
timer?.invalidate()
timer = nil
}
func tick() {
assert(state == .running)
cancelTick()
if currentBlock.canFall(in: board) {
currentBlock.fall()
callback?(.fall)
scheduleTick()
}
else if case .falling = currentBlock.cell {
currentBlock.makeFrozen()
blockCount += 1
callback?(.freeze)
let completed = board.findCompletedLines()
if completed.count > 0 {
board.remove(lines: completed)
score += completed.count
callback?(.completed(lines: completed))
}
if isGameOver {
callback?(.gameOver)
stop()
}
else {
scheduleTick()
}
}
else {
currentBlock = nextBlock.placed(above: height, in: board)
nextBlock = generateNextBlock()
callback?(.newBlock)
tick()
}
}
func generateNextBlock() -> Block {
var shapes = Block.Shape.all
for recent in recentShapes {
let index = shapes.firstIndex(of: recent)!
shapes.remove(at: index)
}
let shape = shapes.random()
recentShapes.append(shape)
let memory = 3
let excess = recentShapes.count - memory
if excess > 0 {
recentShapes.removeFirst(excess)
}
return Block(shape: shape, orientation: Block.Orientation.all.random())
}
}
extension Engine: Serializable {
public typealias Representation = [String: Any]
public func serialize() -> Representation {
var dict: Representation = [:]
dict["width"] = width
dict["height"] = height
dict["initialInterval"] = initialInterval
dict["score"] = score
dict["blocks"] = blockCount
dict["currentBlock"] = currentBlock.serialize()
dict["nextBlock"] = nextBlock.serialize()
dict["recentShapes"] = recentShapes.map { $0.serialize() }
dict["board"] = board.serialize()
dict["started"] = dateStarted
dict["serialized"] = Date()
return dict
}
public static func deserialize(_ dict: Representation) -> Engine? {
guard let width = dict["width"] as? Int else { return nil }
guard let height = dict["height"] as? Int else { return nil }
guard let interval = dict["initialInterval"] as? TimeInterval else { return nil }
let engine = Engine(width: width, height: height, interval: interval)
guard let score = dict["score"] as? Int else { return nil }
engine.score = score
guard let blocks = dict["blocks"] as? Int else { return nil }
engine.blockCount = blocks
guard let currentBlock = Block.deserialize(dict["currentBlock"]) else { return nil }
engine.currentBlock = currentBlock
guard let nextBlock = Block.deserialize(dict["nextBlock"]) else { return nil }
engine.nextBlock = nextBlock
guard let recentShapesStrings = dict["recentShapes"] as? [String] else { return nil }
var recentShapes: [Block.Shape] = []
for s in recentShapesStrings {
guard let shape = Block.Shape.deserialize(s) else { return nil }
recentShapes.append(shape)
}
engine.recentShapes = recentShapes
guard let board = Board.deserialize(dict["board"]) else { return nil }
engine.board = board
guard let dateStarted = dict["started"] as? Date else { return nil }
engine.dateStarted = dateStarted
return engine
}
}