#include<iostream>
#include <stdlib.h>
usingnamespace std;
int main(){
int r = 5, c = 5;;
char player = 'P';
char choice = 0;
int dr = 2, dc = 2;//diamond in row //dimond in column
int br = 3, bc = 3;
int pr = 1, pc = 1;
int score = 0;
int k = 1;
char d = 'D';
char d1 = 'D';
char b = 'B';
int p = 0;
while (score != 25){
if (pc == dc && pr == dr) {
score++;
int newdc = rand() % 5;
int newdr = rand() % 5;
while (newdc == dc) newdc = rand() % 5;
while (newdr == dr) newdr = rand() % 5;
dc = newdc;
dr = newdr;
}
for (int i = 1; i <= r; i = i + 1){
for (int j = 1; j <= c; j = j + 1){
if (i == pr&&j == pc){
cout << " " << player;
}
elseif (i == dr&&j == dc){
cout << " " << d;
}
elseif (i == br&&j == bc){
cout << " " << b;
}
else{
cout << " *";
}
}
cout << endl;
}
cout << " " << score;
cout << "Enter your choice= ";
cin >> choice;
if (choice == 'd' || choice == 'D'){
pr = pr + 1;
}
if (choice == 'r' || choice == 'R'){
pc = pc + 1;
}
if (choice == 'l' || choice == 'L'){
pc = pc - 1;
}
if (choice == 'u' || choice == 'U'){
pr = pr - 1;
}
}
}
Now when you will run this program and go to diamond.It will increase your score and give diammond a new positon. You get diamond again but now diamond will disappear from grid. I dont understand why?
Can anyone guide me?
You are getting a random number, 0 to 5, for row and one for column, which works correctly, but you are couting the grid starting at 1 for row and 1, for column. The diamond is never printed if it is located in column 1 or row 1. Here is your corrected code.
Usually people tell us what the program is supposed to do.
Not <stdlib.h> but <cstdlib>.
What's up with the random, bizarre vertical spacing?
There's no way you need that many variables. You're not even using some of them.
Not i = i + 1; but ++i;, etc.
Don't use 1-based indexing. That's not the C++ way. Always use 0-based indexing unless there's a really good reason not to. (You're not even using the 1-base indexing correctly since rand() % 5 returns 0 to 4, which is why the diamond disappears.)
You allow the player to move right off the board. You need to check that.
about that right off the board i did this
if (choice == 'd' || choice == 'D'){
pr = pr + 1;
if (pr > 5){
pr = pr - 1;
cout << "Invalid movment";
cout << endl;
}
}
if (choice == 'r' || choice == 'R'){
pc = pc + 1;
if (pc > 5){
pc = pc - 1;
cout << "Invalid movment";
cout << endl;
}
}
if (choice == 'l' || choice == 'L'){
pc = pc - 1;
if (pc < 1){
pc = pc + 1;
cout << "Invalid movment";
cout << endl;
}
}
if (choice == 'u' || choice == 'U'){
pr = pr - 1;
if (pr < 1){
pr = pr + 1;
cout << "Invalid movement";
cout << endl;
}