End the game when new pieces can't be placed

This commit is contained in:
Shadowfacts 2019-10-17 17:39:59 -04:00
parent 600768ea5d
commit 0dd8bd79cb
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
3 changed files with 24 additions and 10 deletions

View File

@ -60,6 +60,10 @@ struct ContentView: View {
func startTimer() {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (_) in
guard case .playing(_) = self.controller.state else {
self.stopTimer()
return
}
self.controller.step()
})
}

View File

@ -123,6 +123,10 @@ struct ContentView: View {
func startTimer() {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (_) in
guard case .playing(_) = self.controller.state else {
self.stopTimer()
return
}
self.controller.step()
}
}

View File

@ -32,10 +32,6 @@ public class GameController: ObservableObject {
@Published public var score = 0
var previousPieceWasTetris = false
public var ended: Bool {
return (0..<width).first(where: { board[$0, 0] }) != nil
}
public init() {
self.board = GameBoard(width: width, height: height)
self.currentPiece = nil
@ -48,13 +44,20 @@ public class GameController: ObservableObject {
}
func nextPiece() {
let tetromino = nextTetrominoes.removeFirst()
currentPiece = GamePiece(tetromino: tetromino, topLeft: ((width - tetromino.shape.count) / 2, 0))
let tetromino = nextTetrominoes.first!
let nextPiece = GamePiece(tetromino: tetromino, topLeft: ((width - tetromino.shape.count) / 2, 0))
if overlapsAny(nextPiece) {
state = .ended
} else {
nextTetrominoes.removeFirst()
if currentBag.isEmpty {
generateBag()
}
nextTetrominoes.append(currentBag.removeFirst())
currentPiece = nextPiece
}
}
func generateBag() {
@ -70,8 +73,10 @@ public class GameController: ObservableObject {
clearLines()
nextPiece()
if case .playing(.dropped) = state {
state = .playing(.normal)
}
}
func clearLines() {
var cleared = 0
@ -194,6 +199,7 @@ public class GameController: ObservableObject {
public enum GameState {
case waitingForStart
case playing(PlayState)
case ended
}
public enum PlayState {