xxxxxxxxxx
// DAY 4 - START HERE
// variables used throughout program
int posX;
int posY;
Racer player1;
Racer player2;
boolean gameRunning=true;
// happens once at beginning
void setup(){
size(640,480);
player1=new Racer(1);
player2=new Racer(2);
}
// happens over and over
void draw() {
// put graphics on the screen
drawBackground();
posX= player1.getX();
posY= player1.getY ();
image(player1.getImage(),
posX,
posY);
posX=player2.getX();
posY=player2.getY();
image(player2.getImage(),posX,posY);
// check for winner
if (player1. hasWon())
{
gameRunning= false;
fill(255);
textSize(32);
text("Player 1 Has won",175,240);
}
if (player2.hasWon())
{
gameRunning = false;
fill(255);
textSize(32);
text("Player 2 Has won",175,240);
}
}
void keyPressed ()
{
if(gameRunning){
if (key =='d')
{
player1.rightKey();
} else if (key == 'a')
{
player1.leftKey();
}
if (key == 'j')
{
player2.leftKey();
}
if (key == 'l')
{
player2.rightKey();
}
}
else
{
if (key == ENTER)
{
player1=new Racer(1);
player2=new Racer(2);
gameRunning= true;
}
}
}
void drawBackground()
{
background(#AD2BDE);
fill(#00F061);
rect(0,100,640,100);
// bottom strip of grass
rect(0,400,640,100);
drawTree(20,400);
drawTree(80,400);
drawTree (300,400);
drawTree (200,400);
//bottom strip of grass
drawTree (150,400);
drawTree (80,400);
}
void drawTree(int x, int y)
{
// tree
fill(#6C2B0A);
rect(x+80,y+10,20,50);
fill(#0E5A11);
triangle(x+40,y+20,x+140,y+20,x+90,y-30);
}
class Racer
{
private PImage racerPose1;
private PImage racerPose2;
private int xLoc;
private int yLoc;
private boolean tapFlag = false;
private boolean won = false;
public Racer()
{
}
public Racer(int player)
{
xLoc = 0;
yLoc = player == 2 ? 220 : 0;
if (player == 1)
{
racerPose1 = loadImage("player1_1.jpg");
racerPose2 = loadImage("player1_2.jpg");
}
if (player >= 2)
{
racerPose1 = loadImage("player2_1.jpg");
racerPose2 = loadImage("player2_2.jpg");
}
}
public void leftKey() {
if(tapFlag) {
moveForward();
} else {
moveBackward();
}
tapFlag = false;
}
public void rightKey() {
if(!tapFlag) {
moveForward();
} else {
moveBackward();
}
tapFlag = true;
}
private void moveForward() {
xLoc++;
won = xLoc >= 50;
}
private void moveBackward() {
if (xLoc > 0)
{
xLoc--;
}
}
public int getX() {
return (xLoc*10) + 35;
}
public int getY() {
return yLoc + 40;
}
public boolean hasWon() {
return won;
}
public PImage getImage() {
if(tapFlag) {
return racerPose1;
} else {
return racerPose2;
}
}
}