Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cstdio>
- #include <windows.h>
- #include <deque>
- #include <ctime>
- #define y first
- #define x second
- #define For(i,z) for(int32_t i=0;i<(z);i++)
- using namespace std;
- const int N = 20;
- /*
- 0 - empty
- 1 - snake
- 2 - fruit
- */
- int state[N][N];
- int delay;
- string conv = "DASW";
- vector <pair<int, int> > addpos = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
- deque<pair<int, int> > snake;
- inline void waitForKey() {
- fflush(stdin);
- while (fgetc(stdin) == 0x0A);
- return;
- }
- inline bool correct(int y, int x) {
- if (y < 0 || y >= N) return false;
- if (x < 0 || x >= N) return false;
- return (state[y][x] != 1);
- }
- inline void clearall() {
- delay = 500;
- snake.clear();
- For (i, N)
- For (j, N)
- state[i][j] = 0;
- }
- string fieldchars = ".XO";
- void printfield() {
- system("cls");
- For (i, N) {
- For (j, N)
- cout << fieldchars[state[i][j]];
- cout << '\n';
- }
- cout << endl;
- }
- int genapple() {
- int nxt;
- while (true) {
- nxt = rand() % (N * N);
- if (state[nxt/N][nxt%N] == 0)
- break;
- }
- state[nxt/N][nxt%N] = 2;
- }
- void play() {
- clearall();
- snake.emplace_front(0, 0);
- state[0][0] = 1;
- genapple();
- printfield();
- pair<int, int> curAdd = {0, 1};
- while (true) {
- int tt = GetTickCount();
- //int adidx = -1;
- auto wasAdd = curAdd;
- bool space = GetKeyState(VK_SPACE) & 0x8000;
- while (GetTickCount() - tt < delay / (space ? 3 : 1)) {
- For (i, 4)
- if (GetKeyState(conv[i]) & 0x8000)
- if (wasAdd != make_pair(-addpos[i].y, -addpos[i].x))
- curAdd = addpos[i];
- }
- int ny = snake.front().y + curAdd.y,
- nx = snake.front().x + curAdd.x;
- if (correct(ny, nx) == false) {
- cout << "DEAD!!! Press any key + Enter to continue" << endl;
- waitForKey();
- return;
- }
- if (state[ny][nx] == 2) {
- state[ny][nx] = 1;
- genapple();
- delay = max(100, delay * 96 / 100);
- } else {
- state[ny][nx] = 1;
- state[snake.back().y][snake.back().x] = 0;
- snake.pop_back();
- }
- snake.emplace_front(ny, nx);
- printfield();
- //Sleep();
- }
- }
- int32_t main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(0); cout.tie(0);
- srand(time(NULL));
- cout << "Input on WASD" << endl;
- cout << "Space for triple speed" << endl;
- cout << "Press any button + Enter to continue" << endl;
- waitForKey();
- while (true) {
- play();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement