如何从另一个 class 调用在另一个 class 中创建的 class 实例的方法?
How do you call the methods of a class instance that was created in another class, from another class?
我正尝试在 Java Swing GUI 中为我的突破游戏创建一些动画游戏文本。
预期行为:每次砖块被击中时,它的点都会猛击到屏幕上,暂停 0.25 秒,然后逐渐消失。
我所做的: 在名为 AlertText
的 class 中的方法中使用了计时器。当砖块在 class GameLogic
中被击中时,一个新的 AlertText
被创建并且它的计时器开始 运行。现在在游戏中 Class 我有油漆 class.
问题: 那么我如何调用在 GameLogic
中创建的 AlertText
的特定实例来使用 setter 和getter 在 Game
class 中设置我的 g.drawString
画图的方法。我觉得这应该是一种常见的技术?有名字吗?
我让它与一种积木样式的全局变量一起工作,所以我知道动画正在运行,但我需要 100 多个全局变量来完成每种积木。
游戏Class
public class Game extends JPanel
{
public static final int HEIGHT = 720;
public static final int WIDTH = 600;
public Color color;
private GameLogic gl = new GameLogic();
private KeyboardController controller;
public Paddle player = new Paddle(110, HEIGHT-30, 100, 10, 10, color.black, controller);
public Ball gameBall = new Ball(300, 300, 15, color.black);
private boolean PaddleUpdateComplete = false;
private List<AlertText> activeAlerts = new ArrayList<AlertText>();
Game game = new Game();
public void spawnNewAlert(Brick b){
AlertText alert = new AlertText();
alert.setxPos(b.getXPosition());
alert.setyPos(b.getYPosition());
alert.setText(b.getPoints()+"");
alert.setColor(b.getColor());
activeAlerts.add(alert);
alert.fireText();
}
@Override
public void paint(Graphics g)
{
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, (int)AlertText.staticAlertSize));
g.setColor(new Color(AlertText.staticRed, AlertText.staticGreen, AlertText.staticBlue));
g.drawString(AlertText.staticAlertOne, AlertText.staticAlertXPos, AlertText.staticAlertYPos);
player.draw((Graphics2D)g);
gameBall.draw((Graphics2D)g);
gl.drawBricks(g);
// Draw GameObjects and anything else here
g.setFont(scoreFont);
g.drawString("Score: " + player.getScore(), 10, 25);
g.drawString("LIVES: " + player.getLives(), 150, 25);
if(gl.gameOver(player) &&
gameBall.getYPosition() >= HEIGHT){
g.setColor(Color.black);
g.setFont(endFont);
g.drawString("Game Over! Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
}
if(gl.empty()){
g.setColor(Color.black);
g.setFont(endFont);
g.drawString("You won! Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
timer.stop();
}
if(PowerUps.isMegaPaddle){
g.setColor(Color.orange);
g.setFont(TimeFont);
g.drawString(PowerUps.megaPaddlecount+"", 300, 500);
}
if(PowerUps.isMegaBall){
g.setColor(Color.red);
g.setFont(TimeFont);
g.drawString(PowerUps.megaBallcount+"", 250, 400);
}
if(!game.activeAlerts.isEmpty()){
for(AlertText alert: game.activeAlerts){
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, alert.getTextSize()));
g.setColor(alert.getColor());
g.drawString(alert.getText(), alert.getxPos(), alert.getxPos());
if(alert.count<=0){
game.activeAlerts.remove(alert);
}
}
}
}
public void updateGameState()
{
gameBall.move();
player.move(controller);
gl.checkCollisions(gameBall, player, timer, WIDTH, HEIGHT, game);
gl.removeBrick();
// Move GameObjects and check for collisions here
if(Paddle.paddleHits==1 && !PaddleUpdateComplete){
gameBall.setXVelocity(10);
gameBall.setYVelocity(gameBall.getYVelocity()-6);
PaddleUpdateComplete = true;
}
}
public final void setupGame()
{
gameBall.setXVelocity(0);
gameBall.setYVelocity(-10);
player.setLives(5);
gl.makeBricks();
// Instantiate instance variables here
}
// Constructor method should not be modified
public Game()
{
// Set the size of the Panel to the correct size
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
// Set the background color of the Panel to black
this.setBackground(Color.BLACK);
// Instantiate a KeyboardController and listen for input with it
controller = new KeyboardController();
this.addKeyListener(controller);
// Call the setupGame method to initialize instance variables
this.setupGame();
// Get focus in the window
this.setFocusable(true);
this.requestFocusInWindow();
}
// Start method should not be modified
public void start()
{
// Set up a new Timer to repeat every 20 milliseconds (50 FPS)
timer = new Timer(20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
repaint();
updateGameState();
}
});
timer.setRepeats(true);
timer.start();
}
Timer timer;
}
警报 Class 方法 fireText()
public void fireText(){
count = 50;
textSize=0;
Firing=true;
Timer time = new Timer(50, null);
time.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(count>47){
textSize+=10;
xPos-=2;
count--;
}
else if(count>42){
count--;
}
else {
yPos -= 1;
xPos += 1;
textSize -= 1;
count--;
if(count<=0) {
text ="";
count=-1;
Firing =false;
time.stop();
}
}
}
});
time.start();
}
GameLogic 方法
public void checkCollisions(Ball ball, Paddle player, Timer time, int WIDTH, int HEIGHT, Game game) {
if(hitPaddle(ball, player)){
ball.setYVelocity(ball.getYVelocity() * -1);
Paddle.paddleHits++;
return;
}
//check if ball hit any walls
if(ball.getXPosition() >= (WIDTH - ball.getDiameter()) || ball.getXPosition() <= 0){
ball.setXVelocity(ball.getXVelocity() * -1);
}
if(ball.getYPosition() > (player.getYPosition() + player.getHeight() + 10)){
resetBall(ball, player, time, WIDTH, HEIGHT);
}
if(ball.getYPosition() <= 0){
ball.setYVelocity(ball.getYVelocity() * -1);
}
//handle collisions between bricks
int brickRowsActive = 0;
for(ArrayList<Brick> alb : bricks){
if(alb.size() == horizontalCount){
++brickRowsActive;
}
}
for(int i = (brickRowsActive==0) ? 0 : (brickRowsActive - 1); i < bricks.size(); ++i){
for(Brick b : bricks.get(i)){
if(brickHitByBall(ball, b)){
checkPowerUps(b, player, ball);
game.spawnNewAlert(b);
player.setScore(player.getScore() + b.getPoints());
b.decrementType();
}
}
}
}
据我了解,您想通过另一个对象触发一个对象中的方法,这两个对象都包含在第三个上层对象中,对吗?
我会在 Game 对象中同时创建 AlertText 和 GameLogic 对象,然后将 AlertText 的引用传递给 GameLogic,从而使 GameLogic 可以触发 AletText 的 fireText() 方法。您必须从 spawnNewAlert 方法中删除 AlertText 的实例化(实际上您只需要一个 AlertText 实例),并稍微修改一下 fireText 方法以在每个 运行.
后重置
在 GameLogic 中:
AlertText alert;
public GameLogic(AlertText alert //other parameters) {
this.alert = alert;
//other stuff you do here
}
在游戏中假设:
GameLogic gameLogic;
AlertText alertText;
public Game() {
alertText = new AlertText();
gameLogic = new GameLogic(alertText);
}
public void paint(Graphics g) {
gameLogic.spawnNewAlert(brick);
}
可能您想要在 Game
class 中完成渲染的警报列表,并且您希望能够在 GameLogic
class 处理所有游戏的地方。
有多种方法可以做到这一点。假设您在 GameLogic
中引用了 Game
class,然后将 spawnNewAlert()
的代码移至 Game
。然后你的代码在GameLogic
可以调用game.spawnNewAlert(b)
然后交给Game
class去管理。
您需要在 Game
class:
中添加一些内容
- 新成员字段
private List<AlertText> activeAlerts = new ArrayList<AlertText>();
- 在
spawnNewAlert()
中,就在您 fireText() 之前,将警报添加到 activeAlerts
- 在
paint()
中,遍历 activeAlerts
并绘制每一个,删除任何不再有效的(注意如何删除,使用 Iterator
或推迟在迭代后移除 to 以防止 ConcurrentModificationException
.)
我正尝试在 Java Swing GUI 中为我的突破游戏创建一些动画游戏文本。
预期行为:每次砖块被击中时,它的点都会猛击到屏幕上,暂停 0.25 秒,然后逐渐消失。
我所做的: 在名为 AlertText
的 class 中的方法中使用了计时器。当砖块在 class GameLogic
中被击中时,一个新的 AlertText
被创建并且它的计时器开始 运行。现在在游戏中 Class 我有油漆 class.
问题: 那么我如何调用在 GameLogic
中创建的 AlertText
的特定实例来使用 setter 和getter 在 Game
class 中设置我的 g.drawString
画图的方法。我觉得这应该是一种常见的技术?有名字吗?
我让它与一种积木样式的全局变量一起工作,所以我知道动画正在运行,但我需要 100 多个全局变量来完成每种积木。
游戏Class
public class Game extends JPanel
{
public static final int HEIGHT = 720;
public static final int WIDTH = 600;
public Color color;
private GameLogic gl = new GameLogic();
private KeyboardController controller;
public Paddle player = new Paddle(110, HEIGHT-30, 100, 10, 10, color.black, controller);
public Ball gameBall = new Ball(300, 300, 15, color.black);
private boolean PaddleUpdateComplete = false;
private List<AlertText> activeAlerts = new ArrayList<AlertText>();
Game game = new Game();
public void spawnNewAlert(Brick b){
AlertText alert = new AlertText();
alert.setxPos(b.getXPosition());
alert.setyPos(b.getYPosition());
alert.setText(b.getPoints()+"");
alert.setColor(b.getColor());
activeAlerts.add(alert);
alert.fireText();
}
@Override
public void paint(Graphics g)
{
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, (int)AlertText.staticAlertSize));
g.setColor(new Color(AlertText.staticRed, AlertText.staticGreen, AlertText.staticBlue));
g.drawString(AlertText.staticAlertOne, AlertText.staticAlertXPos, AlertText.staticAlertYPos);
player.draw((Graphics2D)g);
gameBall.draw((Graphics2D)g);
gl.drawBricks(g);
// Draw GameObjects and anything else here
g.setFont(scoreFont);
g.drawString("Score: " + player.getScore(), 10, 25);
g.drawString("LIVES: " + player.getLives(), 150, 25);
if(gl.gameOver(player) &&
gameBall.getYPosition() >= HEIGHT){
g.setColor(Color.black);
g.setFont(endFont);
g.drawString("Game Over! Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
}
if(gl.empty()){
g.setColor(Color.black);
g.setFont(endFont);
g.drawString("You won! Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
timer.stop();
}
if(PowerUps.isMegaPaddle){
g.setColor(Color.orange);
g.setFont(TimeFont);
g.drawString(PowerUps.megaPaddlecount+"", 300, 500);
}
if(PowerUps.isMegaBall){
g.setColor(Color.red);
g.setFont(TimeFont);
g.drawString(PowerUps.megaBallcount+"", 250, 400);
}
if(!game.activeAlerts.isEmpty()){
for(AlertText alert: game.activeAlerts){
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, alert.getTextSize()));
g.setColor(alert.getColor());
g.drawString(alert.getText(), alert.getxPos(), alert.getxPos());
if(alert.count<=0){
game.activeAlerts.remove(alert);
}
}
}
}
public void updateGameState()
{
gameBall.move();
player.move(controller);
gl.checkCollisions(gameBall, player, timer, WIDTH, HEIGHT, game);
gl.removeBrick();
// Move GameObjects and check for collisions here
if(Paddle.paddleHits==1 && !PaddleUpdateComplete){
gameBall.setXVelocity(10);
gameBall.setYVelocity(gameBall.getYVelocity()-6);
PaddleUpdateComplete = true;
}
}
public final void setupGame()
{
gameBall.setXVelocity(0);
gameBall.setYVelocity(-10);
player.setLives(5);
gl.makeBricks();
// Instantiate instance variables here
}
// Constructor method should not be modified
public Game()
{
// Set the size of the Panel to the correct size
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
// Set the background color of the Panel to black
this.setBackground(Color.BLACK);
// Instantiate a KeyboardController and listen for input with it
controller = new KeyboardController();
this.addKeyListener(controller);
// Call the setupGame method to initialize instance variables
this.setupGame();
// Get focus in the window
this.setFocusable(true);
this.requestFocusInWindow();
}
// Start method should not be modified
public void start()
{
// Set up a new Timer to repeat every 20 milliseconds (50 FPS)
timer = new Timer(20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
repaint();
updateGameState();
}
});
timer.setRepeats(true);
timer.start();
}
Timer timer;
}
警报 Class 方法 fireText()
public void fireText(){
count = 50;
textSize=0;
Firing=true;
Timer time = new Timer(50, null);
time.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(count>47){
textSize+=10;
xPos-=2;
count--;
}
else if(count>42){
count--;
}
else {
yPos -= 1;
xPos += 1;
textSize -= 1;
count--;
if(count<=0) {
text ="";
count=-1;
Firing =false;
time.stop();
}
}
}
});
time.start();
}
GameLogic 方法
public void checkCollisions(Ball ball, Paddle player, Timer time, int WIDTH, int HEIGHT, Game game) {
if(hitPaddle(ball, player)){
ball.setYVelocity(ball.getYVelocity() * -1);
Paddle.paddleHits++;
return;
}
//check if ball hit any walls
if(ball.getXPosition() >= (WIDTH - ball.getDiameter()) || ball.getXPosition() <= 0){
ball.setXVelocity(ball.getXVelocity() * -1);
}
if(ball.getYPosition() > (player.getYPosition() + player.getHeight() + 10)){
resetBall(ball, player, time, WIDTH, HEIGHT);
}
if(ball.getYPosition() <= 0){
ball.setYVelocity(ball.getYVelocity() * -1);
}
//handle collisions between bricks
int brickRowsActive = 0;
for(ArrayList<Brick> alb : bricks){
if(alb.size() == horizontalCount){
++brickRowsActive;
}
}
for(int i = (brickRowsActive==0) ? 0 : (brickRowsActive - 1); i < bricks.size(); ++i){
for(Brick b : bricks.get(i)){
if(brickHitByBall(ball, b)){
checkPowerUps(b, player, ball);
game.spawnNewAlert(b);
player.setScore(player.getScore() + b.getPoints());
b.decrementType();
}
}
}
}
据我了解,您想通过另一个对象触发一个对象中的方法,这两个对象都包含在第三个上层对象中,对吗?
我会在 Game 对象中同时创建 AlertText 和 GameLogic 对象,然后将 AlertText 的引用传递给 GameLogic,从而使 GameLogic 可以触发 AletText 的 fireText() 方法。您必须从 spawnNewAlert 方法中删除 AlertText 的实例化(实际上您只需要一个 AlertText 实例),并稍微修改一下 fireText 方法以在每个 运行.
后重置在 GameLogic 中:
AlertText alert;
public GameLogic(AlertText alert //other parameters) {
this.alert = alert;
//other stuff you do here
}
在游戏中假设:
GameLogic gameLogic;
AlertText alertText;
public Game() {
alertText = new AlertText();
gameLogic = new GameLogic(alertText);
}
public void paint(Graphics g) {
gameLogic.spawnNewAlert(brick);
}
可能您想要在 Game
class 中完成渲染的警报列表,并且您希望能够在 GameLogic
class 处理所有游戏的地方。
有多种方法可以做到这一点。假设您在 GameLogic
中引用了 Game
class,然后将 spawnNewAlert()
的代码移至 Game
。然后你的代码在GameLogic
可以调用game.spawnNewAlert(b)
然后交给Game
class去管理。
您需要在 Game
class:
- 新成员字段
private List<AlertText> activeAlerts = new ArrayList<AlertText>();
- 在
spawnNewAlert()
中,就在您 fireText() 之前,将警报添加到activeAlerts
- 在
paint()
中,遍历activeAlerts
并绘制每一个,删除任何不再有效的(注意如何删除,使用Iterator
或推迟在迭代后移除 to 以防止ConcurrentModificationException
.)