Skip to content

Instantly share code, notes, and snippets.

@depfryer
Last active October 30, 2020 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depfryer/2097313dea58d58c869bacd1f268401e to your computer and use it in GitHub Desktop.
Save depfryer/2097313dea58d58c869bacd1f268401e to your computer and use it in GitHub Desktop.
updateGame = function(delta) {
/* to update the location of the game, we're going to simulate it's position at
every millisecond since the last update. */
for (var i = 0; i < delta && state == updateGame; ++i) {
// move the ball
ball.advance();
// check to see what happened to the ball
if (!ball.bounced(p1, p2, PLAY_HEIGHT - LINE_WIDTH)) {
var scoringPlayer = null;
/* if the ball didn't hit anything, did it go past
any of the paddles? */
if (ball.x < p1.x) {
// slipping past paddle 1 means player 2 scored
scoringPlayer = p2;
} else if (ball.x > p2.x) {
// slipping past paddle 1 means player 2 scored
scoringPlayer = p1;
}
// if one of the players scored
if (scoringPlayer != null) {
// increase their score
scoringPlayer.scored();
//redrop the ball
ball.drop(scoringPlayer == p1 ? 1 : -1, p1.score + p2.score);
//show the status box for the next game state
statusBox.style.display = "block";
if (scoringPlayer.score < 100) {
/* we're still playing if the person who just scored hasn't hit
the max score. */
state = prePlay;
} else {
state = gameOver;
}
}
} else {
try {
boingplayer.play();
} catch (error) {}
}
}
if (state == updateGame) {
/* If we're still playing and haven't gone to the game-over or inter-point state,
then we'll run the P2 AI based on the ball's new location */
for (var i = 0; i < delta; i += AI_STEP) {
p2.AI(ball);
p1.AI(ball);
}
ball.display();
}
return true;
}
Player.prototype.AI = function (ball) {
/* the AI player is only going to play when the ball is moving towards it.
This means that the AI is specifically only coded for the paddle on the right
side of the play area */
if (ball.y > this.y + this.height - LINE_WIDTH) {
// the ball has moved past the bottom of the paddle
this.moveTo(this.y + 1);
} else if (ball.y < this.y) {
// the ball has moved past the top of the paddle
this.moveTo(this.y - 1);
}
};
AI_STEP = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment