pvjc26/du4/main.c
mk570rp 10cc177646 a4:
git commit -m a4
git commit -m a4:
2026-05-10 19:30:35 +00:00

97 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include "game.h"
#ifdef _WIN32
#include <conio.h>
#else
#include <unistd.h>
#include <termios.h>
#endif
#ifndef _WIN32
int getch() {
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int c = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return c;
}
#endif
void draw(struct state* s) {
system("clear");
for (int y = 0; y < s->height; y++) {
for (int x = 0; x < s->width; x++) {
if (is_snake(s->snake, x, y)) {
printf("O");
}
else {
int food = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (s->foodx[i] == x && s->foody[i] == y) {
printf("*");
food = 1;
}
}
if (!food) printf(".");
}
}
printf("\n");
}
}
void set_dir(struct state* s, char c) {
if (c == 'w') { s->sx = 0; s->sy = -1; }
if (c == 's') { s->sx = 0; s->sy = 1; }
if (c == 'a') { s->sx = -1; s->sy = 0; }
if (c == 'd') { s->sx = 1; s->sy = 0; }
}
int main() {
struct state s;
s.width = 20;
s.height = 10;
s.snake = add_snake(NULL, 5, 5);
s.sx = 1;
s.sy = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
s.foodx[i] = rand() % s.width;
s.foody[i] = rand() % s.height;
}
int result = END_CONTINUE;
while (result == END_CONTINUE) {
draw(&s);
char c = getch();
set_dir(&s, c);
result = step_state(&s);
}
draw(&s);
if (result == END_WALL) printf("Game Over: wall\n");
if (result == END_SNAKE) printf("Game Over: self\n");
if (result == END_FOOD) printf("You Win!\n");
free_snake(s.snake);
return 0;
}