我制作了一个飞扬的鸟类游戏,并且一直运作良好。但是现在我遇到了一个问题,我希望当这只鸟接触到墙壁的颜色时,游戏就会重新开始。这是源代码。顺便说一句,我认为这可能没有正确格式化。由于我是新手,您还可以建议如何正确编码此代码吗?谢谢。
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.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FlappyBirds extends JPanel implements ActionListener,KeyListener {
public int WIDTH=800,HEIGHT=800,x=WIDTH/2-10,y=HEIGHT/2-10 , gravity=0, ticks=0;
public static FlappyBirds flappy;
public boolean jump;
public boolean run=true;
public ArrayList<Rectangle>walls;
public Random generator;
public FlappyBirds(){
Timer t=new Timer(10,this);
JFrame window=new JFrame("Flappy Birds");
window.setSize(WIDTH ,HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(this);
window.setVisible(true);
window.addKeyListener(this);
walls=new ArrayList<Rectangle>();
generator=new Random();
addWall(true);
addWall(true);
t.start();
}
public static void main(String[] args) {
flappy=new FlappyBirds();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(new Color(0,200,255));
g.fillRect(0,0,WIDTH,HEIGHT);
g.setColor(Color.ORANGE);
g.fillRect(0, HEIGHT-100, WIDTH,100);
g.setColor(Color.GREEN);
g.fillRect(0,HEIGHT-110,WIDTH,10);
g.setColor(Color.red);
g.fillRect(x, y, 15, 15);
g.setFont(new Font("Arial",15,15));
int colorman=0;
g.setColor(new Color(200,200,40));
for(Rectangle rect:walls){
paintWall(rect,g);
}
}
@Override
public void actionPerformed(ActionEvent e) {
while(run==true){
repaint();
ticks ++;
if(jump){
if(ticks%8==0){
gravity=-10;
}
}
else if(ticks%8==0 && gravity<15 && jump==false){
gravity+=2;
}
y += gravity;
for(Rectangle rect:walls){
rect.x -=10;
}
for(int i=0;i<walls.size();i++){
Rectangle r=walls.get(i);
if(r.x+r.width<0){
walls.remove(r);
addWall(false);
}
}
}
}
}