gpt4 book ai didi

java - 当红色矩形与青色矩形碰撞时如何将其移除?

转载 作者:行者123 更新时间:2023-12-01 11:51:35 25 4
gpt4 key购买 nike

这是我的代码:

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

public class Draw extends JComponent implements KeyListener {

Random r = new Random();

int x = 0;
int y = 0;
int a = 5 * r.nextInt(150);
int b = 5 * r.nextInt(90);

Image img1 = Toolkit.getDefaultToolkit().getImage("C:/Users/Administrator/eclipse/My Projects/Game/src/bluebackground1.png");

public Draw(){
addKeyListener(this);
setFocusable(true);
}

//display
public void paint(Graphics g){
g.drawImage(img1, 0, 0, this);

g.setColor(Color.CYAN);
g.fill3DRect(x, y, 50, 50, true);

g.setColor(Color.RED);
g.draw3DRect(a, b, 50, 50, true);

g.setColor(Color.BLACK);
g.drawLine(0, 500, 800, 500);

g.setColor(Color.BLACK);
g.drawString("Press R to restart the game", 10, 540);
g.drawString("Use arrow keys to move", 600, 540);

if(x == a && y == b){
g.setColor(Color.BLACK);
g.setFont(new Font("", Font.PLAIN, 50));
g.drawString("Victory", 300, 550);
}
}

//controls
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_UP){
y -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_DOWN){
y += 5;
} else if(k.getKeyCode() == KeyEvent.VK_LEFT){
x -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_RIGHT){
x += 5;
}

if(k.getKeyCode() == KeyEvent.VK_R){
restart();
}

//border
if(x < 0){
x += 5;
} else if(x > 745){
x -= 5;
} else if(y < 0){
y += 5;
} else if (y > 450){
y -= 5;
}

repaint();
}

public void keyReleased(KeyEvent k) {}

public void keyTyped(KeyEvent k) {}

//restart function
public void restart(){
x = 0;
y = 0;
a = 5 * r.nextInt(150);
b = 5 * r.nextInt(90);
}
}

我想要的是,当可移动的青色矩形进入不可移动的红色矩形内部时,红色矩形永久消失,因为游戏尚未结束,青色矩形必须移动更多。

当红色矩形与青色矩形碰撞时如何将其移除?

最佳答案

Shape实例存储在List中。在绘制时,迭代列表并绘制每一个。删除一个形状后,将其从列表中删除并调用 repaint()

关于java - 当红色矩形与青色矩形碰撞时如何将其移除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28779733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com