ArrayLists in Pong
in
Programming Questions
•
1 year ago
I have an arrayList of balls in a game similar to pong. I added a feature where about 10 balls are added in the middle of the screen so that there would be an explosion type thing... Then, I gave every ball an ID, and the only ball that matters (i.e. can score) is the ball with an ID of 1.
This code is for the explosion.. What it does is create 10 new balls, but starts at the highest ID so that there are no repeat ID's.
void moreballs() {
int maxid=-10;
for (int i=balls.size()-1;i>0;i--) {//loop through balls and get the highest ID
Ball b1=(Ball) balls.get(i);
if (b1.id>maxid) {
maxid=b1.id;
}
}
maxid+=1;
int limi=maxid+10;
for (int k=maxid;k<limi;k+=1) {//add to the balls array, but start with the highest id in the array so that there is no overlapping
balls.add(new Ball(w/2, h/2, k));//x,y,ID
}
}
So this does exactly what I need to do, but it means that the arrayList sometimes has gaps in the ID's. For example if you print the ID's of the list sometimes you get something like:
------------------------------
1
2
9
10
11
12
13
14
15
16
17
18
19
20
21
------------------------------
This leads to a problem in the
pointscored() section.
The point scored section does 2 things. If the ID is 1, it resets the ball and gives a point to whoever scored. If the ID isn't 1, then it should remove the ball. The problem is I can't get the second part to work. Everything I've been able to do has either created an out of memory error, an out of array index error, or just doesn't remove the balls.
- void pointscored(int id) {
- if (id==1) {
- userscore+=1;
- }
- int j=0;
- int limi=balls.size()-1;
- for (int k=balls.size()-1;j<=limi;k-=1) {
- if (k==id) {
- j+=1;
- if (id!=1) {
- balls.remove(id);
- }
- }
- }
- }
When I run this code with the rest of the game I get mixed results. If just one ball "scores", then it freezes for about 5 seconds and continues. If multiple balls score, then the game freezes and gets an Index Out Of Bounds Exception.
1