Tetris/Tetris Mac/ContentView.swift

84 lines
2.7 KiB
Swift

//
// ContentView.swift
// Tetris Mac
//
// Created by Shadowfacts on 10/16/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import SwiftUI
import TetrisKit
import TetrisUI
struct ContentView: View {
@ObservedObject var controller: GameController/* = {
let c = GameController()
c.start()
return c
}()*/
@State var timer: Timer?
var body: some View {
GeometryReader { (geometry) in
HStack(alignment: .top, spacing: 8) {
VStack {
Text("Held")
.font(.title)
.fontWeight(.bold)
if self.controller.heldTetromino != nil {
Group {
TetrominoView(size: 100 / 4, tetromino: self.controller.heldTetromino!)
}.frame(width: 100, height: 100, alignment: .center)
} else {
Rectangle().foregroundColor(.clear).frame(width: 100, height: 100)
}
Text("Score")
.font(.title)
.fontWeight(.bold)
Text(verbatim: self.controller.score.description)
.font(.title)
}
.padding(.leading, 8)
BoardView(board: self.$controller.board, currentPiece: self.$controller.currentPiece, droppedPiece: self.$controller.currentPieceAtDropPoint)
.aspectRatio(CGSize(width: self.controller.width, height: self.controller.height), contentMode: .fit)
.onAppear(perform: self.startTimer)
.onDisappear(perform: self.stopTimer)
VStack {
Text("Next")
.font(.title)
.fontWeight(.bold)
NextTetromioesView(size: 100, tetrominoes: self.controller.nextTetrominoes)
.frame(width: 100)
}
.padding(.trailing, 8)
}
}
.frame(maxWidth: 634, maxHeight: 804)
}
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()
})
}
func stopTimer() {
self.timer?.invalidate()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let c = GameController()
c.start()
return ContentView(controller: c)
}
}