I just began a little fun project which is good ol' snake in CLI. What I'm currently figuring out is changing directions of a single dot inside a box (no snake yet!). I created an enum type with values up, down etc. and created a simple loop to update the position. What's curious is that no matter what value I assign to the direction variable, it is always 3 (DOWN). Here's working example:
#include <iostream>
using namespace std;
bool gameOver;
const int width = 60;
const int height = 20;
int x, y, fruitX, fruitY, score;
enum eDirection {STOP, LEFT, RIGHT, UP, DOWN};
enum eDirection dir;
int modulo(int x,int N){
return (x % N + N) %N;
}
void Setup(){
gameOver = false;
dir = LEFT;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw(){
system("cls");
for (int i = 0; i < width; i++){
cout << "#";
}
cout << endl;
for (int i = 0; i < height; i++){
cout << "#";
for (int j = 0; j < width; j++){
if (j == x && i == y){
cout << "O";
}
else{
cout << " ";
}
}
cout << "#";
cout << endl;
}
for (int i = 0; i < width; i++){
cout << "#";
}
cout << endl;
if (dir = STOP){
} else if (dir = UP){
y = modulo((y - 1) , height);
} else if (dir = DOWN){
y = modulo((y + 1) , height);
} else if (dir = LEFT){
x = modulo((x - 1) , width);
} else if (dir = RIGHT){
x = modulo((x + 1) , width);
}
}
void Input(){
}
void Logic(){
}
int main()
{
Setup();
while(!gameOver)
{
Draw();
cout << endl;
cout << "Direction value is: ";
cout << dir;
Input();
Logic();
//Sleep(10);
}
}
Any ideas? I'm fairly new to C++ and it's still difficult for me to get my head around some of its concepts. Thanks in advance!
Change:
if (dir = STOP)
to:
if (dir == STOP)
since you want to compare those two, not assign UP
to dir
. Same change is required for your other conditions in the else-if statements.
Tip: Enable compiler warnings in order to get informed about those pesky logical errors. For example in GCC, you could use the useful all warnings flag (Wall), like this:
gcc -Wall snake.c -o snake
to get:
54:19: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
56:24: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
58:26: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
60:26: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
62:27: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
where the the numbers at the start of each warning is in format line:column
, allowing you to find the line of code that emits the warning, and also the column at that line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.