Reputation: 11
Hi I'm a student and in my class we are programming a litte snake game, now the Problem ist that some times whene an Apple is eaten the game will freez, we figured out that it is propably caused by 2 Apples spawning at the same Position but we don't know how to avoid that. The Apples are generated in an arraylist so I think we need to locate the Elements inside the arraylist to say the Programm it is not allowed to spawn them there and needs to search for a new location until is has found one whithout an existing apple.
I searched on the Internet if there is a solution for my problem but i think it is a bit to specific or I follow the wrong path and some of you will find what I can't.
If you need any more details just write me a message. I'm glad to help you on helping me :D .
private void createApples(int max) {
int loop = 0;
int appleX;
int appleY;
Element apple;
boolean exists;
int index;
for (loop = 0; loop < max; loop++) {
exists = false;
do {
appleX =
new Random().nextInt(bounds.width / SNAKE_SIZE) *
SNAKE_SIZE + SNAKE_SIZE / 2;
appleY =
new Random().nextInt(bounds.height / SNAKE_SIZE) *
SNAKE_SIZE + SNAKE_SIZE / 2;
index = 0;
while (index < apples.size() && !exists) {
exists = apples.get(index).equal(appleX, appleY);
index++;
}
if (!exists)
exists = player.contains(appleX, appleY);
exists = player2.contains(appleX, appleY);
}
while (exists);
apple = new Element(appleX, appleY, SNAKE_SIZE, Color.white, bounds);
apples.add(apple);
}
}
Upvotes: 1
Views: 94
Reputation: 20909
Without going through your code in detail:
if (!exists)
exists = player.contains(appleX, appleY);
exists = player2.contains(appleX, appleY);
without curly braces, you are just applying the condition to the first line here. This is what your computer will see:
if (!exists){
exists = player.contains(appleX, appleY);
}
exists = player2.contains(appleX, appleY);
and this means, no matter what you have computed already for exists
- it will be overwritten by whatever is true for player2
.
But your exists should be true, whenever it is true for player1
OR player2
.
You can use the following instead:
exists |= player.contains(appleX, appleY);
exists |= player2.contains(appleX, appleY);
(Shorthand for)
if (!exists)
exists = player.contains(appleX, appleY);
if (!exists)
exists = player2.contains(appleX, appleY);
Can you add information, what apples
is (type), and how your equals / hashcode
method on Element
is implemented?
while (index < apples.size() && !exists) {
exists = apples.get(index).equal(appleX, appleY);
index++;
}
(I guess you implented your own, cause you also called it equal
instead of equals
)
Upvotes: 2