本帖最后由 蒋映辉 于 2012-5-24 19:51 编辑
- 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);
- }
- }
- }
-
-
- }
复制代码 |