To begin with, here is the "Board" class code (my world):
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* The Board class is my world.
* @Robert Griffith
* @11/05/2013
*/
public class Board extends World
{
public Board()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(640, 480, 1);
prepare();
}
private void prepare()
{
//Counter counter = new Counter();
//addObject(counter, 48, 19);
Ball ball = new Ball();
addObject(ball, 320, 240);
Paddle1 paddle1 = new Paddle1();
addObject(paddle1, 10, 240);
Paddle2 paddle2 = new Paddle2();
addObject(paddle2, 630, 240);
}
}
Here is the moving Ball class code -- no bouncing your interaction yet:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* This is the Ball for our Pong game.
* @Robert Griffith
* @11/05/2013
*/
public class Ball extends Actor
{
int x = 320;
int y = 240;
int yDirection;
int ballSpeed;
int start = 0;
/**
* Runs the main program.
*/
public void act()
{
if (start == 0){ startup(); }
x = x + ballSpeed;
y = y + yDirection;
setLocation(x, y);
}
/**
* Set the direction and speed of the Ball
*/
public void startup(){
start++;
if ( Greenfoot.getRandomNumber(100) < 50 )
{ yDirection = -3; }
else { yDirection = 3; }
if ( Greenfoot.getRandomNumber(100) < 50 )
{ ballSpeed = -3; }
else { ballSpeed = 3; }
}
}
Next we have the paddles. Here is Paddle1:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* The left paddle (Paddle1) class.
* @Robert Griffith
* @11/05/213
*/
public class Paddle1 extends Actor
{
int y = 240;
int paddleSpeed = 10;
/**
* Run the program.
*/
public void act()
{
checkKeys();
}
/**
* Check keys and move the paddle
*/
public void checkKeys()
{
if ( Greenfoot.isKeyDown("a"))
{
y=y-paddleSpeed;
if (y < 48) {y = 48; } // y = half my paddle height
setLocation(10, y); // Set the x coordinate at 10
}
if ( Greenfoot.isKeyDown("z"))
{
y=y+paddleSpeed;
if (y > 432) {y = 432; } // y = world width - half my paddle height
setLocation(10, y); // Set the x coordinate at 10
}
}
}
Note that Paddle2 is nearly identical to Paddle1 except for being further over on the x axis.
No comments:
Post a Comment