summaryrefslogtreecommitdiff
path: root/Week1-Pacman/src/pacman.c
blob: f3a4769de52d43bd4ff22550b345e3e9c875374e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <SDL2/SDL.h>
#include <stdbool.h>
#include "pacman.h"

#define PACMAN_SPEED 261
#define PACMAN_SIDE 40

void handle_pacman_input(SDL_Event* e, struct pacman* pacman) {

  if(e->type == SDL_KEYDOWN) {
    switch(e->key.keysym.sym) {
    case SDLK_UP:
      pacman->facing = FACING_UP;
      break;
    case SDLK_DOWN:
      pacman->facing = FACING_DOWN;
      break;
    case SDLK_LEFT:
      pacman->facing = FACING_LEFT;
      break;
    case SDLK_RIGHT:
      pacman->facing = FACING_RIGHT;
      break;
    }
  }
}

void update_pacman(struct pacman* pacman, float dt) {

  if(pacman->facing == FACING_UP) {
    pacman->ypos -= PACMAN_SPEED * dt;
  } else if(pacman->facing == FACING_DOWN) {
    pacman->ypos += PACMAN_SPEED * dt;
  } else if(pacman->facing == FACING_LEFT) {
    pacman->xpos -= PACMAN_SPEED * dt;
  } else {
    pacman->xpos += PACMAN_SPEED * dt;
  }

  update_animation(&pacman->animations[pacman->facing], dt);
}

void draw_pacman(struct demo* demo, const struct pacman* pacman) {
  const struct animation* current_animation =
    &pacman->animations[pacman->facing];

  SDL_Rect d_rect = {
    .x = pacman->xpos,
    .y = pacman->ypos,
    .w = PACMAN_SIDE,
    .h = PACMAN_SIDE
  };

  draw_animation(demo, current_animation, &d_rect);
}