This program is a simple Tic Tac Toe game between a player and the computer. The computer just generates a random space to move to if said space is not already occupied. Also, I have the x-coordinates on the vertical axis while the y-coordinates are on the horizontal axis. I did this because I use a two dimensional array, and that is just how they are structured.
When running the program, some of the spaces are faulty and I cannot find out why. When the user inputs the point (0,2) the program also fills in the point (1,0) and vise versa. This also occurs with the points (1,2) and (2,0).
#include<iostream>
#include<string>
#include<stdlib.h>
#include<ctime>
using namespace std;
int board[2][2];
int chooseFirstPlayer();
void userMove(int boardArray[2][2]);
void compMove(int boardArray[2][2]);
int checkIfWinner(int boardArray[2][2]);
void displayBoard(int boardArray[2][2]);
int main(){
srand(time(NULL));
int x,y,winner;
for(x = 0; x <= 2; x++){ //sets the enitre board array to 0
for(y = 0; y <= 2; y++){
board[x][y] = 0;
}
}
if (chooseFirstPlayer() == 1){ //the user gets to movve first
do{//it will loop this until there is a winner
displayBoard(board);
userMove(board);
displayBoard(board);
winner = checkIfWinner(board);
if (winner == 0){//after the player moves, it will see if he won. If not, then the computer willbe able to move.
compMove(board);
displayBoard(board);
winner = checkIfWinner(board);
}
}while (winner == 0);//it will loop until a winner is found
}
else{//same structure as above just slightly altered to allow the computer to move first
do{
compMove(board);
displayBoard(board);
winner = checkIfWinner(board);
if (winner == 0){
userMove(board);
displayBoard(board);
winner = checkIfWinner(board);
}
}while(winner == 0);
}
if (winner = 1){
cout << "Congratulations, you won!";
}
else if (winner = 2){
cout << "Sorry, you lost!";
}
}
int chooseFirstPlayer(){//randomly genereate a number 1 or 2 to choose who moves first
return rand() % 2 + 1;
}
void userMove(int boardArray[2][2]){
int userX, userY;
do{
cout << "Enter an x coordinate: "<<endl;
cin >> userX;
cout << "Enter a y coordinate: "<<endl;
cin >> userY;
if (boardArray[userX][userY] != 0){
cout << "That loaction is already occupied"<<endl;
}
}while(boardArray[userX][userX] != 0);
boardArray[userX][userY] = 1;
}
void compMove(int boardArray[2][2]){
int compX,compY;
do{
compX = rand() % 3;
compY = rand() % 3;
}while(boardArray[compX][compY] != 0);
boardArray[compX][compY] = 2;
}
int checkIfWinner(int boardArray[2][2]){
if(boardArray[0][0] == boardArray[0][1] && boardArray[0][1] == boardArray[0][2]){ //across
return boardArray[0][0];}
else if (boardArray[1][0] == boardArray[1][1] && boardArray[1][1] == boardArray[1][2]){
return boardArray[1][0];}
else if (boardArray[2][0] == boardArray[2][1] && boardArray[2][1] == boardArray[2][2]){
return boardArray[2][0];}
else if (boardArray[0][0] == boardArray[1][0] && boardArray[1][0] == boardArray[2][0]){//down
return boardArray[0][0];}
else if (boardArray[0][1] == boardArray[1][1] && boardArray[1][1] == boardArray[2][1]){
return boardArray[0][1];}
else if (boardArray[0][2] == boardArray[1][2] && boardArray[1][2] == boardArray[2][2]){
return boardArray[0][2];}
else if (boardArray[0][0] == boardArray[1][1] && boardArray[1][1] == boardArray[2][2]){//diagonal
return boardArray[0][0];}
else if (boardArray[2][0] == boardArray[1][1] && boardArray[1][1] == boardArray[0][2]){
return boardArray[2][0];}
else{
return 0;
}
}
void displayBoard(int boardArray[2][2]){
system("CLS");
cout <<" "<<" Y1 "<<" Y2 "<<" Y3 "<<endl;
cout <<" X1 "<< "__"<<boardArray[0][0]<<"__|__"<<boardArray[0][1]<<"__|__"<<boardArray[0][2]<<"__"<<endl;
cout <<" X2 "<< "__"<<boardArray[1][0]<<"__|__"<<boardArray[1][1]<<"__|__"<<boardArray[1][2]<<"__"<<endl;
cout <<" X3 "<< " "<<boardArray[2][0]<<" | "<<boardArray[2][1]<<" | "<<boardArray[2][2]<<" "<<endl;
}
My IDE is Dev-C++ (5.4.2)
Your array is 2x2 and you do:
for(x = 0; x <= 2; x++){ //sets the enitre board array to 0
for(y = 0; y <= 2; y++){
board[x][y] = 0;
}
}
and you access memory you shouldn't. That means you are going out of bounds!
Here x and y will take a value equal to 2 eventually.
Indexing of an array starts from 0 until it's size - 1.
So, you could use an array of 3x3, or change your code (and the function checkIfWinner that goes until 2).
Side note:
You have missed the equality operator here:
if (winner = 1){
cout << "Congratulations, you won!";
}
else if (winner = 2){
cout << "Sorry, you lost!";
}
What will happen if you leave it as is? The assignment will take place and will result in logical true, thus the first condition will be always true (and the second, but the code won't go that far).
So, change = with ==.
Related
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();
}
I was working on a project to make ball/object hit game in c++.
I used system("cls"); to clear the screen and display Game Over message. User scores are being reset to zero 0. while removing system("cls"); doesn't effect the score of user. Is there any good way to clear the screen without clearing the values of vairables?
Here is an example code. This is the function for level 2 of my game.
I have commented on the line which is causing me this problem.
int level_2(string user_name,int scores)
{
system("CLS");
for(int i=5;i>0;i--)
{
cout<< "\n\n\n\n\n_________________________________\n";
cout<< "| |\n";
cout<< "| level 2 starts in "<<i<<" seconds\t|\n";
cout<< "| |\n";
cout<< "_________________________________\n";
Sleep(1000);
system("CLS");
}
system("CLS");
string s = "=======";
string h = " ";
int i=5, x=10, y=29;
cout << "Press Arrow Keys to move, press q to quit\tWelcome "<<user_name<<"!\n";
cout<< "_________________________________\n";
for(int i=0;i<31;i++)
cout<< "| |\n";
cout<< "_________________________________\n";
int x1 = rand() % 19 + 1,
y1 = rand() % 19+ 1,
x2 = rand() % 19 + 1,
y2 = rand() % 19 + 1,
x3=2,
y3=2,
incX=-1,
incY=-1,
incXX=1,
incYY=1,
speed=70;
while (true){
gotoxy(x, y);
cout << s;
if (kbhit())
{
gotoxy(x, y);
cout << h;
i = getch();
if (i == 'q')
{
break;
}
if (i == UP && y>UPLIMIT)
y=y-2;
else if (i == DOWN && y<LOWLIMIT)
y=y+2;
if (i == LEFT && x>LEFTLIMIT)
x = x - 3;
else if (i == RIGHT && x<RIGHTLIMIT-6)
x = x + 3;
}
drawObject(x3, y3);
print_scores(scores);
hideObject(x3, y3);
if(y1<LOWLIMIT)
drawObject(x1, y1);
if(y2<LOWLIMIT)
drawObject(x2, y2);
Sleep(speed);// to slow down the process
hideObject(x1, y1);
hideObject(x2, y2);
if (x1 == RIGHTLIMIT) incX = -1;
if (x1 == LEFTLIMIT) incX = 1;
if (y1 == LOWLIMIT)
{
incY = 0;
speed=40;
}
if (x1>x-2 && x1<x+7 )
{ if(y1==y-1)
{
incY=-1;
scores=scores+10;
total_scores=total_scores+10;
}
}
if (y1 == UPLIMIT) incY = 1;
x1 += incX;
y1 += incY;
if (x2 == RIGHTLIMIT) incXX = -1;
if (x2 == LEFTLIMIT) incXX = 1;
if (y2 == LOWLIMIT )
{
incYY = 0;
speed=40;
}
if (x2>x-2 && x2<x+7 )
{ if(y2==y-1){
incYY=-1;
scores=scores+10;
total_scores=total_scores+10;
}
}
if (y2 == UPLIMIT) incYY = 1;
x2 += incXX;
y2 += incYY;
speed=speed-1;
if (speed<25)
speed=25;
if(incY==0 && incYY==0)
{
system("cls");
cout<<"\n\n\n\tG";Sleep(50);cout<<"a";Sleep(50);cout<<"m";Sleep(50);cout<<"e";Sleep(50);cout<<" ";Sleep(50);cout<<"O";Sleep(50);cout<<"v";Sleep(50);cout<<"e";Sleep(50);cout<<"r";
system("pause>nul");
system("cls"); //this line is clearing my scores
break;
}
if(incY==0 && incYY==0)
break;
if(scores>=score2)
{
ofstream out("records.txt");
out<<scores;
out.close();
ofstream out1("total_scores.txt");
out1<<total_scores;
out1.close();
break;
}
}
}
system("cls") don't clear the value of variables. If you have problems with it, save the variables in a file before you clear the screen and load after the system("cls") line.
#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?
I'm now working on a Tic Tac Toe project. I'm having the problem that whenever I input into the console an ordinate,for example [6][0] (and the program will put the mark 'X' or 'O' into that position) for an array with the size of [15][15],it will automatically save the mark 'X' or 'O' into another position which is not in the array range (in my case is [5][15]).This is my program (P/S: I'm Vietnamese so just ignore the parts that are in Vietnamese):
int size = 15;
int inputAmount;
int inputX = 0;
int inputY = 0;
char board[15][15];
bool checkWin = false;
char mark = 'X';
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
}
// Lay-coordinate of the muon practice player list
void takeInput() {
do {
// Lay gia tri toa do x
do {
cout << "Please choose the horizontal (rightward) number (smaller than " << size + 1 << "): ";
cin >> inputX;
} while ((inputX > size) || (inputX <= 0));
// Lay y coordinate values
do {
cout << "Please choose the vertical (downward) number (smaller than " << size + 1 << "): ";
cin >> inputY;
} while ((inputY > size) || (inputY <= 0));
inputX--;
inputY--;
if (board[inputX][inputY] != '.')
cout << "Already chosen!" << endl ;
} while (board[inputX][inputY] != '.');
board[inputX][inputY] = mark;
if (mark == 'X')
mark = 'O';
else
mark = 'X';
cout << endl << endl << endl;
}
// Hien game board on the screen
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (; y < size ; y++)
{
for (; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
x = 0;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
x,y = 0;
takeInput();
inputAmount++;
}
}
// At first preparation game board
void prepareGameboard () {
int x,y;
for (; y < size ; y++)
{
for (; x < size ; x++)
{
board[x][y] = '.' ;
}
x = 0;
}
}
int main(array<System::String ^> ^args)
{
char reset = 'y';
do {
prepareGameboard();
loadGameboard();
checkWin = 0;
inputAmount = 0;
cout << "Do you want to replay ? (y/n): ";
cin >> reset;
if ((reset == 'y') || (reset == 'Y'))
{
system("CLS");
}
} while ((reset == 'y') || (reset == 'Y'));
return 0;
}
I would change x,y = 0 to x = y = 0 at line 123 in the code you pasted. And also add return 0 to the function checkWinLose().
You are not initializing the values for x and y in ther for's.
Try to use :
void prepareGameboard () {
int x,y;
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
board[x][y] = '.' ;
}
}
}
And:
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
takeInput();
inputAmount++;
}
}
Also, like #Heinz said, and a return 0; at the end of the checkWinLose function;
Looking at your code, I believe the you are assuming the int always are initialized with 0 and that checkWinLose will return 0 by the default. Local variables have undefined initialization values and when no explicity return is called, the function just return so 'garbage' value.
Try to always add the returned value to the functons and initialize your variables (specially counters).
Update
This is how the function checkWinLose should be with the return 0;
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
return 0; //<- Returning false if the all other tests failed
}
I want to ask user to set a compass direction as a char, using n for north, e for east etc and so on, or to use default value which is set to North. e.g (0,0,'n').
Then I want to make it randomly move 100 times in any direction. I am now confused on the loop inside my class. I don't know where should I add the loop. Also, the output shows me the values I have typed.
I would appreciate your help !
output example:
0===0---n
#include<iostream>
#include<string>
#include<iomanip>
#include<ctime>
using namespace std;
class bug
{
public:
bug();
bug(int x_pos, int y_pos, char direction);
void turn(char direction);
void move(int x, int y,char direction);
int get_X() const;
int get_Y() const;
char get_direction() const;
private:
int x;
int y;
char direction;
};
bug::bug(int x_pos, int y_pos, char d)
{
x = x_pos;
y = y_pos;
direction = d;
}
bug::bug()
{
x = 0;
y = 0;
direction = 'n';
}
void bug::turn(char direction)
{
int num = 1 + rand() % 3;
if (direction == 'n')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'n';
}
else if (direction == 'w')
{
if (num == 1)
direction = 'w';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
else if (direction == 's')
{
if (num == 1)
direction = 's';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'e';
}
else if (direction == 'e')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
}
void bug::move(int x, int y, char direction)
{
if (direction == 'n')
y = y + 1;
else if (direction == 'w')
x = x - 1;
else if (direction == 's')
y = y - 1;
else if (direction == 'e')
x = x + 1;
}
int bug::get_X() const
{
return x;
}
int bug::get_Y() const
{
return y;
}
char bug::get_direction() const
{
return direction;
}
void display(bug start)
{
cout << start.get_X()<<"==="<<start.get_Y() << "---"<<start.get_direction() << endl;
}
int main()
{
srand(time(0));
bug first;
int choice;
cout << custom mode(1) or default mode(2) ? ";
cin >> choice;
if (choice == 1)
{
int x, y;
char dir;
cout << "the x axis: ";
cin >> x;
cout << "the y axis: ";
cin >> y;
cout << "the direction: ";
cin >> dir;
bug first(x, y, dir);
//first.turn(dir);
//first.move(x,y);
display(first);
}
else
{
for(int j =0;j<100;j++)
{
bug first;
//first.turn;
//first.move();
//for(int j =0;j<100;j++)
display(first);
}
}
system("pause");
}
There is a missing " on the line:
cout << custom mode(1) or default mode(2) ? ";
I believe the intention is to have the double quote in front of the word custom like so:
cout << "custom mode(1) or default mode(2) ? ";
Start Modification
There are some things to consider that will be more clearly seen by stepping through with the debugger and observing the internal variables versus the passed by value parameters. The passed by value parameters happen to be named the same as the internal class data member variables. Please think through these things and decide what the desired behavior is for the turn and move functions for both mode choices.
End Modification