Tetris/TetrisKit/GameBoard.swift

55 lines
1.3 KiB
Swift
Raw Normal View History

2019-10-15 16:24:58 +00:00
//
// GameBoard.swift
// TetrisKit
//
// Created by Shadowfacts on 10/13/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import Foundation
public struct GameBoard {
public let width: Int
public let height: Int
2019-10-15 21:52:16 +00:00
public internal(set) var tiles: [[Tetromino?]]
2019-10-15 16:24:58 +00:00
public init(width: Int, height: Int) {
self.width = width
self.height = height
tiles = (1...height).map { _ in
2019-10-15 21:52:16 +00:00
Array(repeating: nil, count: width)
2019-10-15 16:24:58 +00:00
}
}
public subscript(x: Int, y: Int) -> Bool {
2019-10-15 21:52:16 +00:00
return self.tiles[y][x] != nil
}
public subscript(x: Int, y: Int) -> Tetromino? {
2019-10-15 16:24:58 +00:00
return self.tiles[y][x]
}
2019-10-15 21:52:16 +00:00
public mutating func set(piece: GamePiece) {
2019-10-15 16:24:58 +00:00
let (left, top) = piece.topLeft
for y in 0..<piece.tiles.count where y + top < height {
for x in 0..<piece.tiles.first!.count where x + left < width {
if piece.tiles[y][x] {
2019-10-15 21:52:16 +00:00
self.tiles[y + top][x + left] = piece.tetromino
2019-10-15 16:24:58 +00:00
}
}
}
}
2019-10-15 21:52:16 +00:00
mutating func clear(tiles: [(Int, Int)]) {
2019-10-15 16:24:58 +00:00
for (x, y) in tiles {
2019-10-15 21:52:16 +00:00
self.tiles[y][x] = nil
2019-10-15 16:24:58 +00:00
}
}
2019-10-15 21:52:16 +00:00
func rowFull(_ row: Int) -> Bool {
return tiles[row].allSatisfy({ $0 != nil })
2019-10-15 16:24:58 +00:00
}
}