Files
oop/assignment6/Question3/Model.java
2022-05-25 13:14:19 +08:00

106 lines
2.2 KiB
Java

import java.awt.Graphics;
import java.util.ArrayList;
public class Model {
// instance variables
private int score;
private ArrayList<IShape> bubbles;
// constructor
public Model() {
score = 0;
bubbles = new ArrayList<IShape>();
}
// getters and setters
public int getScore() {
return score;
}
/**
* @param w
* @param h
*/
public void addBubble(int w, int h) {
bubbles.add(new Bubble((int) (w * Math.random()), (int) (h * Math.random())));
}
/**
* @param dx
* @param dy
*/
public void moveAll(int dx, int dy) {
for (int i = 0; i < bubbles.size(); i++) {
bubbles.get(i).setX(bubbles.get(i).getX() + dx);
bubbles.get(i).setY(bubbles.get(i).getY() + dy);
}
}
/**
* clear all bubbles
*
* @param w
* @param h
*/
public void clearInvisibles(int w, int h) {
for (int i = bubbles.size() - 1; i >= 0; i--) {
if (!bubbles.get(i).isVisible(w, h)) {
bubbles.remove(i);
score--;
}
}
}
/**
* delete bubbles that are hit by the mouse
*
* @param x
* @param y
*/
public void deleteBubblesAtPoint(int x, int y) {
for (int i = bubbles.size() - 1; i >= 0; i--) {
if (bubbles.get(i).isIn(x, y)) {
bubbles.remove(i);
score++;
}
}
}
/**
* draw all bubbles
*
* @param g
*/
public void drawAll(Graphics g) {
for (IShape bubble : bubbles) {
bubble.draw(g);
}
}
public static void testModel() {
Model m = new Model();
System.out.println(m.getScore() == 0);
System.out.println(m.bubbles.size() == 0);
m.addBubble(100, 100);
m.addBubble(100, 100);
System.out.println(m.getScore() == 0);
System.out.println(m.bubbles.size() == 2);
m.clearInvisibles(200, 200);
System.out.println(m.getScore() == 0);
System.out.println(m.bubbles.size() == 2);
m.clearInvisibles(0, 0);
System.out.println(m.getScore() == -2);
System.out.println(m.bubbles.size() == 0);
m.addBubble(100, 100);
m.addBubble(100, 100);
System.out.println(m.getScore() == -2);
System.out.println(m.bubbles.size() == 2);
m.moveAll(200, 200);
System.out.println(m.getScore() == -2);
System.out.println(m.bubbles.size() == 2);
m.clearInvisibles(200, 200);
System.out.println(m.getScore() == -4);
System.out.println(m.bubbles.size() == 0);
}
}