2019-10-15 16:24:58 +00:00
|
|
|
//
|
|
|
|
// 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
|
2019-10-20 23:21:04 +00:00
|
|
|
if self.currentPieceAt(col, row) {
|
|
|
|
Rectangle()
|
|
|
|
.foregroundColor(self.currentPiece!.tetromino.color)
|
|
|
|
.frame(width: size, height: size)
|
|
|
|
.border(self.currentPiece!.tetromino.borderColor, width: 6)
|
|
|
|
} else if self.droppedPieceAt(col, row) {
|
|
|
|
Rectangle()
|
|
|
|
.foregroundColor(.gray)
|
|
|
|
.frame(width: size, height: size)
|
|
|
|
} else {
|
|
|
|
Rectangle()
|
|
|
|
.foregroundColor(.clear)
|
|
|
|
.frame(width: size, height: size)
|
|
|
|
}
|
2019-10-15 21:52:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-15 16:24:58 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|