nikpez
Ominide
1 min. di lettura
Vota 4 / 5

Concetti Chiave

  • This code is a basic implementation of the classic Snake game using the ncurses library in C.
  • The game logic is handled by a parent process, with child processes managing user input and a timer.
  • Player movement is controlled by reading keyboard input and adjusting the snake's direction accordingly.
  • A random "apple" appears on the grid, and the snake grows when it "eats" the apple.
  • The game uses pipes for inter-process communication to manage inputs and game state updates.
Snake

#include
#include
#include
#include
#include
#include

typedef struct{
int xm;
int ym;
}coordinate;

int main()
{

initscr();
noecho();
curs_set(0);
//start_color();
//init_pair(2, 0, 4);

int x=0, y=0;
char melap='O';
char cursore[21]= {"#"};
int p[2],pmela[2];
int pid1, pid2,pid3;
int mangiato=1;
coordinate mela;

srand(time(NULL));

mvprintw(y, x, "%s",cursore);
refresh();
pipe(p);
pipe(pmela);

if(pid1 = fork() == 0) //processo figlio tasti
{
char car;
while(1)
{
car=getch();
write(p[1], &car, sizeof(char));
}
}
else if(pid2 = fork() == 0) //timer
{
char i = '\0';
while(1)
{
usleep(1000000);
write(p[1], &i, sizeof(char));
}
}
else
{
char cond;
char dir='s';

mela.xm=rand()%10;
mela.ym=rand()%10;
mvprintw(mela.ym, mela.xm,"%c",melap);
refresh();

while(1)
{
read(p[0], &cond, sizeof(char));
if(cond=='\0')
{
erase();
switch(dir)
{
case 'w':
mvprintw(y, x, " ");
mvprintw(--y, x, "%s", cursore);
refresh();
break;
case 'a':
mvprintw(y, x, " ");
mvprintw(y, --x, "%s", cursore);
refresh();
break;
case 's':
mvprintw(y, x, " ");
mvprintw(++y, x, "%s", cursore);
refresh();
break;
case 'd':
mvprintw(y, x, " ");
mvprintw(y, ++x, "%s", cursore);
refresh();
break;
}
mvprintw(mela.ym, mela.xm,"%c",melap);
refresh();
}
else
dir=cond;

if(mela.ym==y &&mela.xm==x)
{
mvprintw(mela.ym, mela.xm," ");
strcat(cursore,"#");
mela.xm=rand()%10;
mela.ym=rand()%10;
mvprintw(mela.ym, mela.xm,"%c",melap);
refresh();
}

}
}

kill(pid1,15);
kill(pid2,15);
endwin();
return 0;
}

Domande e risposte

Hai bisogno di aiuto?
Chiedi alla community