Ad Code

ARTIFICIAL INTELLIGENCE for PONG GAME in p5.js | VIVEK

 

ARTIFICIAL INTELLIGENCE FOR PONG

Pong was the first sports-based arcade videogame. Basically, it is a virtual version of table tennis. At the time of this project's conception, I had gone through a long period of time without touching neither Java, nor the subject of artificial intelligence. I felt like I neglected both of these long enough and that it was time to come up with a small project that will serve as practice. Making a game-engine for Pong - plus a challenging artificial player to play against - is just the kind of exercise I was looking for!


Source : screenshot - p5.js window, Pong game by VIVEK.


Game rules

Pong is governed by very simple rules. The virtual table is rectangular, with each player controlling a paddle on opposing sides. Let's call the sides the players occupy goals and the sides they do not walls. The ball is released in the center and bounces around upon contact with either paddles or walls. Each player's objective is to not let the ball touch its goal, since that constitutes a loss.



In all further discussion we will assume the players take the bottom/top sides of the table as their goals. Players can move their paddles left and right at constant top-speed. The ball is also moving at constant speed, and bounces off surfaces it collides with according to the following rules:

  1. Normally, the ball moves in constant speed in its current direction until it hits either a wall or a paddle (if it hits a goal, the game ends).
  2. Upon hitting a wall, the ball's movement direction is reflected across the surface normal, as if it were a ray of light bouncing off a mirror.
  3. Upon hitting a paddle, the ball's new direction depends on its distance from the paddle center: A hit dead on the middle results in a bounce direction that is straight-up. A hit on the edge will send the ball in a low-angled direction away.


Designing an artificial opponent

The making of the game-engine itself was not very eventful or exciting. The making of the AI, on the other hand, was a lot of fun. We started with a very simple game-plan, and iteratively identified its deficiencies and worked to amend them up to the point where the AI felt challenging enough.


Coding an artificial opponent is not easy, read the things we have to keep in mind while creating "Player 2":


Much better! Playing against this AI is already quite challenging, and although the AI can still technically be exploited, such exploits requires quite the gameplay skill. All in all, we have achieved our objective of making a reasonably challenging artificial opponent for Pong.



👾 Are you curious to create yours?

Follow this instructions:

(Copy & Paste in p5.js editor)


const RAD2DEG = 180 / Math.PI;
const DEG2RAD = Math.PI / 180;
function rand(a, b) {
    return (a + Math.random() * (b - a));
}
function setup() {
    createCanvas(600, 400);
    background(20);
  
    fill(225);
    textAlign(CENTER);
    paddles = new Group();
    player = createSprite(width-10, height / 2, 10, 70);
    player.shapeColor = 'blue';
    paddles.add(player);
    computer = createSprite(10, height / 2, 10, 70);
    computer.shapeColor = 'red';
    paddles.add(computer);
    ball = createSprite(width / 2, height / 2, 15, 15);
    ball.shapeColor = 'white';
    computerPos = Array.apply(null, Array(10)).map(Number.prototype.valueOf, height / 2);
    score = [0,0];
    ball.setSpeed(4, rand(-10, 10));
}
function draw() {
    background('#0f0');
  noFill();
  rect(0, 80, 100, 240);
  rect(0, 145, 30, 100);
  rect(500, 80, 100, 240);
   rect(570, 145, 30, 100);
  rect(300, 0, 1, 400);
  ellipse(width/2, height/2, 120);
    drawSprites();
  
    // set play paddle position to mouse position, within bounds
    player.position.y = Math.max(0, Math.min(height, mouseY));
    // perfect computer player
    // computer.position.y = ball.position.y;
    // delayed computer player
    computerPos.push(ball.position.y);
    computer.position.y = computerPos.shift();
    // wall collisions
    if (ball.position.y < 4 || ball.position.y > height - 4) {
        ball.velocity.y *= -1;
    }
    // goal collisions
    if (ball.position.x < 4) {
        score[1]++;
        ball.position.x = width/2;
        ball.position.y = height/2;
        ball.setSpeed(4, rand(170,190));
    }
    else if (ball.position.x > width - 4) {
        score[0]++;
        ball.position.x = width/2;
        ball.position.y = height/2;
        ball.setSpeed(4, rand(-10,10));
    }
    // ball/paddle collisions
    ball.overlap(paddles, function(ball, paddle) {
        ball.velocity.x *= -1.01;
        ball.velocity.y += (ball.position.y - paddle.position.y) / 20;
    });
    scoreText = score[0] + " – " + score[1];
    text(scoreText, width/2, 20);
}


License

(CC0 1.0 Universal) You're free to use this game and code in any project, personal or commercial. There's no need to ask permission before using these. Giving attribution is not required, but appreciated.




⏰ IT'S TIME TO TEST!



"Be ready to catch the ball when it is thrown by life." ~ Steve Jobs

 



✅ Play the PONG Game here :

https://preview.p5js.org/VIVEK./present/qrjv_3iTq






To know more about my passions and interests as well as my other games like this, visit:




🌸 According to Bruce Lee:

"You will never learn anything new unless you are ready to accept yourself with your limitations. You must accept the fact that you are capable in some directions and limited in others, and you must develop your capabilities." ~ Bruce Lee

🔥 Another well-developed Pong Game for You!

https://codeincomplete.com/games/pong/


Source : Code inComplete


Conclusions

Although designed for this particular implementation of pong, the same concepts and code could be used for any version — it just comes down to changing some of the pre-processing steps. Of course, another method is to use machine learning through reinforcement learning or just simple conv net, but I like this classical approach; at least in this instance where I don’t need robust generality or difficult image processing steps. As I mentioned, this version of pong is 2 player, and I honestly cannot beat my own AI…



If you any part of this post provided some useful information or just a bit of inspiration please follow me for more.



🔍 About the Software : p5.js



p5.js is a JavaScript library for creative coding, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! p5.js is free and open-source because we believe software, and the tools to learn it, should be accessible to everyone.

Using the metaphor of a sketch, p5.js has a full set of drawing functionality. However, you’re not limited to your drawing canvas. You can think of your whole browser page as your sketch, including HTML5 objects for text, input, video, webcam, and sound.

👉 Visit : https://p5js.org/



📚 Learn

These tutorials provide more in-depth or step-by-step overviews of particular topics. Check out the examples page to explore short demonstrations of various p5.js topics.


Click Here : https://p5js.org/learn/



🌐  See also

  • More about Artificial Intelligence for Pong on this page.
  • You can view the source code and documentation on GitHub.

🌈 Wrapping Up

I hope you enjoyed this tutorial. If you had any doubts, then please comment them below. Thank you ;)

Get notified about the latest news, amazing facts, and many more at INFINITE VIVEK.

🛩️ Fly to our official Telegram Group.


  SUBSCRIBE  


Post a Comment

0 Comments

Ad Code