package samsjava; import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class game extends Applet { paddle computer = new paddle(); paddle human = new paddle(); ball Ball = new ball(); java.util.Timer timer; Graphics doublebuffer; Image offscreen; int input = 0; private final int WIDTH =640; private final int HEIGHT = 480; public class ball { int x = 320; int y = 240; double xspeed=0; double yspeed=1; int size = 20; int direction = -1;; int speed=5; public void move () { if(direction == 1){ y-=yspeed; x-=xspeed; } if(direction == -1){ y+=yspeed; x+=xspeed; } } public void playerhit () { direction=1; xspeed = speed*Math.sin(human.x-Ball.x*(Math.PI/180)); xspeed*=-1; } public void wallhit(){ xspeed*=-1; } public void computerhit(){ direction=-1; xspeed = speed*Math.sin(computer.x-Ball.x*(Math.PI/180)); xspeed*=-1; } public void reset(){ x = 320; y = 240; size = 20; direction = -1; int xspeed=0; int yspeed=1; } } public class paddle { int x = 0; int y = 0; int width = 80; int height = 20; } public void init() { human.y=440; computer.y=0; this.setSize(WIDTH,HEIGHT); timer = new java.util.Timer(); timer.schedule(new gameTask(),0,1*10); offscreen = createImage(640,480); doublebuffer = offscreen.getGraphics(); } class gameTask extends TimerTask { public void run(){ if(Ball.y>690){ Ball.reset(); } if(Ball.x>640 || Ball.x<0){ Ball.wallhit(); } if(Ball.x-human.x>0 && Ball.x-human.x<80){ if(Ball.y>420 && Ball.y<460){ Ball.playerhit(); }} if(Ball.x-computer.x>0 && Ball.x-computer.x<80){ if(Ball.y>0 && Ball.y<20){ Ball.computerhit(); } } Ball.move(); computer.x=(Ball.x)-40; human.x+=input; repaint(); } } public boolean keyDown(Event evt,int key) { switch (key) { case Event.LEFT: if(human.x>0){ if(input>0){ input=0; } input-= 2; } break; case Event.RIGHT: if(human.x<600){ if(input<0){ input=0; } input+= 2; } break; } return true; } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { doublebuffer.clearRect(0,0,640,480); doublebuffer.fillRect(human.x,human.y,human.width,human.height); doublebuffer.fillOval(Ball.x,Ball.y,Ball.size,Ball.size); doublebuffer.fillRect(computer.x,computer.y,computer.width,computer.height); g.drawImage(offscreen,0,0,this); } }