Editing Target.js - match to UML

This commit is contained in:
Yewon Kim 2025-05-18 23:43:32 +09:00
parent d27f84134e
commit f688f75ce6

View File

@ -1,23 +1,23 @@
import { MAX_TARGETS, TARGET_WIDTH } from './Constants'; import { MAX_TARGETS, TARGET_WIDTH } from './Constants';
import { Subject } from './Subject'; import { Subject } from './Subject';
import { Gun } from './Gun';
import teddy from '../data/teddy.png'; import teddy from '../data/teddy.png';
import duck from '../data/duck.png'; import duck from '../data/duck.png';
import squirrel from '../data/squirrel.png'; import squirrel from '../data/squirrel.png';
class Target extends Subject { class Target extends Subject {
constructor(x, y, img) { constructor(x, y, width) {
super(); super();
this.x = x; this.x = x;
this.y = y; this.y = y;
this.img = img; this.width = width;
this.height = width;
this.visible = true; this.visible = true;
this.img = null;
} }
draw() { draw() {
if (this.visible && this.img) { if (this.visible && this.img) {
image(this.img, this.x, this.y, TARGET_WIDTH, TARGET_WIDTH); image(this.img, this.x, this.y, this.width, this.height);
} }
} }
@ -25,34 +25,35 @@ class Target extends Subject {
return 0; // to be overridden return 0; // to be overridden
} }
hit() { isHit(x, y) {
if (this.visible) { return (
this.visible &&
x >= this.x &&
x <= this.x + this.width &&
y >= this.y &&
y <= this.y + this.height
);
}
shoot(x, y) {
if (this.isHit(x, y)) {
this.visible = false; this.visible = false;
this.notifySubscribers('target-hit', this.getPoints()); this.notifySubscribers('target-hit', this.getPoints());
} }
} }
contains(px, py) {
return this.visible &&
px >= this.x &&
px <= this.x + TARGET_WIDTH &&
py >= this.y &&
py <= this.y + TARGET_WIDTH;
}
update(source, ...others) { update(source, ...others) {
if (source === 'gun') { if (source === 'gun') {
const [x, y] = others; const [x, y] = others;
if (this.contains(x, y)) { this.shoot(x, y);
this.hit();
}
} }
} }
} }
class TeddyTarget extends Target { class TeddyTarget extends Target {
constructor(x, y) { constructor(x, y) {
super(x, y, loadImage(teddy)); super(x, y, TARGET_WIDTH);
this.img = loadImage(teddy);
} }
getPoints() { getPoints() {
@ -62,7 +63,8 @@ class TeddyTarget extends Target {
class DuckTarget extends Target { class DuckTarget extends Target {
constructor(x, y) { constructor(x, y) {
super(x, y, loadImage(duck)); super(x, y, TARGET_WIDTH);
this.img = loadImage(duck);
} }
getPoints() { getPoints() {
@ -72,7 +74,8 @@ class DuckTarget extends Target {
class SquirrelTarget extends Target { class SquirrelTarget extends Target {
constructor(x, y) { constructor(x, y) {
super(x, y, loadImage(squirrel)); super(x, y, TARGET_WIDTH);
this.img = loadImage(squirrel);
} }
getPoints() { getPoints() {