Posted On
//
Pinball is typically created using JavaScript along with HTML and CSS. Below is an example of a simple pinball game created using these languages:
HTML:
html
Pinball Game
CSS:
css
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#game-board {
position: relative;
width: 800px;
height: 500px;
margin: 0 auto;
border: 1px solid black;
}
#ball {
position: absolute;
top: 250px;
left: 400px;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
}
.flipper {
position: absolute;
bottom: 10px;
width: 100px;
height: 20px;
background-color: blue;
}
#left-flipper {
left: 100px;
}
#right-flipper {
right: 100px;
}
JavaScript (pinball.js):
javascript
document.addEventListener("DOMContentLoaded", function() {
var ball = document.getElementById("ball");
var gameBoard = document.getElementById("game-board");
var leftFlipper = document.getElementById("left-flipper");
var rightFlipper = document.getElementById("right-flipper");
// Set initial position of flippers
var flipperPosition = 400;
leftFlipper.style.transform = "translateX(" + flipperPosition + "px)";
rightFlipper.style.transform = "translateX(" + flipperPosition + "px)";
// Event listener to move flippers horizontally
document.addEventListener("keydown", function(event) {
if (event.key === "ArrowLeft") {
flipperPosition -= 10;
} else if (event.key === "ArrowRight") {
flipperPosition += 10;
}
leftFlipper.style.transform = "translateX(" + flipperPosition + "px)";
rightFlipper.style.transform = "translateX(" + flipperPosition + "px)";
});
// Function to move ball indefinitely
function moveBall() {
var ballX = parseInt(ball.style.left) || 400;
var ballY = parseInt(ball.style.top) || 250;
var ballXSpeed = 3;
var ballYSpeed = 3;
setInterval(function() {
if (ballX < 0 || ballX > 780) {
ballXSpeed = -ballXSpeed;
}
if (ballY < 0 || ballY > 480) {
ballYSpeed = -ballYSpeed;
}
ballX += ballXSpeed;
ballY += ballYSpeed;
ball.style.left = ballX + "px";
ball.style.top = ballY + "px";
}, 10);
}
moveBall();
});
This code creates a pinball game with a ball and two flippers. The ball moves automatically back and forth horizontally, and the flippers can be controlled using the left and right arrow keys. The ball bounces off the walls of the game board. Feel free to modify this code and add more features to create a more advanced version of the game.
Labels: