forked from nakidai/csnake
1
0
Fork 0

Add windows support in threads and sleep

Nakidai 2023-11-24 23:58:37 +03:00
parent ce1e91d90f
commit 1ff14f7cbc
2 changed files with 24 additions and 3 deletions

View File

@ -1,14 +1,14 @@
#include "input.h" #include "input.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#ifdef WIN32 #ifdef _WIN32
#include <conio.h> #include <conio.h>
#else #else
#include <unistd.h> #include <unistd.h>
#include <termios.h> #include <termios.h>
#endif #endif
#ifdef WIN32 #ifdef _WIN32
#define getch _getch #define getch _getch
#else #else
int getch(void) int getch(void)

View File

@ -1,8 +1,13 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h> #include <stdbool.h>
#include <pthread.h>
#include <time.h> #include <time.h>
#ifdef _WIN32
#include <Windows.h>
#include <process.h>
#else
#include <pthread.h>
#endif
#include "input.h" #include "input.h"
#include "screen.h" #include "screen.h"
@ -27,10 +32,18 @@ Food generateFood(Player *player)
return food; return food;
} }
#ifdef _WIN32
void resetCoordinates(void)
{
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, (COORD){0});
}
#else
void resetCoordinates(void) void resetCoordinates(void)
{ {
printf("\e[1;1H\e[2J"); printf("\e[1;1H\e[2J");
} }
#endif
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
@ -48,7 +61,11 @@ int main(int argc, char **argv)
bool stopped = false; bool stopped = false;
InputArgs input_args = (InputArgs){ key, running }; InputArgs input_args = (InputArgs){ key, running };
#ifdef _WIN32
_beginthread(input, 0, &input_args);
#else
pthread_create(&input_thread, NULL, input, &input_args); pthread_create(&input_thread, NULL, input, &input_args);
#endif
while (*running) while (*running)
{ {
screenSet(screen, ' '); screenSet(screen, ' ');
@ -59,7 +76,11 @@ int main(int argc, char **argv)
for (i = 0; i < SIZE*2; ++i) putchar('-'); for (i = 0; i < SIZE*2; ++i) putchar('-');
printf("\nScore: %d\n", player->score); printf("\nScore: %d\n", player->score);
#ifdef _WIN32
Sleep(1000L);
#else
nanosleep(&(struct timespec){.tv_sec = 1}, NULL); nanosleep(&(struct timespec){.tv_sec = 1}, NULL);
#endif
switch (*key) switch (*key)
{ {
case 'q': case 'q':