Skip to content

Instantly share code, notes, and snippets.

@efruchter
Created February 27, 2017 02:21
Show Gist options
  • Save efruchter/b9a02db2dd9212bf867361d7e2a44f07 to your computer and use it in GitHub Desktop.
Save efruchter/b9a02db2dd9212bf867361d7e2a44f07 to your computer and use it in GitHub Desktop.
A 1-script snake game implemented in object-less c++
// Snake.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[width * height], tailY[width * height];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
void Setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw()
{
system("cls");
for (int i = 0; i < width + 2; i++)
{
cout << "#";
}
cout << endl;
for (int i = 0; i < height; i++)
{
cout << "#";
for (int j = 0; j < width; j++)
{
if (i == y && j == x)
{
cout << "O";
}
else if (i == fruitY && j == fruitX)
{
cout << "F";
}
else
{
bool printedTail = false;
for (int k = 0; k < nTail; k++)
{
if (j == tailX[k] && i == tailY[k])
{
cout << "o";
printedTail = true;
break;
}
}
if (!printedTail)
{
cout << " ";
}
}
}
cout << "#";
cout << endl;
}
for (int i = 0; i < width + 2; i++)
{
cout << "#";
}
cout << endl << "Score: " << score;
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
if (dir != RIGHT)
{
dir = LEFT;
}
break;
case 'd':
if (dir != LEFT)
{
dir = RIGHT;
}
break;
case 'w':
if (dir != DOWN)
{
dir = UP;
}
break;
case 's':
if (dir != UP)
{
dir = DOWN;
}
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic()
{
if (nTail > 0)
{
for (int i = nTail - 1; i > 0; i--)
{
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
tailX[0] = x;
tailY[0] = y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x == fruitX && y == fruitY)
{
score++;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
if (x < 0)
{
x = width - 1;
}
else if (x >= width)
{
x = 0;
}
if (y < 0)
{
y = height - 1;
}
else if (y >= height)
{
y = 0;
}
for (int k = 0; k < nTail; k++)
{
if (x == tailX[k] && y == tailY[k])
{
gameOver = true;
break;
}
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(100);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment