End the game when new pieces can't be placed
This commit is contained in:
parent
600768ea5d
commit
0dd8bd79cb
|
@ -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()
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 currentBag.isEmpty {
|
||||
generateBag()
|
||||
if overlapsAny(nextPiece) {
|
||||
state = .ended
|
||||
} else {
|
||||
nextTetrominoes.removeFirst()
|
||||
if currentBag.isEmpty {
|
||||
generateBag()
|
||||
}
|
||||
nextTetrominoes.append(currentBag.removeFirst())
|
||||
|
||||
currentPiece = nextPiece
|
||||
}
|
||||
nextTetrominoes.append(currentBag.removeFirst())
|
||||
}
|
||||
|
||||
func generateBag() {
|
||||
|
@ -70,7 +73,9 @@ public class GameController: ObservableObject {
|
|||
clearLines()
|
||||
nextPiece()
|
||||
|
||||
state = .playing(.normal)
|
||||
if case .playing(.dropped) = state {
|
||||
state = .playing(.normal)
|
||||
}
|
||||
}
|
||||
|
||||
func clearLines() {
|
||||
|
@ -194,6 +199,7 @@ public class GameController: ObservableObject {
|
|||
public enum GameState {
|
||||
case waitingForStart
|
||||
case playing(PlayState)
|
||||
case ended
|
||||
}
|
||||
|
||||
public enum PlayState {
|
||||
|
|
Loading…
Reference in New Issue