Tetris/TetrisUI/CurrentPieceView.swift

54 lines
2.0 KiB
Swift

//
// CurrentPieceView.swift
// Tetris
//
// Created by Shadowfacts on 10/14/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import SwiftUI
import TetrisKit
struct CurrentPieceView: View {
let boardWidth: Int
let boardHeight: Int
@Binding var currentPiece: GamePiece?
@Binding var droppedPiece: GamePiece?
var body: some View {
GridView(rows: self.boardHeight, columns: self.boardWidth) { (col, row, size) in
Rectangle()
.foregroundColor(self.currentPieceAt(col, row) ? Color.blue : self.droppedPieceAt(col, row) ? Color.gray : Color.clear)
.frame(width: size, height: size)
}
}
func currentPieceAt(_ col: Int, _ row: Int) -> Bool {
guard let currentPiece = self.currentPiece else { return false }
let (left, top) = currentPiece.topLeft
let pieceHeight = currentPiece.tiles.count
let pieceWidth = currentPiece.tiles.first!.count
return col - left >= 0 && col - left < pieceWidth && row - top >= 0 && row - top < pieceHeight && currentPiece.tiles[row - top][col - left]
}
func droppedPieceAt(_ col: Int, _ row: Int) -> Bool {
guard let droppedPiece = self.droppedPiece else { return false }
let (left, top) = droppedPiece.topLeft
let pieceHeight = droppedPiece.tiles.count
let pieceWidth = droppedPiece.tiles.first!.count
return col - left >= 0 && col - left < pieceWidth && row - top >= 0 && row - top < pieceHeight && droppedPiece.tiles[row - top][col - left]
}
}
struct CurrentPieceView_Previews: PreviewProvider {
@State static var currentPiece: GamePiece? = GamePiece(tetromino: .t)
@State static var droppedPiece: GamePiece? = {
var piece = GamePiece(tetromino: .t)
return piece.moved(by: (0, 16 - piece.tiles.count))
}()
static var previews: some View {
CurrentPieceView(boardWidth: 10, boardHeight: 16, currentPiece: $currentPiece, droppedPiece: $droppedPiece)
}
}