I am making a whack-a-mole game for my class but I am stuck on the basic controls. I setup a basic board, using an array with a border using ascii symbols, with O representing the holes and X the hammer. When I go to move the hammer, lets say to the right, I have to press it twice for the hammer to move and I don't know why. It has to go through the whole loop 2 times before moving the hammer the right way.
#include <iostream>
#include <windows.h>
using namespace std;
bool gamerunning = true;
const int num = 20; //width
const int num2 = 40; //height
int x, y, score, perx, pery;
int hole1x, hole1y;
int hole2x, hole2y;
int hole3x, hole3y;
int hole4x, hole4y;
void setup(){
x= 5;
y=5;
hole1x = 15;
hole1y = 5;
hole2x = 15;
hole2y = 10;
hole3x = 25;
hole3y = 5;
hole4x = 25;
hole4y = 10;
score = 0;
perx = 15;
pery = 6;
}
//creating board
void draw(){
system("cls");
int i,j;
char Layout[num][num2];
for (i=0;i<num;i++){
for (j=0;j<num2;j++){
//boarder for play area
if (i==0 && j==0) //Top Left
Layout [i][j] = 201;
else if( i==0 && j==num2-1) //top right
Layout [i][j] = 187;
else if(i==num-1 && j==0) //bottom left
Layout [i][j] = 200;
else if(i ==num-1 && j==num2-1) //bottom right
Layout [i][j] = 188;
else if (i==0 || i==num - 1)
Layout[i][j]=205;
else if(j==0 || j==num2-1)
Layout [i][j] = 186;
else
Layout[i][j]=' ';
//holes
if(i == hole1y && j == hole1x)
Layout[i][j]= 'O';
if(i == hole2y && j == hole2x)
Layout[i][j]= 'O';
if(i == hole3y && j == hole3x)
Layout[i][j]= 'O';
if(i == hole4y && j == hole4x)
Layout[i][j]= 'O';
//character
if(i == pery && j == perx)
Layout[i][j]= 'X';
cout << Layout[i][j];
}
cout << endl;
}
}
void input(){
if(GetAsyncKeyState(VK_RIGHT)){
if(perx<=15)
perx +=10;
}
if(GetAsyncKeyState(VK_LEFT)){
if(perx>=25)
perx -=10;
}
if(GetAsyncKeyState(VK_DOWN)){
if(pery<=10)
pery +=5;
}
if(GetAsyncKeyState(VK_UP)){
if(pery>=10)
pery -=5;
}
if(GetAsyncKeyState(VK_ESCAPE)){
gamerunning = false;
}
}
void logic(){
}
int main(){
setup();
while(gamerunning == true){
draw();
input();
logic();
system("pause>nul");
}
system("cls");
cout << "GAME OVER" << endl;
return 0;
}
Here :
while(gamerunning == true)
{
draw();
input();
system("pause>nul");
logic();
}
You first draw your game board then you get the input, drawing will not happen until the next time loop execution, so your drawing will not update.
You need to put first draw call outside the loop (for initial drawing) then inside the loop call draw after input. like this :
draw();
while(gamerunning == true)
{
input();
draw();
system("pause>nul");
logic();
}
Related
you know the screensavers on old dvd players? I made it in the console using ascii but when it hits a corner it goes out of sight. I'm not sure what is happening, it should work. I'm just messing around and trying to learn so it's not a big deal but if anyone is interested in taking a look I would be very grateful! Also any general feedback and advice would be appreciated.
#include <iostream>
#include <windows.h>
using namespace std;
int width = 20;
int height = 10;
int iconX, iconY;
enum eDirection {UPLEFT,UPRIGHT,DOWNRIGHT,DOWNLEFT}dir;
int lastDir;
void Setup()
{
dir = UPRIGHT; //sets the direction and a
iconX = rand() % width + 1; //random starting point
iconY = rand() % height + 1;
}
void Draw()
{
system("cls");//clear the screen each frame
for (int y = 0; y < height + 2; y++) { // this goes from top to bottom of the grid
for (int x = 0; x < width + 2; x++) { // and then left to right to hit every square with these conditionals
if (y == 0 || y == height + 1) cout << "-"; //top and bottom border
if ((x == 0 || x == width + 1) && (y != 0 && y != height + 1)) cout << "|"; // both sides
if (x == iconX && y == iconY) cout << "0"; // this is the icon that will bounce around the screen
else if ((y != 0 && y != height + 1) && (x != 0 && x != width+1)) cout << " "; // if the icon wasn't drawn and
} //we aren't currently on a border it makes a space
cout << endl;
}
}
void Move()
{ //bounces on the sides
if (iconX == 1 || iconX == width) {
switch (lastDir) {
case 0:
dir = UPRIGHT; //this code checks if the icon is right
break; //next to a wall and depending on which
case 1: //direction it was moving it is given a
dir = UPLEFT; //new direction to move in
break;
case 2:
dir = DOWNLEFT;
break;
case 3:
dir = DOWNRIGHT;
break;
}
}
//bounces on the top and bottom
if (iconY == 1 || iconY == height) {
switch (lastDir) {
case 0:
dir = DOWNLEFT; //same thing down here but for
break; //the top and bottom
case 1:
dir = DOWNRIGHT;
break;
case 2:
dir = UPRIGHT;
break;
case 3:
dir = UPLEFT;
break;
}
}
switch (dir) {
case UPLEFT:
iconX--; //this code moves the icon
iconY--; //depending on which direction
break; //is currently saved in dir
case UPRIGHT:
iconX++;
iconY--;
break;
case DOWNLEFT:
iconX--;
iconY++;
break;
case DOWNRIGHT:
iconX++;
iconY++;
break;
}
lastDir = dir; //it saves the last direction
} //as a number to be used to do
//the bouncing
int main()
{
Setup();
while (true) {
Draw();
Move();
}
}
she's fixed! check her out. shout out to #JaMiT for the idea
#include <iostream>
#include <windows.h>
using namespace std;
int width = 20;
int height = 10;
int iconX, iconY;
enum Vertical {UP,DOWN}vert;
enum Horizontal {LEFT,RIGHT}hor;
int lastVert;
int lastHor;
void Setup()
{
vert = UP; //sets the direction and a
hor = LEFT;
iconX = rand() % width + 1; //random starting point
iconY = rand() % height + 1;
}
void Draw()
{
system("cls");//clear the screen each frame
for (int y = 0; y < height + 2; y++) { // this goes from top to bottom of the grid
for (int x = 0; x < width + 2; x++) { // and then left to right to hit every square with these conditionals
if (y == 0 || y == height + 1) cout << "-"; //top and bottom border
if ((x == 0 || x == width + 1) && (y != 0 && y != height + 1)) cout << "|"; // both sides
if (x == iconX && y == iconY) cout << "0"; // this is the icon that will bounce around the screen
else if ((y != 0 && y != height + 1) && (x != 0 && x != width+1)) cout << " "; // if the icon wasn't drawn and
} //we aren't currently on a border it makes a space
cout << endl;
}
}
void Move()
{
if (iconX == 1 || iconX == width)
if (lastHor == 0) //0 is left
hor = RIGHT;
else
hor = LEFT;
if (iconY == 1 || iconY == height)
if (lastVert == 0) //0 is up
vert = DOWN;
else
vert = UP;
if (vert == UP)iconY--;
else iconY++;
if (hor == LEFT)iconX--;
else iconX++;
lastVert = vert;
lastHor = hor;
}
int main()
{
Setup();
while (true) {
Draw();
Move();
}
}
I working on my project this project have a frame to [100] x [25] matrix and i try to add animation but my character is going left but it's not going right.
i tried with "counter" variable but its not work.
int counter = 1;
int counter2 = 1;
int left_border = 1;
int matris1 = sizeof(map)/100;
int matris2 = sizeof(map[0])/4;
int startx = 19;
int starty = 8;
while (true)
...
int right = 0, left = 0;
...
for (int a = 0; a < matris2; a++)
cout << "\n#"; //i have this because i make it square map.
for (int k = 0; k < matris1 - 2; k++)
{
if (left == 1)
{
if (((startx+2)-counter) == left_border)
{
counter = 0;
//cout << "SINIR!!"<< endl ;
}
if (k == (startx-counter) and a == starty)
{
counter += 1;
cout << "O";
}
else {
cout << " ";
}
}
else if (right == 1)
{
if (k == (startx+counter2) and a == starty)
{
counter2 += 1;
cout << "O";
}
its need to be going right but its not.
if you need full code.
https://codeshare.io/UbKVU
[![This is the map and "O" is the character]
https://i.stack.imgur.com/uyGQo.png
The code is very difficult to follow - you should have a coordinate system. I've made a simple example below. Update the player coordinate when a key is pressed and redraw the map x by y position, if the player is there then draw the 'O', otherwise if its a wall draw an 'X' (in this case), otherwise draw a space ' '.
using namespace std;
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define MAPW 15 // map width
#define MAPH 15 // map height
int map[MAPW][MAPH];
#define WALL 1
#define EMPTY 0
void initmap()
{
// just set the map to have walls around the border
for (int x = 0; x < MAPW; x++)
{
for (int y = 0; y < MAPH; y++)
{
if (x == 0 || y == 0 || x == (MAPW - 1) || y == (MAPH - 1))
map[x][y] = WALL;
else
map[x][y] = EMPTY;
}
}
}
int px = MAPW / 2; // player x
int py = MAPH / 2; // player y
void main()
{
initmap(); // initialize map
cout << "Press A/W/S/D to begin and move";
while (1)
{
if (kbhit()) // key pressed?
{
switch (getch()) // which key?
{
case 'a':
if (px > 0 && map[px - 1][py] != WALL) // can go left?
px--; // update x coordinate
break;
case 'd':
if (px < (MAPW-1) && map[px + 1][py] != WALL) // can go right?
px++; // update x coordinate
break;
case 'w':
if (py > 0 && map[px][py - 1] != WALL) // can go up?
py--; // update y coordinate
break;
case 's':
if (py < MAPH && map[px][py + 1] != WALL) // can go down?
py++; // update y coordinate
break;
}
// update map - clear screen and redraw
system("CLS");
// draw map each line
for (int y = 0; y < MAPH; y++)
{
for (int x = 0; x < MAPW; x++)
{
// its a wall?
if (map[x][y] == WALL)
cout << "X";
else
{
// is the player there?
if (x == px && y == py)
{
// draw the player
cout << "O";
}
else // empty space
cout << " ";
}
}
// next line
cout << "\n";
}
}
}
}
Edit #2: Ok, I did another *.cpp to check if the codes for Arrow Keys were right. Doing that, I noticed keyPressed variable in detectKeyPressing() had the wrong type of variable, so I changed it from char to int and changed the codes.
Once I did that, it worked. Now I have put the limits, so the Player cannot go outside the square. But I have another problem, the movement is too tough and if you press the keys too fast, the instructions run with a annoying delay. I know I should use either Sleep(ms) or Delay(ms), but I don't know when I should use it.
This is the new code:
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <Windows.h>
using namespace std;
int detectKeyPressing() {
// 0: Escape
// 1: Enter
//2: Up
// 3: Left
// 4: Down
// 5: Right
int keyPressed = 0;
while (keyPressed != 27) {
if (keyPressed == 0 || keyPressed == 224) {
keyPressed = _getch(); //First value of _getch() when any of the arrow keys are pressed is "224", the next one is the code depending of which arrow you pressed
}
else if (keyPressed == 13) {
return 1;
}
else {
switch (keyPressed) {
//Up
case 72:
return 2;
break;
//Left
case 75:
return 3;
break;
//Down
case 80:
return 4;
break;
//Right
case 77:
return 5;
break;
//Default
default:
return -1;
break;
}
}
};
return 0;
};
int mainMenu() {
int enterPressed = 0;
cout << "Press Enter to Begin, or ESC to exit" << endl;
enterPressed = detectKeyPressing();
system("cls");
return enterPressed;
};
void draw(int playerX, int playerY) {
//Player coordinates, made for testing
cout << "Player.x = " << playerX << endl << "Player.y = " << playerY << endl;
//The next 8 spaces go blank
for (int i = 1; i < 8; i++) {
cout << endl;
}
//Square Limit Making
//Top Limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
cout << endl;
//Border limits and inside the Square
for (int ih = 1; ih < 30; ih++) {
//Left border
cout << "|";
//Inside the Square
for (int iw = 1; iw < 78; iw++) {
if (iw == playerX && ih == playerY) {
cout << "a"; //This is supposed to be ♥ but I don't know how to put it in the screen with a cout
}
else {
cout << " ";
}
}
//Right border
cout << "|" << endl;
}
//Bottom limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
}
int main() {
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 1;
cci.bVisible = FALSE;
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
int pressedKey = -1; //Creating pressedKey at Start
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 1;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
pressedKey = detectKeyPressing(); // Save detectKeyPressing()'s return in pressedKey
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (pressedKey == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (pressedKey > 1 && pressedKey < 6) {
switch (pressedKey) {
//Up
case 2:
Sleep(200);
if (Player.y == Player.speed) {
Player.y = Player.speed; //Top Limit
}
else {
Player.y -= Player.speed;
}
break;
//Left
case 3:
Sleep(200);
if (Player.x == Player.speed) {
Player.x = Player.speed; //Left Limit
}
else {
Player.x -= Player.speed;
}
break;
//Down
case 4:
Sleep(200);
if (Player.y == 30 - Player.speed) {
Player.y = 30 - Player.speed; //Bottom Limit
}
else {
Player.y += Player.speed;
}
break;
//Right
case 5:
Sleep(200);
if (Player.x == 78 - Player.speed) {
Player.x = 78 - Player.speed; //Right Limit
}
else {
Player.x += Player.speed;
}
break;
};
system("cls"); //Erase all
draw(Player.x, Player.y); //Redraw everything, with Player.x or Player.y modified
};
};
};
return 0;
};
Edit #1: I fixed the mistakes you told me, here's the main function modified. It isn't working though.
int main(){
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 50;
cci.bVisible = FALSE; //Changed "TRUE" to "FALSE"
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
int pressedKey = -1; //Creating pressedKey at Start
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 2;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
pressedKey = detectKeyPressing(); //Save detectKeyPressing()'s return in pressedKey
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (pressedKey == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (pressedKey > 1 && pressedKey < 6) {
cout << "There's no problem in Else If statement"; //Couts made for testing
switch (pressedKey) {
cout << "There's no problem in Switch statement";
//Up
case 2:
Player.y -= Player.speed;
cout << "You moved Up";
break;
//Left
case 3:
Player.x -= Player.speed; //Fixed Left movement
cout << "You moved Left";
break;
//Down
case 4:
Player.y += Player.speed;
cout << "You moved Down";
break;
//Right
case 5:
Player.x += Player.speed;
cout << "You moved Right";
break;
};
//system("cls"); //Erase all
//draw(Player.x, Player.y); //Redraw everything, with Player.x and Player.y supposedly modified
};
};
};
return 0;
};
Initial Post: I'm trying to do something like an Undertale normal fight and now I'm doing the "dodging attacks" part, but I'm stuck at making the player move (Yep, that "a") because it didn't update when I press an arrow key (for movement). It is supposed to draw, and put the Player in Player.x and Player.y, so I did something in main() to edit these variables depending on the arrow key you pressed, and then erase and re-draw with the Player.x or Player.y modified.
Here's the code:
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <Windows.h>
using namespace std;
int detectKeyPressing(){
// 0: Escape
// 1: Enter
// 2: Up
// 3: Left
// 4: Down
// 5: Right
char keyPressed = 0;
while (keyPressed != 27){
if(keyPressed == 0){
keyPressed = _getch();
}
else if(keyPressed == 13){
return 1;
}
else{
switch (keyPressed) {
//Up
case 65:
return 2;
break;
//Left
case 68:
return 3;
break;
//Down
case 66:
return 4;
break;
//Right
case 67:
return 5;
break;
//Default
default:
return -1;
break;
}
}
};
return 0;
};
int mainMenu(){
int enterPressed = 0;
cout << "Press Enter to Begin, or ESC to exit" << endl;
enterPressed = detectKeyPressing();
system("cls");
return enterPressed;
};
void draw(int playerX, int playerY) {
//Player coordinates, made for testing
cout << "Player.x = " << playerX << endl << "Player.y = " << playerY << endl;
//The next 8 spaces go blank
for (int i = 1; i < 8; i++) {
cout << endl;
}
//Square Limit Making
//Top Limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
cout << endl;
//Border limits and inside the Square
for (int ih = 1; ih < 30; ih++) {
//Left border
cout << "|";
//Inside the Square
for (int iw = 1; iw < 78; iw++) {
if (iw == playerX && ih == playerY){
cout << "a"; //This is supposed to be ♥ but I don't know how to put it in the screen with a cout
}
else {
cout << " ";
}
}
//Right border
cout << "|" << endl;
}
//Bottom limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
}
int main(){
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 50;
cci.bVisible = TRUE;
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 2;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (detectKeyPressing() == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (detectKeyPressing() > 1 && detectKeyPressing() < 6) {
switch (detectKeyPressing()) {
//Up
case 2:
Player.y -= Player.speed;
break;
//Left
case 3:
Player.x += Player.speed;
break;
//Down
case 4:
Player.y += Player.speed;
break;
//Right
case 5:
Player.x += Player.speed;
break;
};
system("cls"); //Erase all
draw(Player.x, Player.y); //Redraw everything, with Player.x and Player.y supposedly modified
};
};
};
return 0;
};
I did a few tests and it seems that the else if in "//If any of the Arrow Keys is Pressed" part isn't running but I don't know why.
I would really appreciate any help you can provide. Sorry if anything isn't well written, I'm not a native english speaker.
Where you have this comment
//Draw if proyectile is moving - not yet add a variable to save your pressed key, something like
int pressedKey = detectKeyPressing();
Then, use that variable to check which condition is met within your if-else.
What’s happening is that you’re calling your function, thus asking/waiting for an input each time a condition is being checked.
I am trying to write an application, in which the user inputs an integer
1 = up,
2 = down
3 = left
4 = right and
x : moves along the 3x3 grid.
I am not sure what I have done wrong, so any help would be appreciated.
#include "stdafx.h"
#include <iostream>
using namespace std;
char player = 'x';
char grid[3][3] = {{ player, '.' ,'.'},{'.', '.', '.' },{'.', '.', '.' } };
void Draw() {
for (int row = 0; row <= 2; row++) {
for (int col = 0; col <= 2; col++) {
cout << grid[row][col];
}
cout << endl;
}
}
int main() {
int posX = 0;
int posY = 0;
int in;
Draw();
while (1) {
cin >> in;
if (in == 1) {
grid[posY][posX] = '.';
posY = posY - 1;
grid[posY][posX] = player;
}
else if (in == 2) {
grid[posY][posX] = '.';
posY = posY + 1;
grid[posY][posX] = player;
}
else if (in == 3) {
grid[posY][posX] = '.';
posX = posX - 1;
grid[posY][posX] = player;
}
else if (in == 4) {
grid[posY][posX] = '.';
posX = posX + 1;
grid[posY][posX] = player;
}
else {
grid[posY][posX] = player;
}
system("cls");
Draw();
}
cin.get();
return 0;
}
I have compile it and everything is ok.... But you must check if the player is on the max side of grid, and then if player want to move you must stop him, because of wall of course;>
Example :
while (1)
{
cin >> in;
if (in == 1)
{
if(posY>0) // HERE
{
grid[posY][posX] = '.';
posY = posY - 1;
grid[posY][posX] = player;
}
}
...
}
#include <iostream>
#include <fstream>
using namespace std;
void printArray(void);
char grid[6][34] = {'0'}; // empty floor
void movement(int command);
int direction = 2; // 1 for north, 2 for east, 3 for south, 4 for west. Turtle starts facing east.
void turtleMovement(int, int);
int spacesMoved; // used after F command.
int yCoord = 0; // Y position assumed 0;
int xCoord = 0; // X position assumed 0;
bool pen = 0; // assume pen is up
void initialize(void);
char command; // U for pen up, D for pen Down, R for right turn, L for left turn, F for forward movement with spaces moved, P for array print, and Q for end.
int main(){
initialize();
ifstream infile;
infile.open("commands.txt");
infile >> command;
while(command != 'Q'){
if(command == 'U'){
pen = 0;
}
else if(command == 'D'){
pen = 1;
}
if(command == 'R' || command == 'L'){
movement(command);
}
if(command == 'F'){
infile >> spacesMoved;
turtleMovement(yCoord, xCoord);
}
else if(command == 'P')
printArray();
infile >> command;
}
}
//=====================================================================================================================================================
//
// Function Name: intialize
//
// Pre: none
//
// Post: sets every element of the array grid to all zeroes.
//
//======================================================================================================================================================
void initialize()
{
for(int i = 0; i < 6; i++){ //
for(int j = 0; j < 34; j++){ // Initialization of Array to all zeros.
grid[i][j] = '0'; //
}
}
}
//=====================================================================================================================================================
//
// Function Name: printArray
//
// Pre: none
//
// Post: prints out the array grid to the console
//
//======================================================================================================================================================
void printArray()
{
for(int i = 0; i < 6; i++)
for(int j = 0; j < 34; j++){
grid[i][j];
cout << grid[i][j] << (j == 33 ? "\n" : ""); // if the row gets to 33 characters a new line will be made.
}
}
void movement(int command)
{
if (direction == 2){ // direction is east
if (command == 'R')
direction = 3;// if you're facing east and you turn right you're now facing south
else if (command == 'L') // if you're facing east and you turn left you're now facing north.
direction = 1;
}
else if (direction == 3) // direction is south
{
if (command == 'R') // turn right to go west
direction = 4;
else if (command == 'L') // turn left to go east
direction = 2;
}
else if (direction == 4) // direction is west
{
if (command == 'R') // right for north
direction = 1;
else if (command == 'L') // left for south
direction = 3;
}
else if (direction == 1) // direction is north
{
if (command == 'R') // right for east
direction = 2;
else if (command == 'L') // left for west
direction = 4;
}
}
void turtleMovement(int y, int x){
if(direction == 2){
int i = y;
for(int j = x; j < x + spacesMoved; j++){
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
xCoord += spacesMoved - 1; //updates the x coordinate
}
else if(direction == 3){
for(int i = y; i < y + spacesMoved; i++){
int j = x;
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
yCoord += spacesMoved - 1; //updates the y coordinate
}
else if(direction == 4){
int i = y;
for(int j = x; j > x - spacesMoved; j++){
if(pen == 1)
grid[i][j] = '1';
else if (pen == 0)
grid[i][j] = '0';
}
xCoord -= spacesMoved - 1; //updates the x coordinate
}
else if(direction == 1){
for(int i = y; i > y- spacesMoved; i++){
int j = x;
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
yCoord -=spacesMoved - 1; //updates the y coordinate
}
}
I'm having extreme frustration with my program, when I try and do a 180 turn, i.e. a R R or a L L the whole program just freezes. Is it something with my logic? or a syntax? because it doesn't give me any of those errors.
Sorry, but your program is annoying me and it is a little hard to read.
Try this:
struct Position
{
int x;
int y;
};
struct Direction_Vector : Position
{
unsigned int direction;
};
const unsigned int MAX_DIRS = 4u;
void movement(char command,
const Direction_Vector present_dir,
Direction_Vector& new_dir)
{
unsigned int dir = present_dir.direction;
switch (command)
{
case 'R': // rotate clockwise;
dir = (dir + 1) % MAX_DIRS;
break;
case 'L': // rotate counter clockwise
dir = (dir + (MAX_DIRS - 1)) % MAX_DIRS;
break;
case 'M': // Move one position in the given direction
switch (dir)
{
case 0: // Assume north, Y decreases
new_dir.y = present_dir.y - 1;
break;
case 1: // Assume east, X increases
new_dir.x = present_dir.x + 1;
break;
case 2: // Assume south, Y increases
new_dir.y = present_dir.y - 1;
break;
case 3: // Assume west, X decreases
new_dir.x = present_dir.x - 1;
break;
}
break;
default:
break;
}
new_dir.direction = dir;
}
You may be able to optimize the movement section by using algebra and realizing a relationship between the direction and the ordinate that gets adjusted.
Also, I have not put in any boundary checking.
Sorry if I ruined your day by simplifying a lot of your posted code.
Use a debugger and step through the above code and figure out if it handles the 180 degree turns correctly.
Edit 1: Truth Tables
Here are the truth tables for the movement and ordinate changes
Direction | Delta X | Delta Y| // "delta" means change
----------+---------+--------+
0 | 0 | -1 |
----------+---------+--------+
1 | +1 | 0 |
----------+---------+--------+
2 | 0 | +1 |
----------+---------+--------+
3 | -1 | 0 |
----------+---------+--------+
Can you come up with an algebraic equation for the ordinates based on the direction?