Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <ctime>
- #include <conio.h>
- #include <dos.h>
- #include <Windows.h>
- #include <time.h>
- using namespace std;
- int const weight = 20;
- int const leight = 20;
- int field[weight][leight];
- int dir;
- int snake_x = weight / 2;
- int snake_y = leight / 2;
- bool game_over = false;
- int tail = 3;
- int snake_olx;
- int snake_oly;
- void generate_food()
- {
- srand(time(NULL));
- int food_x = rand() % (weight - 2) + 1;
- int food_y = rand() % (leight - 2) + 1;
- field[food_x][food_y] = -2;
- }
- void init_field()
- {
- for (int i = 0; i < weight; i++)
- {
- field[0][i] = -1;
- field[leight - 1][i] = -1;
- }
- for (int i = 1; i < leight - 1; i++)
- {
- for (int j = 1; j < weight - 1; j++)
- {
- field[i][0] = -1;
- field[i][j] = 0;
- field[i][weight - 1] = -1;
- }
- }
- field[snake_x][snake_y] = 1;
- generate_food();
- }
- char get_field_char(int key) {
- char ch;
- switch (key)
- {
- case -1:
- ch = '#';
- break;
- case 0:
- ch = ' ';
- break;
- case -2:
- ch = '@';
- break;
- /*case 3:
- ch = '^';
- break;
- case 4:
- ch = '|';
- break;
- */
- default:
- break;
- }
- return ch;
- }
- void input()
- {
- if (_kbhit())
- {
- int ch = _getch();
- switch (ch)
- {
- //case 'w':
- case 230:
- dir = 1;
- break;
- //case 'a':
- case 228:
- dir = 2;
- break;
- //case 's':
- case 235:
- dir = 3;
- break;
- //case 'd':
- case 162:
- dir = 4;
- break;
- default:
- break;
- }
- }
- }
- void logic()
- {
- snake_olx = snake_x;
- snake_oly = snake_y;
- switch (dir)
- {
- case 1:
- snake_x--;
- snake_olx = snake_x;
- break;
- case 2:
- snake_y--;
- break;
- case 3:
- snake_x++;
- break;
- case 4:
- snake_y++;
- break;
- default:
- break;
- }
- }
- void update_field()
- {
- if (field[snake_x][snake_y] == -1)
- {
- game_over = true;
- }
- else if (field[snake_x][snake_y] == -2)
- {
- generate_food();
- tail++;
- field[snake_olx][snake_oly] = tail;
- field[snake_x][snake_y] = tail++;
- }
- /*else if (field[snake_x][snake_y] > 2)
- {
- game_over = true;
- }*/
- for (int i = 1; i < leight - 1; i++)
- {
- for (int j = 1; j < weight - 1; j++)
- {
- if (_kbhit())
- {
- if (field[i][j] > 0)
- {
- field[i][j] --;
- }
- }
- }
- }
- }
- void print_field()
- {
- for (int i = 0; i < weight; i++)
- {
- for (int j = 0; j < leight; j++)
- {
- if (field[i][j] > 0)
- {
- cout << '^';
- }
- else
- cout << get_field_char(field[i][j]);
- }
- cout << endl;
- }
- }
- int main()
- {
- init_field();
- while (game_over != true)
- {
- input();
- logic();
- print_field();
- update_field();
- system("cls");
- Sleep(10);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement