Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- struct LightsOutApp: App {
- var body: some Scene {
- WindowGroup {
- ContentView()
- }
- }
- }
- var SingleMode = false
- struct ContentView: View {
- @State var buttons: [[ButtonState]] = Array(repeating: Array(repeating: ButtonState.off, count: columns), count: rows)
- var body: some View {
- HStack {
- VStack {
- ForEach(0..<rows, id: \.self) { row in
- HStack {
- ForEach(0..<columns, id: \.self) { column in
- Button(action: {
- buttonClick(row: row, column: column)
- }) {
- Text(buttons[row][column].text)
- .frame(width: 50, height: 50)
- .background(buttons[row][column].color)
- .border(Color.clear, width: 0)
- }
- }
- }
- }
- }
- // Button on the left side
- Button(action: {
- if SingleMode == false {
- SingleMode = true
- } else {
- SingleMode = false
- }
- }) {
- Text("Single Toggle Mode")
- .padding(10)
- .background(Color.blue)
- .foregroundColor(Color.white)
- }
- }
- }
- func buttonClick(row: Int, column: Int) {
- buttons[row][column].toggle()
- let neighbors = [(row - 1, column), (row + 1, column), (row, column - 1), (row, column + 1)]
- if SingleMode == false {
- for (neighborRow, neighborColumn) in neighbors {
- if (0..<rows).contains(neighborRow) && (0..<columns).contains(neighborColumn) {
- buttons[neighborRow][neighborColumn].toggle()
- }
- }
- }
- }
- }
- enum ButtonState: Identifiable {
- case on, off
- var text: String {
- switch self {
- case .on:
- return ""
- case .off:
- return ""
- }
- }
- var color: Color {
- switch self {
- case .on:
- return Color.red
- case .off:
- return Color.green
- }
- }
- mutating func toggle() {
- self = (self == .on) ? .off : .on
- }
- var id: Int {
- text.hashValue
- }
- }
- let rows = 5
- let columns = 5
- @available(iOS 15.0, *)
- struct ContentView_Previews: PreviewProvider {
- static var previews: some View {
- ContentView()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement