I am trying to implement an undo / redo functionality in my line drawing/moving/deleting program. I am currently saving each line as a list of points and storing all the lines in a list. After every drawing/moving/deleting operation I will add the new list of lines to my buffer and increment the bufferIterator(counter) to be the last element of the buffer at every mouseReleased action. When I press ESC I am trying to make the current lines variable the previous list of lines and repaint, but the repaint part is not working. Does anyone have any idea what I am doing wrong ?
The code is here:
public class Kimp {
public static void main(String[] args) {
JFrame frame = new JFrame("Kimp!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.add(new CanvasPanel());
frame.setVisible(true);
}
}
class CanvasPanel extends JPanel {
private List<List<List<Point>>> buffer = new LinkedList<List<List<Point>>>();
private List<List<Point>> lines = new LinkedList<List<Point>>();
private List<Point> points = new LinkedList<Point>();
public boolean ctrlPressed;
public int bufferIterator = 0;
public int pressedX = -999;
public int pressedY = -999;
public int differenceX;
public int differenceY;
public List<Point> pressedLine = new LinkedList<Point>();
public List<Point> movedLine = new LinkedList<Point>();
public Color lineColor = Color.BLUE;
public CanvasPanel() {
this.setFocusable(true);
this.requestFocusInWindow();
addKeyListener(keyAdapter);
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.WHITE);
g2.setStroke(new BasicStroke(3));
g2.fillRect(0, 0, getWidth(), getHeight());
for (List<Point> line : lines) {
drawLine(line, g2);
}
drawLine(points, g2);
}
private void drawLine(List<Point> points, Graphics2D g2) {
if (points.size() < 2) return;
if (ctrlPressed) {
int lineS = points.size();
int lineP = pressedLine.size();
//Set the color to RED, if the line is being moved.
if (lineS == lineP) {
boolean first = comparePoints(points.get(0), pressedLine.get(0));
boolean second = comparePoints(points.get(lineS - 1), pressedLine.get(lineP - 1));
boolean third = comparePoints(points.get(lineS / 2), pressedLine.get(lineP / 2));
if (first && second && third) {
lineColor = Color.RED;
}
} else {
lineColor = Color.BLUE;
}
} else {
lineColor = Color.BLUE;
}
Point p1 = points.get(0);
for (int i=1, n=points.size(); i<n; i++) {
Point p2 = points.get(i);
g2.setColor(lineColor);
g2.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
private KeyAdapter keyAdapter = new KeyAdapter() {
#Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == ke.VK_ESCAPE) {
System.out.println("ESC PRESSED");
if (bufferIterator != 0) {
System.out.println("UNDOING!");
//UNDO
lines = new LinkedList<List<Point>>();
int index = bufferIterator - 1;
if (index >= 0) {
lines = buffer.get(index);
}
repaint();
} else {
int reply = JOptionPane.showConfirmDialog(null, "Do you want to exit?",
"Exit", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
} else if(ke.getKeyCode() == ke.VK_CONTROL) {
ctrlPressed = true;
} else if (ke.getKeyCode() == ke.VK_SPACE) {
System.out.println("REDOING");
//REDO
}
}
#Override
public void keyReleased(KeyEvent ke) {
if(ke.getKeyCode() == ke.VK_CONTROL) {
ctrlPressed = false;
}
}
};
private MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (ctrlPressed) {
if (e.isMetaDown()) {
Point pointPressed = e.getPoint();
for (int j=0, m=lines.size(); j<m; j++) {
List<Point> line = lines.get(j);
for (int i=0, n=line.size(); i<n; i++) {
Point pt = line.get(i);
//This is, to allow a small margin of missing, but still only take 1 point.
if (pointPressed.x - pt.x <= 1 && pointPressed.y - pt.y <= 1) {
//Only the first point will be "the point clicked".
if (pressedX == -999 && pressedY == -999) {
pressedX = pt.x;
pressedY = pt.y;
pressedLine = line;
}
}
}
}
for (int x = 0, r = lines.size(); x < r; x++) {
int lenA = lines.get(x).size();
int lenB = pressedLine.size();
if (lenA == lenB) {
boolean first = comparePoints(lines.get(x).get(0), pressedLine.get(0));
boolean second = comparePoints(lines.get(x).get(lenA - 1), pressedLine.get(lenB - 1));
boolean third = comparePoints(lines.get(x).get(lenA / 2), pressedLine.get(lenB / 2));
if (first && second && third) {
lines.remove(x);
buffer.add(lines);
repaint();
break;
}
}
}
} else {
Point pointPressed = e.getPoint();
for (int j=0, m=lines.size(); j<m; j++) {
List<Point> line = lines.get(j);
for (int i=0, n=line.size(); i<n; i++) {
Point pt = line.get(i);
//This is, to allow a small margin of missing, but still only take 1 point.
if (pointPressed.x - pt.x <= 1 && pointPressed.y - pt.y <= 1) {
//Only the first point will be "the point clicked".
if (pressedX == -999 && pressedY == -999) {
pressedX = pt.x;
pressedY = pt.y;
pressedLine = line;
}
}
}
}
}
} else {
points.add(e.getPoint());
repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
Point pointDragged = e.getPoint();
if (ctrlPressed) {
differenceX = pointDragged.x - pressedX;
differenceY = pointDragged.y - pressedY;
//Create the moved line
for (Point p : pressedLine) {
movedLine.add(new Point(p.x + differenceX , p.y + differenceY));
}
for (int i=0, n=lines.size(); i<n; i++) {
int lineS = lines.get(i).size();
int lineP = pressedLine.size();
//Choose 3 points in order to not go through all of them
boolean first = comparePoints(lines.get(i).get(0), pressedLine.get(0));
boolean second = comparePoints(lines.get(i).get(lineS - 1), pressedLine.get(lineP - 1));
boolean third = comparePoints(lines.get(i).get(lineS / 2), pressedLine.get(lineP / 2));
if (first && second && third) {
lines.set(i, movedLine);
pressedX = pressedX + differenceX;
pressedY = pressedY + differenceY;
pressedLine = movedLine;
movedLine = new LinkedList<Point>();
repaint();
break;
}
}
} else {
points.add(pointDragged);
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (points.size() > 1) {
lines.add(points);
points = new LinkedList<Point>();
}
//Add the current canvas to buffer
buffer.add(lines);
System.out.println("Buffer size:");
System.out.println(buffer.size() );
System.out.println(buffer.get(buffer.size() - 1));
bufferIterator = buffer.size() - 1;
pressedX = -999;
pressedY = -999;
}
};
public boolean comparePoints (Point p1, Point p2) {
if (p1.x == p2.x && p1.y == p2.y) {
return true;
}
return false;
}
}
The issue is that you are not adding new objects to the buffer. Each time it is a reference to the same List. So when you get the list at the correct index out of the buffer you get the same list as any other index.
To fix this create a copy of the lines list to add to the buffer instead of adding lines each time.
Something like:
buffer.add(lines);
lines = new LinkedList<List<Point>(lines);
Related
I currently learned about processing.exe. I've made a snake game in processing and I want to modify it. What I want is every time the snake eats food, the food that is moving randomly also gets given random colors.
here's my code:
snake s;
int grid = 15;
PVector food;
int r;
int g;
int b;
int warna;
void setup() {
size(600, 600);
s = new snake();
food = new PVector();
r = (int)random(255);
g = (int)random(255);
b = (int)random(255);
frameRate(15);
newFood();
}
void draw() {
background(0);
s.showScore();
s.display();
if (s.gameOver()) {
background(0);
textAlign(LEFT);
textSize(25);
fill(255);
text("Game Over", 10, 10, width - 20, 50);
noLoop();
}
if (s.eat(food)) {
newFood();
}
s.move();
fill (r, g, b);
rect (food.x, food.y, grid, grid);
}
void newFood() {
food.x = floor(random(width));
food.y = floor(random(height));
food.x = floor(food.x/grid) * grid;
food.y = floor(food.y/grid) * grid;
if (food.x == floor(random(width)) && food.y == floor(random(height))){
fill (r = (int)random(255), g = (int)random(255), b = (int)random(255));
rect( food.x, food.y, grid, grid);
}
}
void keyPressed() {
if (keyCode == UP) {
s.arah(0, -1);
} else if (keyCode == DOWN) {
s.arah(0, 1);
} else if (keyCode == RIGHT) {
s.arah(1, 0);
} else if (keyCode == LEFT) {
s.arah(-1, 0);
}
}
And this are the snake :
class snake {
float x = 0;
float y = 0;
float xspd = 1;
float yspd = 0;
int panjang = 0;
ArrayList<PVector> body = new ArrayList<PVector>();
snake() {
}
boolean eat(PVector pos) {
float d = dist(x, y, pos.x, pos.y);
if (d < 1) {
panjang++;
return true;
} else {
return false;
}
}
void arah(float x, float y) {
xspd = x;
yspd = y;
}
boolean gameOver() {
for (int i = 0; i < body.size(); i++) {
PVector pos = body.get(i);
float d = dist(x, y, pos.x, pos.y);
if (d < 1) {
panjang = 0;
body.clear();
return true;
}
}
return false;
}
void move() {
if (panjang > 0) {
if (panjang == body.size() && !body.isEmpty()) {
body.remove(0);
}
body.add(new PVector(x, y));
}
x = x + xspd*grid;
y = y + yspd*grid;
x = (x + width) % width;
y = (y + height) % height;
}
void display() {
noStroke();
fill(255);
for (PVector bagi : body) {
rect(bagi.x, bagi.y, grid, grid);
}
rect(x, y, grid, grid);
}
void showScore() {
textAlign(LEFT);
textSize(25);
fill(255);
text("Score: " + body.size(), 10, 10, width - 20, 50);
}
}
I've tried to change the color with declare r, g, b and assign a random color to it. But the food color doesn't seem to change every time the snake eats the food. Any suggestions on what I should do?
You're doing good so far. The only part you missed is that you want to change the food's color when you create some new food. So... you just have to take this part of the setup() method:
r = (int)random(255);
g = (int)random(255);
b = (int)random(255);
and move it in the newFood() method.
Hope this helps. Have fun!
As a beginner in Java, I'm working on a project of Space Invaders. Looking to add more levels.
private void LevelInit() {
aliens = new ArrayList<>();
int currentLevel = 1;
if (currentLevel == 1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
//System.out.println(currentLevel);
}
}
}
else if (currentLevel == 2) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
// System.out.println(currentLevel);
}
}
}
else if (currentLevel == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
//System.out.println(currentLevel);
}
}
}
player = new Player();
bullet = new Bullet();
}
This function is the logic behind the code that initializes the game and gets called by the constructor. The simple way of adding levels is adding more Aliens.
This is how it looks after being updated from yesterday, levels are being added but the arraylists are being stuck together. Like the 12 - 16 - 24 aliens are together printed, some spaceships take 1 hit some 2 and some 3 and when they are all destroyed system give message of You passed level 1 and 2 and 3 together which is confusing me why are they bound together like that and not being passed.
And I can't figure it out. Also,
private void update() {
if (deaths == 12) {
inGame = false;
timer.stop();
message = "Next Level!";
}
// player
player.act();
// shot
if (bullet.isVisible()) {
int shotX = bullet.getX();
int shotY = bullet.getY();
for (Alien alien : aliens) {
int alienX = alien.getX();
int alienY = alien.getY();
if (alien.isVisible() && bullet.isVisible()) {
if (shotX >= (alienX)
&& shotX <= (alienX + Constants.ALIEN_WIDTH)
&& shotY >= (alienY)
&& shotY <= (alienY + Constants.ALIEN_HEIGHT)) {
var ii = new ImageIcon(explImg);
alien.setImage(ii.getImage());
alien.setDying(true);
deaths++;
bullet.die();
}
}
}
int y = bullet.getY();
y -= 4;
if (y < 0) {
bullet.die();
} else {
bullet.setY(y);
}
}
// aliens
for (Alien alien : aliens) {
int x = alien.getX();
if (x >= Constants.BOARD_WIDTH - Constants.BORDER_RIGHT && direction != -1) {
direction = -1;
for(Alien a2 : aliens) {
a2.setY(a2.getY() + Constants.GO_DOWN);
}
}
if (x <= Constants.BORDER_LEFT && direction != 1) {
direction = 1;
for(Alien a : aliens) {
a.setY(a.getY() + Constants.GO_DOWN);
}
}
}
for(Alien alien : aliens) {
if (alien.isVisible()) {
int y = alien.getY();
if (y > Constants.GROUND - Constants.ALIEN_HEIGHT) {
inGame = false;
message = "Invasion!";
}
alien.act(direction);
}
}
// bombs
var generator = new Random();
for (Alien alien : aliens) {
int shot = generator.nextInt(15);
Alien.Bomb bomb = alien.getBomb();
if (shot == Constants.CHANCE && alien.isVisible() && bomb.isDestroyed()) {
bomb.setDestroyed(false);
bomb.setX(alien.getX());
bomb.setY(alien.getY());
}
int bombX = bomb.getX();
int bombY = bomb.getY();
int playerX = player.getX();
int playerY = player.getY();
if (player.isVisible() && !bomb.isDestroyed()) {
if (bombX >= (playerX)
&& bombX <= (playerX + Constants.PLAYER_WIDTH)
&& bombY >= (playerY)
&& bombY <= (playerY + Constants.PLAYER_HEIGHT)) {
var ii = new ImageIcon(explImg);
player.setImage(ii.getImage());
player.setDying(true);
bomb.setDestroyed(true);
}
}
if (!bomb.isDestroyed()) {
bomb.setY(bomb.getY() + 1);
if (bomb.getY() >= Constants.GROUND - Constants.BOMB_HEIGHT) {
bomb.setDestroyed(true);
}
}
}
}
This function is to update the game whenever anything happens. The code is made from a bunch of YouTube videos and GitHubs, so excuse the copying if you see any.
I need to create new levels by simply adding more aliens, tried using a for loop but that resulted in either the aliens move faster or the bullet doesn't destroy an alien, it just hits.
Board class:
public class Board extends JPanel {
private Dimension d;
private List<Alien> aliens;
private Player player;
private Bullet bullet;
private int level;
private int direction = -1;
private int deaths = 0;
private boolean inGame = true;
private String explImg = "src/images/explosion.png";
private String message = "Game Over";
private Timer timer;
public Board() {
initBoard();
gameInit();
LevelInit();
}
private void initBoard() {
addKeyListener(new TAdapter());
setFocusable(true);
d = new Dimension(Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
setBackground(Color.black);
timer = new Timer(Constants.DELAY, new GameCycle());
timer.start();
gameInit();
}
private void gameInit() {
aliens = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j,
Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
player = new Player();
bullet = new Bullet();
}
private void LevelInit() {
inGame = true;
timer.start();
int level = 1;
if (aliens.isEmpty()) {
level++;
int AlienCount;if(level == 2) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
} else if (level == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
}
}
player = new Player();
bullet = new Bullet();
}
private void drawAliens(Graphics g) {
for (Alien alien : aliens) {
if (alien.isVisible()) {
g.drawImage(alien.getImage(), alien.getX(), alien.getY(), this);
}
if (alien.isDying()) {
alien.die();
}
}
}
private void drawPlayer(Graphics g) {
if (player.isVisible()) {
g.drawImage(player.getImage(), player.getX(), player.getY(), this);
}
if (player.isDying()) {
player.die();
inGame = false;
}
}
private void drawShot(Graphics g) {
if (bullet.isVisible()) {
g.drawImage(bullet.getImage(), bullet.getX(), bullet.getY(), this);
}
}
private void drawBombing(Graphics g) {
for (Alien a : aliens) {
Alien.Bomb b = a.getBomb();
if (!b.isDestroyed()) {
g.drawImage(b.getImage(), b.getX(), b.getY(), this);
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, d.width, d.height);
g.setColor(Color.green);
if (inGame) {
g.drawLine(0, Constants.GROUND,
Constants.BOARD_WIDTH, Constants.GROUND);
drawAliens(g);
drawPlayer(g);
drawShot(g);
drawBombing(g);
} else {
if (timer.isRunning()) {
timer.stop();
}
gameOver(g);
}
Toolkit.getDefaultToolkit().sync();
}
private void gameOver(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
g.setColor(new Color(0, 32, 48));
g.fillRect(50, Constants.BOARD_WIDTH / 2 - 30, Constants.BOARD_WIDTH - 100, 50);
g.setColor(Color.white);
g.drawRect(50, Constants.BOARD_WIDTH / 2 - 30, Constants.BOARD_WIDTH - 100, 50);
var small = new Font("Helvetica", Font.BOLD, 14);
var fontMetrics = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(message, (Constants.BOARD_WIDTH - fontMetrics.stringWidth(message)) / 2,
Constants.BOARD_WIDTH / 2);
}
private void update() {
if (deaths == aliens.size()) {
inGame = false;
timer.stop();
message = "Next Level!";
}
// player
player.act();
// shot
if (bullet.isVisible()) {
int shotX = bullet.getX();
int shotY = bullet.getY();
for (Alien alien : aliens) {
int alienX = alien.getX();
int alienY = alien.getY();
if (alien.isVisible() && bullet.isVisible()) {
if (shotX >= (alienX)
&& shotX <= (alienX + Constants.ALIEN_WIDTH)
&& shotY >= (alienY)
&& shotY <= (alienY + Constants.ALIEN_HEIGHT)) {
var ii = new ImageIcon(explImg);
alien.setImage(ii.getImage());
alien.setDying(true);
deaths++;
bullet.die();
}
}
}
int y = bullet.getY();
y -= 4;
if (y < 0) {
bullet.die();
} else {
bullet.setY(y);
}
}
// aliens
for (Alien alien : aliens) {
int x = alien.getX();
if (x >= Constants.BOARD_WIDTH - Constants.BORDER_RIGHT && direction != -1) {
direction = -1;
Iterator<Alien> i1 = aliens.iterator();
while (i1.hasNext()) {
Alien a2 = i1.next();
a2.setY(a2.getY() + Constants.GO_DOWN);
}
}
if (x <= Constants.BORDER_LEFT && direction != 1) {
direction = 1;
Iterator<Alien> i2 = aliens.iterator();
while (i2.hasNext()) {
Alien a = i2.next();
a.setY(a.getY() + Constants.GO_DOWN);
}
}
}
Iterator<Alien> it = aliens.iterator();
while (it.hasNext()) {
Alien alien = it.next();
if (alien.isVisible()) {
int y = alien.getY();
if (y > Constants.GROUND - Constants.ALIEN_HEIGHT) {
inGame = false;
message = "Invasion!";
}
alien.act(direction);
}
}
// bombs
var generator = new Random();
for (Alien alien : aliens) {
int shot = generator.nextInt(15);
Alien.Bomb bomb = alien.getBomb();
if (shot == Constants.CHANCE && alien.isVisible() && bomb.isDestroyed()) {
bomb.setDestroyed(false);
bomb.setX(alien.getX());
bomb.setY(alien.getY());
}
int bombX = bomb.getX();
int bombY = bomb.getY();
int playerX = player.getX();
int playerY = player.getY();
if (player.isVisible() && !bomb.isDestroyed()) {
if (bombX >= (playerX)
&& bombX <= (playerX + Constants.PLAYER_WIDTH)
&& bombY >= (playerY)
&& bombY <= (playerY + Constants.PLAYER_HEIGHT)) {
var ii = new ImageIcon(explImg);
player.setImage(ii.getImage());
player.setDying(true);
bomb.setDestroyed(true);
}
}
if (!bomb.isDestroyed()) {
bomb.setY(bomb.getY() + 1);
if (bomb.getY() >= Constants.GROUND - Constants.BOMB_HEIGHT) {
bomb.setDestroyed(true);
}
}
}
}
private void doGameCycle() {
update();
repaint();
}
private class GameCycle implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
doGameCycle();
}
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
int x = player.getX();
int y = player.getY();
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
if (inGame) {
if (!bullet.isVisible()) {
bullet = new Bullet(x, y);
}
}
}
}
}
}
As #JoachimSauer mentioned, your code needs refactoring. Here is one possible solution to your problem.
Additions
You will need two extra variables and one extra method.
Variables
1: int currentLevel - keeps track of the current level
2: boolean isLevelOver - keeps track if the current level is still active or not
Method
private void levelInit(int currentlevel)
{
aliens = new ArrayList<>();
int alienCount = //calculate alien count depending upon the current level
//Add aliens to aliens ArrayList
player = new Player();
bullet = new Bullet();
}
You have to provide implementation of how alienCount will be calculated depending upon currentLevel. The nested loop you used earlier to add aliens to aliens will also change. You have to make the loop dependent upon currentLevel.
Changes
Few of your methods will require some change.
public Board()
{
initBoard();
}
private void initBoard()
{
addKeyListener(new TAdapter());
setFocusable(true);
d = new Dimension(Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
setBackground(Color.black);
levelInit(currentLevel);
timer = new Timer(Constants.DELAY, new GameCycle());
timer.start();
}
private void update()
{
if (deaths == aliens.size())
{
isLevelOver = true;
currentLevel++;
message = "Next Level!";
return;
}
...
}
private void doGameCycle()
{
if (isLevelOver)
{
levelInit(currentLevel);
isLevelOver = false;
}
update();
repaint();
}
Notes
This is one of the possible ways to achieve what you want. There
might be other ways, probably better, but this is what I came up
with.
I tried to find as many additions and updation required in your code. However, I do not know its structure, you do. So there might be more additions or changes required.
I noticed you are were calling gameInit() in initBoard() and then again in Board() constructor. I think that might be unnecessary, please look into it.
You made one call to timer.stop() after setting isGame = false. This again might be unnecessary since you are already doing so inside doDrawing(...). Please also check that.
You should probably set a limit to either the levelCount() or max alien that can be on the screen since if you just keep on adding more aliens in each new level, they might fill up the entire screen.
I have provided many hints which should help you in your problem. If you still face any more problems or someone finds anything wrong with the answer, please comment.
I am trying to have each brick in my game have a random color, however when I try to do this the whole set of bricks become the same color. How do I make each individual brick a random color? Any help is appreciated.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends JoeApplet implements KeyListener
{
String status;
int ballx = 294; // ball spawn x coordinate
int bally = 640; // ball spawn y coordinate
int batx = 294;
int baty = 654;
int brickx = 32;
int bricky = 50;
double movex = -16; // x speed of ball
double movey = -16; //y speed of ball
int count = 0;
int currentLevel=0;
int score=0; //starts score at 0
int lives=3; //lives start at 3
static boolean right = false;
static boolean left = false;
boolean ballFallDown = false;
boolean bricksOver = false;
Rectangle Ball = new Rectangle(ballx, bally, 14, 14); //creates ball
Rectangle Bat = new Rectangle(batx, baty, 100, 12); //creates bat(paddle)
Rectangle[] Brick = new Rectangle[49]; //creates desired number of bricks
public void paint(Graphics art)
{
switch(currentLevel)
{
case 0:
menuScreen(art);
break;
case 1:
game(art);
break;
}
}
public void menuScreen(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,66);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,66);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
art.setColor(Color.yellow);
Font menu = new Font("Arial", Font.BOLD, 20);
art.setFont(menu);
art.drawString("Brick Breaker", 100,400);
art.drawString("Press P to Play", 100,425);
art.drawString("Press Q to Quit game", 100,450);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(100,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
art.setColor(Color.YELLOW);
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 294, 349);
ballFallDown = false;
bricksOver = false;
}
}
public void game(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,225);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,139);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(200,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 100,425);
ballFallDown = false;
bricksOver = false;
}
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
if (Brick[i].intersects(Ball))
{
score=score+10;
Brick[i] = null;
movey = -movey;
count++;
}
}
}
if (count == Brick.length)
{
bricksOver = true;
movex=0;
movey=0;
art.setColor(Color.green);
status = "YOU BEAT THE LEVEL!!";
art.drawString("Press E to Exit", 100,450);
art.drawString("Press N for Next Level", 100,475);
repaint();
}
repaint();
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.setColor(Color.white);
art.drawString("Score:"+score, 600, 684);
Ball.x += movex;
Ball.y += movey;
if (left == true)
{
Bat.x -= 18;
right = false;
}
if (right == true)
{
Bat.x += 18;
left = false;
}
if (Bat.x <= 4)
{
Bat.x = 4;
}
else if (Bat.x >= 586)
{
Bat.x = 596;
}
if (Ball.intersects(Bat))
{
movey = -movey-.1;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 698)
{
movex = -movex;
}
if (Ball.y <= 0)
{
movey = -movey;
}
Font f1 = new Font("Arial", Font.BOLD, 20);
art.setFont(f1);
art.setColor(Color.white);
art.drawString("Lives:"+ lives, 5, 684);
if (Ball.y >= 698 && (bricksOver==false) && lives>0)
{
ballFallDown = true;
art.setColor(Color.red);
status = "";
art.drawString("", 100,450);
lives=lives-1;
ballx = 294;
bally = 640;
Ball = new Rectangle(ballx, bally, 14, 14);
movex = -16;
movey = -16;
repaint();
}
if(lives==0 && Ball.y >= 698)
{
art.setColor(Color.red);
art.drawString("You lost!!", 100,425);
art.drawString("Press E to Exit", 100,450);
}
}
public void init()
{
addKeyListener(this);
for (int i = 0; i < Brick.length; i++) //creates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12) //1st row of bricks
{
brickx = 32;
bricky = 84;
}
if (i == 23) //2nd row of bricks
{
brickx = 82;
bricky = 118;
}
if (i == 32) //3rd row of bricks
{
brickx = 132;
bricky = 152;
}
if (i == 39) //4th row of bricks
{
brickx = 182;
bricky = 186;
}
if (i == 44) //5th row of bricks
{
brickx = 232;
bricky = 220;
}
if (i == 47) //6th row of bricks
{
brickx = 282;
bricky = 254;
}
if (i == 48) //7th row of bricks
{
brickx = 144;
bricky = 132;
}
brickx += 50; //spacing between each brick
}
}
public void restart()
{
ballx = 294;
bally = 640;
batx = 294;
baty = 654;
brickx = 32;
bricky = 50;
Ball = new Rectangle(ballx, bally, 14, 14);
Bat = new Rectangle(batx, baty, 100, 12);
movex = -16;
movey = -16;
ballFallDown = false;
bricksOver = false;
count = 0;
status = null;
for (int i = 0; i < Brick.length; i++) //recreates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12)
{
brickx = 32;
bricky = 84;
}
if (i == 23)
{
brickx = 82;
bricky = 118;
}
if (i == 32)
{
brickx = 132;
bricky = 152;
}
if (i == 39)
{
brickx = 182;
bricky = 186;
}
if (i == 44)
{
brickx = 232;
bricky = 220;
}
if (i == 47)
{
brickx = 282;
bricky = 254;
}
if (i == 48)
{
brickx = 144;
bricky = 132;
}
brickx += 50;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) //allows each key to do desired action
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = true;
}
if (keyCode == e.VK_P && currentLevel == 0)
{
currentLevel = 1;
}
else if (keyCode == e.VK_E && currentLevel == 1)
{
currentLevel = 0;
score=0;
lives=3;
restart();
}
else if(keyCode == e.VK_Q)
{
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = false;
}
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
Game prog = new Game();
prog.init();
}
}
I'd throw that code out and start over as you've got both program logic and repaints within your painting methods, neither of which will help you, and your code appears to be one big huge "God" class, all of which will leave you with code that's a horrific nightmare to debug. Recommendations:
Create at least two separate JPanels to display your program with, a GamePanel and a MenuPanel.
Swap these JPanels using a CardLayout.
Do all graphics within a JPanel's paintComponent method and not within a JFrame's or JApplet's paint method.
Don't forget to call the super's painting method, the same method as your override within your override. This is to clean up any dirty pixels.
Separate your program logic from your GUI
This means that you should have a logical non-GUI representation of a single Brick class as well as a collection of these non-GUI bricks.
You can always give your Brick class a Color field, one that the view or gui uses to paint it with.
Create a game-loop, one that you can control, one that doesn't involve calling repaint() within a painting method, since this leads to a completely uncontrollable loop.
Favor use of Key Bindings over KeyListeners.
Try to avoid use of "magic" numbers, such as hard-coding your brick width and spacing in the class itself. Better to use constants as this too makes debugging and enhancing much easier.
For example, some code that's just to demonstrate showing random colors:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class BrickBreak {
private static void createAndShowGui() {
GamePanel gamePanel = new GamePanel();
JFrame frame = new JFrame("Brick Break");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(gamePanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
// JPanel that draws the game
class GamePanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final Color BACK_GRND = Color.BLACK;
private int prefW;
private int prefH;
private Bricks bricks = new Bricks();
public GamePanel() {
// wide enough to hold the complete top-row of Bricks
// using constants, so GUI automatically resizes if any sizes change
prefW = (Brick.WIDTH + Bricks.X_SPACING) * Bricks.ROW_COUNTS[0] + Bricks.X_SPACING;
prefH = prefW;
setBackground(BACK_GRND);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Brick brick : bricks) {
brick.draw(g2);
}
}
}
// non-GUI class that represents a logical Brick
class Brick {
public static final int WIDTH = 40;
public static final int HEIGHT = 20;
private int x;
private int y;
private Color color;
private Rectangle boundingRectangle;
public Brick(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
boundingRectangle = new Rectangle(x, y, WIDTH, HEIGHT);
}
// yeah, I'm mixing some view with model here.
public void draw(Graphics2D g2) {
g2.setColor(color);
g2.fill3DRect(x, y, WIDTH, HEIGHT, true);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Color getColor() {
return color;
}
// use this to test for collisions
public boolean contains(Point p) {
return boundingRectangle.contains(p);
}
#Override
public String toString() {
return "Brick [x=" + x + ", y=" + y + ", color=" + color + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Brick other = (Brick) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
// logical class that holds all Bricks
// Have class implement Iterable<Brick> so we can easily iterate through its containing
// Brick objects in a for-each loop
class Bricks implements Iterable<Brick> {
public static final int X_SPACING = 10;
public static final int Y_SPACING = X_SPACING;
public static final int[] ROW_COUNTS = {13, 11, 9, 7, 5, 3, 1};
private static final float MIN_SAT = 0.8f;
private List<Brick> brickList;
private Random random = new Random();
public Bricks() {
init(); // safe to call since it's final
}
public final void init() {
// recreate the brickList ArrayList
brickList = new ArrayList<>();
int y = Y_SPACING;
// for each row of bricks
for (int row = 0; row < ROW_COUNTS.length; row++) {
int x = X_SPACING + ((ROW_COUNTS[0] - ROW_COUNTS[row]) / 2) * (X_SPACING + Brick.WIDTH);
// for each column
for (int j = 0; j < ROW_COUNTS[row]; j++) {
// create a random color
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
Color color = Color.getHSBColor(hue, saturation, brightness);
Brick brick = new Brick(x, y, color); // create a new Brick with this Color
brickList.add(brick);
x += X_SPACING + Brick.WIDTH;
}
y += Y_SPACING + Brick.HEIGHT;
}
}
// returns null if no collision
public Brick collision(Point p) {
for (Brick brick : brickList) {
if (brick.contains(p)) {
return brick;
}
}
return null;
}
#Override
public Iterator<Brick> iterator() {
return brickList.iterator();
}
public boolean remove(Brick brick) {
// because Brick implements equals and hashCode, we can do this
return brickList.remove(brick);
}
}
Note that I like using Color's static getHSBColor(float h, float s, float b) method for creating random Colors as this helps me to avoid creating dull Colors, since I can guarantee that the saturation and brightness are above minimum values. All three parameters must be float values between 0f and 1.0f
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
Color color = Color.getHSBColor(hue, saturation, brightness);
Your code has quite a lot of issues, which #HovercaftFullOfEels answer already points out.
As for why your code doesn't work:
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(100,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
This is the part that renders the bricks. You never create a random-number, but use the same Color for each brick (new Color(100, 0, 0);). Instead introduce a new variable into Brick that specifies the color of each brick and is initialized once with a random color.
The Brick-class would afterwards look like this:
public class Brick{
public int x;
public int y;
...
public Color color;
...
}
The ... are just placeholders for other code that may be content of the class. Regarding public access of Class-variables: Encapsulation is a fundamental concept of OOP and should be used (on encapsulation). E.g. instead of giving direct access to Brick.x consider introducing a method Brick#getX().
The program was running fine before I put the Rectangle2D objects in an ArrayList, except that whenever I changed directions, the snake would just rotate rather than bend. Now the snake does not even show up, and my console gives me the error, as provided by Mad Programmer:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException:
Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
I know the issue is related to the ArrayLists, but how do I fix it?
Here is my class:
public class Display extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(1, this);
double xCoord = 50;
double yCoord = 50;
double xvel = 0;
double yvel = .01;
double ranx, xtemp;
double rany, ytemp;
int eaten = 0;
ArrayList<Rectangle2D> rects = new ArrayList<Rectangle2D>();
ArrayList<Double> xloc = new ArrayList<Double>();
ArrayList<Double> yloc = new ArrayList<Double>();
public Display(int xsize, int ysize) {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
xtemp = xsize;
ranx = (xtemp - 15) * Math.random();
ytemp = ysize;
rany = (ytemp - 15) * Math.random();
formSnake();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Adds snake
g2.setColor(Color.YELLOW);
for (int i = 0; i < rects.size(); i++) {
g2.fill(rects.get(i));
}
// Adds fruit at random location
g2.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(ranx, rany, 15, 15));
setBackground(Color.BLACK);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
// Replaces each rectangle location with one before it
for (int i = rects.size() - 1; i > 0; i--) {
xloc.set(i, xloc.get(i - 1));
yloc.set(i, yloc.get(i - 1));
}
// Sets new head location
xloc.set(0, xloc.get(0) + xvel);
yloc.set(0, yloc.get(0) + yvel);
getEaten();
}
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < rects.size(); i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
// Adds 1 2DRectangle to the front of the snake every time it eats
public void extend() {
// Vertical
if (xvel == 0) {
if (yvel <= 0) { // Up
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) - 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Down
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) + 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
// Horizontal
else if (yvel == 0) {
if (xvel <= 0) { // Left
xloc.add(xloc.get(xloc.size() - 1) - 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Right
xloc.add(xloc.get(xloc.size() - 1) + 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
}
public void getEaten() {
if (Math.abs(xCoord - ranx) < 15 && Math.abs(yCoord - rany) < 15) {
rany = ytemp * Math.random();
ranx = xtemp * Math.random();
eaten++;
extend();
}
}
//Directions
public void up() {
yvel = -0.5;
xvel = 0;
}
public void down() {
yvel = 0.5;
xvel = 0;
}
public void left() {
xvel = -0.5;
yvel = 0;
}
public void right() {
xvel = 0.5;
yvel = 0;
}
//Just for testing purposes
public void stop() {
xvel = 0;
yvel = 0;
}
//Direction implementation
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP || code == KeyEvent.VK_NUMPAD8) {
up();
}
if (code == KeyEvent.VK_DOWN || code == KeyEvent.VK_NUMPAD2) {
down();
}
if (code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_NUMPAD6) {
right();
}
if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_NUMPAD4) {
left();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
You seem to be getting a
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
At xloc.set(0, xloc.get(0) + xvel);, because there are no elements the xloc List
Change your formSnake method to do exactly what it says...// Adds initial 3 2DRectangles to snake at start of game instead of using rects.size(), which will be 0 when it's called...
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < 3; i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
I am making a fairly simple game in java and I keep getting this IndexOutofBoundsException from my arraylist. I have 1 that creates an arraylist of "bullets", and another that stores "missles". The program runs and I can fire bullets for about 5 seconds and then it freezes giving me this error. I'm not sure what is happening.
This is part of my Canvas class that creates the array lists.
ArrayList ms = craft.getMissles();
ArrayList bs = craft.getBullets();
for (int i = 0; i < ms.size(); i++ ) {
Missle m = (Missle) ms.get(i);
g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);
}
for (int b = 0; b < bs.size(); b++ ) {
Bullet a = (Bullet) bs.get(b);
g2d.drawImage(a.getImage(), a.getX(), a.getY(), this);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
ArrayList ms = craft.getMissles();
ArrayList bs = craft.getBullets();
for (int i = 0; i < ms.size(); i++) {
Missle m = (Missle) ms.get(i);
if (m.isVisible())
m.move();
else ms.remove(i);
}
for (int b = 0; b < bs.size(); b++) {
Bullet a = (Bullet) bs.get(b);
if (a.isVisible())
a.move();
else ms.remove(b);
}
craft.move();
repaint();
}
And here are parts of my Craft class that has the actions for the missiles. I declare them above and the code worked fine when I only had the missile parts. The error came when I added a second arraylist.
public Craft() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
image = ii.getImage();
missles = new ArrayList();
bullets = new ArrayList();
x = 1000;
y = 60;
}
private ArrayList missles;
private ArrayList bullets;
private final int CRAFT_SIZE = 85;
private final int CRAFT_SIZE2 = 20;
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public ArrayList getMissles() {
return missles;
}
public ArrayList getBullets() {
return bullets;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -2;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -2;
}
if (key == KeyEvent.VK_DOWN) {
dy = 3;
}
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_V) {
fire2();
}
}
public void fire() {
missles.add(new Missle(x + CRAFT_SIZE, y + CRAFT_SIZE/2));
}
public void fire2() {
bullets.add(new Bullet(x + CRAFT_SIZE2, y + CRAFT_SIZE/2));
}
I spotted one bug at least:
else ms.remove(b);
should be
else bs.remove(b);