64 lines
2.2 KiB
Swift
64 lines
2.2 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.colorAt(col, row))
|
|
.frame(width: size, height: size)
|
|
}
|
|
}
|
|
|
|
func colorAt(_ col: Int, _ row: Int) -> Color {
|
|
if currentPieceAt(col, row) {
|
|
return self.currentPiece!.tetromino.color
|
|
} else if droppedPieceAt(col, row) {
|
|
return .gray
|
|
} else {
|
|
return .clear
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|