From f4c475192ee82e3cd137bc03ca76ace6d62a86ac Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Sun, 10 Mar 2013 20:13:53 -0400 Subject: [PATCH] move some game logic to inputs.d --- src/game.d | 34 ++++++----------------------- src/inputs.d | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 28 deletions(-) create mode 100644 src/inputs.d diff --git a/src/game.d b/src/game.d index 1dc00e7..58bee56 100644 --- a/src/game.d +++ b/src/game.d @@ -1,14 +1,7 @@ -static enum uint TICK_MS = 50; -static enum int MOVE_PER_TICK = 1; +import inputs; -enum -{ - MOVE_LEFT, - MOVE_RIGHT, - MOVE_UP, - MOVE_DOWN, - MOVE_COUNT -} +static enum uint TICK_MS = 50; +static enum int NUM_PLAYERS = 2; struct Player { @@ -16,13 +9,6 @@ struct Player int y; }; -struct MoveEvent -{ - int type; - bool active; - uint tick; -}; - class Game { public: @@ -32,29 +18,21 @@ public: } void handle_move_event(int type, bool active) { - m_movements[type] = active; } void update(uint ms) { while (ms > (m_last_tick_ms + TICK_MS)) { - if (m_movements[MOVE_LEFT]) - m_players[m_pindex].x -= MOVE_PER_TICK; - if (m_movements[MOVE_RIGHT]) - m_players[m_pindex].x += MOVE_PER_TICK; - if (m_movements[MOVE_UP]) - m_players[m_pindex].y += MOVE_PER_TICK; - if (m_movements[MOVE_DOWN]) - m_players[m_pindex].y -= MOVE_PER_TICK; m_last_tick_ms += TICK_MS; m_tick++; } } Player[] get_players() { return m_players; } + protected: - bool m_movements[MOVE_COUNT]; uint m_tick; uint m_last_tick_ms; - Player[2] m_players; + Player[NUM_PLAYERS] m_players; + InputEventList[NUM_PLAYERS] m_events; int m_pindex; }; diff --git a/src/inputs.d b/src/inputs.d new file mode 100644 index 0000000..df7f618 --- /dev/null +++ b/src/inputs.d @@ -0,0 +1,60 @@ + +enum +{ + INPUT_LEFT, + INPUT_RIGHT, + INPUT_UP, + INPUT_DOWN, + INPUT_COUNT +} + +typedef bool[INPUT_COUNT] Inputs; + +struct InputEvent +{ + uint tick; + Inputs inputs; + InputEvent *next; +}; + +class InputEventList +{ +public: + void add_event(uint tick, int event, bool active) + { + InputEvent *ie = get_event_for_tick(tick); + ie.inputs[event] = active; + } + InputEvent *get_event_for_tick(uint tick) + { + if (m_last_event is null) + { + m_events = new InputEvent(); + m_last_event = m_events; + m_last_event.tick = tick; + } + else if (m_last_event.tick < tick) + { + m_last_event.next = new InputEvent(); + m_last_event = m_last_event.next; + m_last_event.tick = tick; + } + return m_last_event; + } + InputEvent *get_first_event() { return m_events; } + void remove_older_than(uint tick) + { + while ((m_events !is null) && (m_events.tick <= tick)) + { + m_events = m_events.next; + } + if (m_events is null) + { + m_last_event = null; + } + } + +protected: + InputEvent *m_events; + InputEvent *m_last_event; +};