Hi there, first time posting on SO, so please go gentle on me if I manage to fudge it up. I'm also pretty new to coding, so any push in the right direction to make me find the solution myself would be appreciated.
What should happen: There is a game field which is made from an array of arrays of strings. The player (P) should be able to move one field per loop.
What happens: For UP, DOWN and LEFT, it works. But when pressing RIGHT, the player travels as far as he can instead of only one space.
What it might be: I assume it has something to do with changing the position of P inside the array, but I can't find the reason why it would be wrong.
#include "iostream"
#include "conio.h"
#include "typeinfo"
#include <cstdlib>
#include <string>
#include <array>
#include <Windows.h>
void main()
{
// Utilities
bool wants_to_exit = false;
char move;
// Block types
std::string a = " ";
std::string W = "###";
std::string P = " O ";
// Map
std::string fields[10][10] = {
{ W , W , W , W , W , W , W , W , W , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , a , P , a , a , W , a , a , a , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , a , a , a , a , a , a , a , a , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , a , a , a , a , W , a , a , a , W },
{ W , W , W , W , W , W , W , W , W , W }
};
// Main Loop
while (!wants_to_exit)
{
// Display Map on Console
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
std::cout << fields[x][y];
}
printf("\n");
}
std::cout << std::endl;
std::cout << _kbhit() << std::endl;
std::cout << "\n\nUse the arrow Keys to move" << std::endl;
move = _getch();
// Movement
if (move == 72) // UP
{
for (int x = 1; x < 10; x++)
{
for (int y = 1; y < 10; y++)
{
if (fields[y][x] == P)
{
if (fields[y-1][x] == a)
{
fields[y][x] = a;
fields[y-1][x] = P;
move = 0;
break;
}
}
}
}
}
else if (move == 80) // DOWN
{
for (int x = 1; x < 10; x++)
{
for (int y = 1; y < 10; y++)
{
if (fields[y][x] == P)
{
if (fields[y+1][x] == a)
{
fields[y][x] = a;
fields[y+1][x] = P;
move = 0;
break;
}
}
}
}
}
else if (move == 75) // LEFT
{
for (int x = 1; x < 10; x++)
{
for (int y = 1; y < 10; y++)
{
if (fields[y][x] == P)
{
if (fields[y][x-1] == a)
{
fields[y][x] = a;
fields[y][x-1] = P;
move = 0;
break;
}
}
}
}
}
else if (move == 77) // RIGHT
{
for (int x = 1; x < 10; x++)
{
for (int y = 1; y < 10; y++)
{
if (fields[y][x] == P)
{
if (fields[y][x+1] == a)
{
fields[y][x] = a;
fields[y][x+1] = P;
move = 0;
break;
}
}
}
}
}
else if (move == 113) // QUIT (press q)
{
wants_to_exit = true;
}
Sleep(1);
system("cls");
}
}