Tetris/TetrisUI/TetrominoView.swift

62 lines
1.5 KiB
Swift

//
// TetrominoView.swift
// Tetris
//
// Created by Shadowfacts on 10/15/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import SwiftUI
import TetrisKit
public struct TetrominoView: View {
let tetromino: Tetromino
public init(tetromino: Tetromino) {
self.tetromino = tetromino
}
public var body: some View {
GridView(rows: self.rows, columns: self.columns) { (col, row, size) in
Rectangle()
.foregroundColor(self.colorAt(col, row))
.frame(width: size, height: size)
}
}
var rows: Int {
self.tetromino.shape.firstIndex(where: { row in
row.allSatisfy({ el in
!el
})
}) ?? self.tetromino.shape.count
}
var columns: Int {
self.tetromino.shape.map { row in
(row.firstIndex(where: { el in
!el
}) ?? row.count - 1) + 1
}.max() ?? self.tetromino.shape.first!.count
}
func colorAt(_ col: Int, _ row: Int) -> Color {
if row < tetromino.shape.count && col < tetromino.shape[row].count && tetromino.shape[row][col] {
return tetromino.color
} else {
return .clear
}
}
}
struct TetrominoView_Previews: PreviewProvider {
static var previews: some View {
Group {
TetrominoView(tetromino: .t)
TetrominoView(tetromino: .i)
TetrominoView(tetromino: .z)
TetrominoView(tetromino: .j)
}
}
}