-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.c
More file actions
105 lines (88 loc) · 2.79 KB
/
Copy pathsnake.c
File metadata and controls
105 lines (88 loc) · 2.79 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#define SDL_MAIN_HANDLED
#include "inc/SDL.h"
#include <stdio.h>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define BLOCK_SIZE 20
// Directions
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
typedef struct {
int x, y;
} Snake;
int init(SDL_Window **window, SDL_Renderer **renderer) {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return 0;
}
*window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!*window) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return 0;
}
*renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_ACCELERATED);
if (!*renderer) {
printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
return 0;
}
return 1;
}
int handle_events(int *direction) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
return 0;
}
if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_UP:
if (*direction != DOWN) *direction = UP;
break;
case SDLK_DOWN:
if (*direction != UP) *direction = DOWN;
break;
case SDLK_LEFT:
if (*direction != RIGHT) *direction = LEFT;
break;
case SDLK_RIGHT:
if (*direction != LEFT) *direction = RIGHT;
break;
}
}
}
return 1;
}
int main(int argc, char *argv[]) {
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
if (!init(&window, &renderer)) {
return 1;
}
Snake snake = {SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2};
int direction = RIGHT; // Initial movement
int running = 1;
while (running) {
running = handle_events(&direction);
// Update snake position based on direction
if (direction == UP) snake.y -= BLOCK_SIZE;
if (direction == DOWN) snake.y += BLOCK_SIZE;
if (direction == LEFT) snake.x -= BLOCK_SIZE;
if (direction == RIGHT) snake.x += BLOCK_SIZE;
// Clear the screen
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Draw the snake
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_Rect snakeBlock = {snake.x, snake.y, BLOCK_SIZE, BLOCK_SIZE};
SDL_RenderFillRect(renderer, &snakeBlock);
SDL_RenderPresent(renderer);
SDL_Delay(100);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}