diff --git a/Sources/Picross/main.swift b/Sources/Picross/main.swift index 380288e..43f5472 100644 --- a/Sources/Picross/main.swift +++ b/Sources/Picross/main.swift @@ -35,26 +35,27 @@ var eventHandler = EventHandler() while !quit { eventHandler.pump() { e in - if e.type == SDL_EVENT_QUIT.rawValue { - quit = true - } - if e.type == SDL_EVENT_MOUSE_BUTTON_DOWN.rawValue { - let x = Int(e.button.y) / 32 - let y = Int(e.button.x) / 32 + switch e { + case .quit(_): + quit = true + case .mouseButtonDown(let button): + let x = Int(button.y) / 32 + let y = Int(button.x) / 32 - guard x < 10 && y < 10 else { return } + guard x < 10 && y < 10 else { return } - if board[x][y] != 3 { - if e.button.button == 1 { - if puzzle[x][y] == 1 { - board[x][y] = 1 - } else { - board[x][y] = 3 + if board[x][y] != 3 { + if button.button == 1 { + if puzzle[x][y] == 1 { + board[x][y] = 1 + } else { + board[x][y] = 3 + } + } else if button.button == 3 && board[x][y] != 1 { + board[x][y] = board[x][y] == 2 ? 0 : 2 } - } else if e.button.button == 3 && board[x][y] != 1 { - board[x][y] = board[x][y] == 2 ? 0 : 2 } - } + default: {}() } } @@ -78,5 +79,3 @@ while !quit { Engine.delay(100) } - -Engine.quit() diff --git a/Sources/SDL/Event.swift b/Sources/SDL/Event.swift index 60139f0..c91dadb 100644 --- a/Sources/SDL/Event.swift +++ b/Sources/SDL/Event.swift @@ -7,9 +7,38 @@ public class EventHandler { handle = SDL_Event() } - public func pump(handler: (SDL_Event) -> ()) { + public func pump(handler: (Event) -> ()) { while SDL_PollEvent(&handle) == true { - handler(handle) + if let event = Event(from: handle) { + handler(event) + } + } + } +} + +public enum Event { + case quit(SDL_QuitEvent) + case keyDown(SDL_KeyboardEvent) + case keyUp(SDL_KeyboardEvent) + case mouseButtonDown(SDL_MouseButtonEvent) + case mouseButtonUp(SDL_MouseButtonEvent) + + init?(from event: SDL_Event) { + let type = SDL_EventType(rawValue: event.type) + let event: Event? = switch type { + case SDL_EVENT_QUIT: .quit(event.quit) + case SDL_EVENT_KEY_DOWN: .keyDown(event.key) + case SDL_EVENT_KEY_UP: .keyUp(event.key) + case SDL_EVENT_MOUSE_BUTTON_DOWN: .mouseButtonDown(event.button) + case SDL_EVENT_MOUSE_BUTTON_UP: .mouseButtonUp(event.button) + default: nil + } + + if let event = event { + self = event + } else { + print("Unknown event type: \(type)") + return nil } } }