以前一直没有在UI上面花时间,昨天想要试着写几个简单的游戏,才发现其实不掌握UI 技术就有好多断层,然后今天开始向它挑战 下午写了个弹球游戏
先上代码
package com.tanqiu;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
public class PinBall {
private final int X_TABLE=300;
private final int Y_TABLE=400;
private final int RACKET_WIDTH=60;
private final int RACKET_HEIGHT=10;
private int X_Speed=10;
private int Y_Speed=10;
private int BALL_SIZE=16;
private int ballx=10,bally=10;//小球的初始位置
private int racketx=0;//板的初始x位置
private final int rackety=300;
private boolean islose=false;
Frame f=new Frame();
MyCanvas drawArea=new MyCanvas();
Timer t;
public void init(){
drawArea.setPreferredSize(new Dimension(X_TABLE,Y_TABLE));
KeyAdapter key = new KeyAdapter(){
public void keyPressed(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
if(racketx>0)racketx-=10;
}
else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
if(racketx+RACKET_WIDTH< X_TABLE) racketx+=10;
}
}
};
f.addKeyListener(key);
drawArea.addKeyListener(key);
drawArea.setBackground(new Color(20,30,40));
ActionListener task=new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
t=new Timer();
t.schedule(new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
if(ballx>X_TABLE-BALL_SIZE*2||ballx<=0) X_Speed=-X_Speed;
if(bally>Y_TABLE-BALL_SIZE*3||bally<=0) Y_Speed=-Y_Speed;
else if((racketx-RACKET_WIDTH<ballx&&ballx<racketx+RACKET_WIDTH)&&(bally>=rackety-BALL_SIZE)) Y_Speed=-Y_Speed;
else if(bally>rackety){
islose=true;
t.cancel();
}
ballx+=X_Speed;
bally+=Y_Speed;
drawArea.repaint();
}
}, 100,100);
f.setBackground(new Color(20,30,40));
f.pack();
f.add(drawArea);
f.setVisible(true);
f.setSize(X_TABLE, Y_TABLE);
//f.setDefaultCloseOperation(3);
}
public static void main(String[] args){
new PinBall().init();
}
class MyCanvas extends Canvas{
public void paint(Graphics g){
if(islose==false){
g.setColor(new Color(220,100,80));
g.fillOval(ballx, bally, BALL_SIZE, BALL_SIZE);
g.setColor(new Color(80,80,200));
g.fillRect(racketx, rackety, RACKET_WIDTH, RACKET_HEIGHT);
}
else{
g.setColor(new Color(255,0,0));
g.setFont(new Font("Times",Font.BOLD,30));
g.drawString("您输了", 50, 200);
}
}
}
}
怎么说呢,效果是基本实现了,首先是界面比较丑,然后 那个刷新的太明显了 该查下怎么解决。
学到的东西吧,首先是绘图,使用Canvas来绘图的方法,建立一个类(可以是内部类)继承Canvas类 重写它的paint方法,实现画图的功能,在主函数中用repaint()来实现。