#113行實現超簡單視覺化彈球java小遊戲
本來打算實現一個貪吃蛇,對於我現在還有點困難,,於是寫了一個更加簡單的彈球小遊戲,小白放心食用
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class snake {
Frame frame=new Frame();
//球大小
private final int ballX=10;
private final int ballY=10;
//球位置
private int blocalX=250;
private int blocalY=0;
//球速度
private int speedX=5;
private int speedY=-10;
//板磚大小
private final int brickY=10;
private final int brickX=40;
private int speed=10;
//板磚位置
private int BlocalX=230;
private int BlocalY=450;
//遊戲結束
private boolean isover=false;
//畫布大小
private final int x=500;
private final int y=500;
//timer
private Timer timer;
//重寫 canvas中paint
private class mycanvas extends Canvas{
@Override
public void paint(Graphics g) {
//遊戲結束時
if (isover){
g.drawString("GmaeOver!",240,250);
}
//遊戲進行時
else {
g.setColor(Color.red);
g.fillOval(blocalX,blocalY,ballX,ballY);
g.setColor(Color.yellow);
g.fillRect(BlocalX,BlocalY,brickX,brickY);
}
}
}
//建立畫板
mycanvas drawarea=new mycanvas();
public void init() {
//組裝與遊戲邏輯實現
KeyListener keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code=e.getKeyCode();
if(code==KeyEvent.VK_LEFT&&BlocalX-speed>=0)
BlocalX-=speed;
else if(code==KeyEvent.VK_RIGHT&&BlocalX+speed<=x-brickX)
BlocalX+=speed;
}
};
frame.addKeyListener(keyListener);
drawarea.addKeyListener(keyListener);
ActionListener actionListener=new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (blocalX<=0||blocalX>=x)
speedX=-speedX;
if(blocalY>BlocalY&&blocalX<BlocalX||blocalY>BlocalY&&blocalX<=BlocalX+brickX) {
timer.stop();
isover=true;
drawarea.repaint();
}
if(blocalY<=0||blocalY==BlocalY&&blocalX>=BlocalX&&blocalX<BlocalX+brickX)
speedY=-speedY;
blocalX+=speedX;
blocalY+=speedY;
drawarea.repaint();
}
};
drawarea.setPreferredSize(new Dimension(x,y));
frame.add(drawarea);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(1);
}
});
timer=new Timer(100,actionListener);
timer.start();
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new snake().init();
}
}