Event: wrap Event enum

This commit is contained in:
candy committed 2024-10-26 15:38:51 -04:00
1 parent 523a187763
commit 461d0c96de
2 files changed
+48 -20

No files matched your search

+17 -18
View File
@@ -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()
+31 -2
View File
@@ -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
}
}
}