From: Ken Allen Date: 2007-03-19T05:58:36+09:00 Subject: Re: ruby-sdl: How do you poll events? ChrisKaelin wrote: > The code of my raw main loop is below. I'm sure there are better ways > to poll the event queue. Do you have better ideas? > Also I'm not sure about the garbage collect thing at the bottom... > > loop { > offset_x = 0 > offset_y = 0 > if event.poll != 0 > case event.type > when SDL::Event::QUIT > break > when SDL::Event::KEYDOWN > case event.keySym > when SDL::Key::ESCAPE > break > when SDL::Key::LEFT > offset_x = -5 > when SDL::Key::RIGHT > offset_x = +5 > when SDL::Key::DOWN > offset_y = +5 > when SDL::Key::UP > offset_y = -5 > end > end > end > > before = now > now = SDL::getTicks > dt = now-before > # here comes the rendering finally > player.draw(screen) > enemies.each{|i| i.draw(screen)} > screen.fillRect(0,0,640,480,0) > w.to_sdl(screen, offset_x, offset_y) > screen.fillRect(0,0,640,480,0) > ObjectSpace.garbage_collect > screen.flip > } > > > > Here's the main loop from my game engine. You should poll the event queue in a loop or you'll only handle one event every iteration of the main loop. I handle the input by passing the important info from the event on to the top element of a stack of input handlers. This means you can easily switch control contexts by pushing/popping handlers. This isn't really perfect though. Ideally it wouldn't be method calls directly on the top element, ideally the event poller shouldn't know about the stack and the input handler should allow for allowing events to continue down the stack. Errr, this may not really have been what you were asking for. Also I think there's a helper function in sdl that builds a hash of keysyms to booleans that stores the keyboard state. Anyway, I hope this helps you. def main_loop @running = true @last_time = SDL.get_ticks while @running while event = SDL::Event2.poll case event when SDL::Event2::Quit quit when SDL::Event2::KeyDown @input.last.key_down( event.sym ) unless @input.empty? when SDL::Event2::KeyUp @input.last.key_up( event.sym ) unless @input.empty? when SDL::Event2::MouseButtonDown @input.last.mouse_down( event.button, P[event.x,event.y] ) when SDL::Event2::MouseButtonUp @input.last.mouse_up( event.button, P[event.x,event.y] ) end end current_time = SDL.get_ticks if current_time - @last_time > GAME_SPEED @last_time = current_time Core.objects.update current_time end Core.display.draw end end