Hello,
I have the following code and I need some help:
Snake.h
#pragma once
#include <vector>
#include <iostream>
enum direction { Up = 'w', Down = 's', Left = 'a', Right = 'd' };
class snake
{
private:
direction dir;
struct SNAKE
{
int x;
int y;
char body;
};
std::vector<SNAKE> Snake;
public:
snake();
void startPos();
//void checkValidMove(direction dir);
void move(direction dir);
};
Snake.cpp
#include "snake.h"
#include <iostream>
#include <Windows.h>
snake::snake()
{
Snake.emplace_back(SNAKE{ 10,12,'@' });
Snake.emplace_back(SNAKE{ 10,13,'o' });
Snake.emplace_back(SNAKE{ 10,14,'o' });
}
void snake::startPos()
{
COORD coord;
for (int i = 0; i < Snake.size(); i++)
{
coord.X = Snake[i].x;
coord.Y = Snake[i].y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << Snake[i].body;
}
}
//continuos move of the snake in a direction
void snake::move(direction dir)
{
COORD coord;
switch(dir)
{
case(Up):
for (int i = 0; i < Snake.size(); i++)
{
coord.X = Snake[i].x;
coord.Y = Snake[i].y-1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << Snake[i].body;
}
break;
case(Down):
for (int i = 0; i < Snake.size(); i++)
{
coord.X = Snake[i].x;
coord.Y = Snake[i].y + 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << Snake[i].body;
}
break;
case(Left):
for (int i = 0; i < Snake.size(); i++)
{
coord.X = Snake[i].x - 1;
coord.Y = Snake[i].y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << Snake[i].body;
}
break;
case(Right):
for (int i = 0; i < Snake.size(); i++)
{
coord.X = Snake[i].x + 1;
coord.Y = Snake[i].y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << Snake[i].body;
}
break;
}
}
Main.cpp
// Snake.cpp : Defines the entry point for the console application.
//
#include "snake.h"
#include "map.h"
#include <stdlib.h>
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
map MAP;
MAP.draw();
snake SNAKE;
SNAKE.startPos();
char input = _getch();
direction dir = Up;
SNAKE.move(dir);
system("pause");
return 0;
}
In Snake.cpp, the move(direction dir) method doesn't work as intended. I wanted it to continuously move the snake. (I know I will have to store the position of the snake's head and tail in order to properly change the direction, but for now, this is what I have). How do I exactly make it move when I press the 'w' key for example?
Also, is it ok to initialize in Main.cpp the dir with Up value?