Hey,
I have been working on a battle ship game for a while, and I'm trying to add in a player vs. computer option. I have two functions that are used to generate a ships coordinate. The first one just generates a random coordinate (the first coord for the ship).
Also In case you didn't know some ships are bigger then others.
Then the second function second function gets a random direction that the ship should face, it also checks if the ship (depending on the length) has enough room to face the randomly chosen direction. If it can't fit, then it picks a different direction. Ok, but the part I'm having trouble with is checking if there is room to place a ship horizontally (left or right).
This is my board:
[11] [12] [13] [14] [15] [16] [17] [18]
[21] [22] [23] [24] [25] [26] [27] [28]
[31] [32] [33] [34] [35] [36] [37] [38]
[41] [42] [43] [44] [45] [46] [47] [48]
[51] [52] [53] [54] [55] [56] [57] [58]
[61] [62] [63] [64] [65] [66] [67] [68]
[71] [72] [73] [74] [75] [76] [77] [78]
[81] [82] [83] [84] [85] [86] [87] [88]
Ok, it is easy to check if there is room to place a ship up and down. Say the first random coord of a 3 space ship is 26. Then to check if it can face up (which it cant) you could use this:
Code:
if (cord_one - 20 < 11)
This would evaluate to 6 < 11, so you know the ship can't go there, but it gets much more complicated when I try to check left and right. I have been trying to use modules, but It's getting too confusing for me.
These are the my two statements for left and right:
(for a ship with three coords)
Code:
if (cord_one + 2 % 10 > 8 || cord_one +2 % 10 < 3)
and
if(cord_one - 2 % 10 < 1 || cord_one - 2 % 10 > 6 )
Here is the entire function:
Code:
int generate_cord2 (int cord_one, int spaces) {
wait(5);
int imp = spaces - 1;
int x, y, i, f;
int go = 1;
i = r_rand(4);
while (go == 1) {
if (i == 1) {
if (cord_one - imp * 10 < 11) {
i == 2;
}
else {
f = cord_one - 10;
return 1;
}
}
else if (i == 2) {
if (cord_one + imp * 10 > 88) {
i == 3;
}
else {
f = cord_one + 10;
return 2;
}
}
else if (i == 3){
if (cord_one + imp % 10 > 8 || cord_one + imp % 10 < spaces) {
i == 4;
}
else {
return 3;
}
}
else if (i == 4) {
if(cord_one - imp % 10 < 1 || cord_one - imp % 10 > 8 - imp) {
i == 1;
}
else {
return 4;
}
}
}
}
Thanks in advance!
David