Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <cstdlib>
- typedef struct SnakePiece {
- int x;
- int y;
- SnakePiece *next;
- } SnakePiece;
- void initialize_board (char **board, int width, int height) {
- for (int i = 0; i < width; i++) {
- board[0][i] = '#';
- board[height-1][i] = '#';
- }
- for (int i = 0; i < height; i++) {
- board[i][0] = '#';
- board[i][width-1] = '#';
- }
- for (int i = 1; i < height-1; i++) {
- for (int j = 1; j < width-1; j++) {
- board[i][j] = ' ';
- }
- }
- }
- void show_board (char **board, int width, int height) {
- for (int i = 0; i < height; i++) {
- for (int j = 0; j < width; j++) {
- printf ("%c", board[i][j]);
- }
- printf ("\n");
- }
- }
- void initialize_snake (SnakePiece **head, int &len, int width, int height) {
- SnakePiece *new_piece = (SnakePiece *) malloc (sizeof(SnakePiece));
- //for (int i = 0; i < 3; i++) {
- new_piece->x = (width/2)-1;
- new_piece->y = (height/2)-1;
- new_piece->next = *head;
- *head = new_piece;
- len++;
- //}
- }
- void show_snake (SnakePiece *head, char **board) {
- SnakePiece *ptr;
- ptr = head;
- while (ptr != NULL) {
- board[ptr->y][ptr->x] = 'o';
- ptr = ptr->next;
- }
- }
- void update_snake (SnakePiece *head, char **board, int x, int y) {
- SnakePiece *ptr;
- ptr = head;
- board[ptr->y][ptr->x] = ' ';
- ptr = ptr->next;
- while (ptr != NULL) {
- ptr->x += x;
- ptr->y += y;
- ptr = ptr->next;
- }
- }
- void move_snake (SnakePiece *head, char **board, char c, int width, int height) {
- if (c == 'a' && head->x > 1) {
- head->x += -1;
- update_snake(head, board, -1, 0);
- }
- }
- void generate_fruit (char **board, int width, int height) {
- int fruitx, fruity;
- fruitx = rand() % width;
- fruity = rand() % height;
- board[fruity][fruitx] = 'x';
- }
- int main()
- {
- char **board;
- int width, height;
- SnakePiece *head = NULL;
- scanf("%d %d", &height, &width);
- board = (char **) malloc (height * sizeof(char *));
- for (int i = 0; i < height; i++) {
- board[i] = (char *) malloc (width * sizeof(char));
- }
- initialize_board(board, width, height);
- int len = 0;
- initialize_snake(&head, len, width, height);
- bool fruit_eaten = 1;
- char c;
- while (true) {
- if (fruit_eaten) {
- generate_fruit(board, width, height);
- fruit_eaten = 0;
- }
- if(kbhit()) {
- c = getch();
- move_snake (head, board, c, width, height);
- }
- show_snake(head, board);
- show_board(board, width, height);
- system ("cls");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment