DEV Community

Rootooner
Rootooner

Posted on

My first game in JavaScript...

SO I made a game, but this was for my computer science class with CodeHS. It is fairly simple with just pressing the ball that has different colors on it.

Colors for the ball in the code:

//Red
//Yellow
//Green

*//THE CODE
*

`var RADIUS = 100;
var OFF_SCREEN = -200;
var DELAY = 600;
var ball;
var score = 10;
var scoreText;
var WIN_SCORE = 20;

//Starts the program start code
function start(){
setUpBall();
setTimer(changeBall, DELAY);
mouseClickMethod(clickHandler)

scoreText = new Text(score);
scoreText.setPosition(0, getHeight())
add(scoreText)
Enter fullscreen mode Exit fullscreen mode

}

function clickHandler(e){
var elem = getElementAt(e.getX(),e.getY());
if(elem != null && elem.getColor() ==
Color.green){
println("Great!")
score++;
}else{
println("Fail.")
score--;
}

    if(score == 0){
        displayMessage("You Lose :(");
    }
    if(score == WIN_SCORE){
        displayMessage("You Win!!! :D");
    }

    scoreText.setText(score);
Enter fullscreen mode Exit fullscreen mode

}

function displayMessage(text){
stopTimer(changeBall);
var msg = new Text(text);
msg.setPosition(getWidth()/2 - msg.getWidth()/2
,200)
add(msg)

}

//Sets up the ball for the game to be used with.
function setUpBall(){
ball = new Circle(RADIUS);
ball.setPosition(OFF_SCREEN, OFF_SCREEN);
add(ball);

}
//Makes the ball go in a random position every 500 milliseconds
function changeBall(){
var x = Randomizer.nextInt(ball.getRadius(),
getWidth() - ball.getRadius());
var y = Randomizer.nextInt(ball.getRadius(),
getHeight() - ball.getRadius());

    ball.setColor(Randomizer.nextColor());



    ball.setPosition(x, y); 
    changeColor();
Enter fullscreen mode Exit fullscreen mode

}
/changes the color of the ball from red to yellow when it
moves every time to a new position.
/
function changeColor(){
var colorCode = Randomizer.nextInt(0, 2);
var color;
if(colorCode == 0){
color = Color.red;
}else if(colorCode == 1){
color = Color.yellow;
}else{
color = Color.green
}

    ball.setColor(color);
Enter fullscreen mode Exit fullscreen mode

}`

The Result


https://codehs.com/sandbox/id/my-first-javascript-game-vQE9Su/run

Image description

Thanks! :D

Top comments (0)