To add trails to the ball when it shoots and introduce a main menu screen with different game modes, we will divide the task into a few steps:
Main Menu: Create a menu that shows the game title and options to start the game or choose game modes.
Game Modes: Implement placeholders for different game modes that can be selected.
Ball Trails: Create a system that tracks the position of the ball as it moves after shooting, allowing us to draw a trail.
Let's update your existing code accordingly.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
body {
background: #faf8ef;
margin: 0;
padding: 0;
}
canvas {
border: 2px solid black;
margin: 0 auto;
display: block;
}
button {
border-radius: 5px;
font-size: 1.5em;
display: block;
margin: 10px auto;
}
#menu {
text-align: center;
padding-top: 20px;
}
#game {
display: none;
}
</style>
</head>
<body>
<div id="menu">
<h1>Ball Game</h1>
<button onclick="startGame()">Start Game</button>
<button onclick="selectGameMode('easy')">Easy Mode</button>
<button onclick="selectGameMode('hard')">Hard Mode</button>
</div>
<div id="game">
<canvas id="canvas" width="720" height="800"></canvas>
<button onclick="gameManager.downBalls()">공 내리기</button>
</div>
<script>
// Constant for trail length
const TRAIL_LENGTH = 10;
function randomInt(...args) {
if (args.length === 1) {
const [n] = args;
return Math.ceil(Math.random() * n);
}
if (args.length === 2) {
const [start, end] = args;
if (start > end) throw Error("Start value is greater than end.");
return Math.ceil(Math.random() * (end - start)) + start;
}
}
// Your existing functions...
class Ball {
constructor(mass, x, y) {
this.position = new Vector(x, y);
this.velocity = new Vector(0, 0);
this.acceleration = new Vector(0, 0);
this.mass = mass;
this.r = this.mass * 8;
this.trail = [];
}
// Your existing methods...
trailEffect() {
if (this.trail.length >= TRAIL_LENGTH) {
this.trail.shift(); // Remove the oldest element
}
this.trail.push(this.position.copy()); // Add the current position
}
display() {
// Display the trail
for (let i = 0; i < this.trail.length; i++) {
const alpha = 1 - (i / this.trail.length);
circle(this.trail[i].x, this.trail[i].y, this.r, `rgba(91, 167, 244, ${alpha})`);
}
// Display the ball
circle(this.position.x, this.position.y, this.r, "#5ba7f4");
}
}
class GameManager {
constructor() {
this.state = {
ballPos: new Vector(width / 2, height - 100),
ballMoving: false,
ballCount: 1,
ballDowning: false,
brickMoving: false,
firstBallStop: true,
level: 1,
over: false,
};
this.balls = new Balls(this.state);
this.bricks = new Bricks();
this.bonusBalls = new BonusBalls();
this.ballLine = new BallLine();
this.ui = new UI();
this.scoreStorage = new LocalStorageManager();
this.state.bestLevel = this.scoreStorage.getBestScore();
this.addBallsAndBricks();
canvas.addEventListener("click", (e) => this.shootBalls(e));
}
async shoot(mousePos, state) {
for (const ball of this.balls) {
if (state.ballDowning) return;
ball.shoot(mousePos);
await delay(Math.max(50 - ~~(state.ballCount / 10), 10));
}
}
// Other existing methods...
}
function startGame() {
document.getElementById("menu").style.display = "none";
document.getElementById("game").style.display = "block";
gameManager = new GameManager();
gameManager.run();
}
function selectGameMode(mode) {
console.log(`Selected game mode: ${mode}`);
// Logic for different game modes can be added here.
startGame(); // Start game after selecting mode
}
</script>
<script>
// All the other existing scripts...
</script>
</body>
</html>
Highlights of the Code Changes:
Menu Structure:
Added a div for the main menu where the "Start Game" and game mode buttons are available.
The game area (with the canvas and button) is hidden until the game starts.
Ball Trail Effect:
Each ball maintains a list of its previous positions, allowing it to draw a fading trail.
The trailEffect() method handles storing the position, and the display() method was updated to render the trail behind the ball.
Main Game Logic:
The startGame() function initiates the game while hiding the menu.
The selectGameMode() function allows for selecting a game mode before starting the game (you can expand this logic to change parameters for different modes if required).
Graphics and Interaction:
The trail drawing uses rgba colors to provide a fading effect to the trails of the balls.
Styling: Basic styles were applied to center the menu and show a button interface for launching the game.
This code serves as a foundation; you can implement more elaborate game modes and effects based on the requirements.
Certainly! Below is the complete HTML script that incorporates a main menu screen, game modes, and the feature of ball trails when shooting. The main components are organized so you can easily follow along:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ball Game</title>
<style>
body {
background: #faf8ef;
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
canvas {
border: 2px solid black;
margin: 0 auto;
display: block;
}
button {
border-radius: 5px;
font-size: 1.5em;
display: block;
margin: 10px auto;
}
#menu {
text-align: center;
padding-top: 20px;
}
#game {
display: none;
}
</style>
</head>
<body>
<div id="menu">
<h1>Ball Game</h1>
<button onclick="startGame()">Start Game</button>
<button onclick="selectGameMode('easy')">Easy Mode</button>
<button onclick="selectGameMode('hard')">Hard Mode</button>
</div>
<div id="game">
<canvas id="canvas" width="720" height="800"></canvas>
<button onclick="gameManager.downBalls()">공 내리기</button>
</div>
<script>
const TRAIL_LENGTH = 10;
function randomInt(...args) {
if (args.length === 1) {
const [n] = args;
return Math.ceil(Math.random() * n);
}
if (args.length === 2) {
const [start, end] = args;
if (start > end) throw Error("Start value is greater than end.");
return Math.ceil(Math.random() * (end - start)) + start;
}
}
const range = function (n, m) {
if (arguments.length === 1)
return Array.from({ length: n }).map((_, i) => i);
if (arguments.length === 2) {
if (n === m) return [n];
else if (n < m) {
return Array.from({ length: m - n + 1 }).map((_, i) => i + n);
} else {
return Array.from({ length: n - m + 1 }).map(
(_, i) => m - i + (n - m)
);
}
}
};
const normalize = (n) => (n < 0 ? -1 : n > 0 ? 1 : 0);
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
class Vector {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
add(v) {
this.x += v.x;
this.y += v.y;
}
sub(v) {
this.x -= v.x;
this.y -= v.y;
}
mult(n) {
this.x *= n;
this.y *= n;
}
mag() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
copy() {
return new Vector(this.x, this.y);
}
}
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const width = 720;
const height = 800;
const uiOffsetY = 80;
function clear() {
ctx.clearRect(0, 0, width, height);
}
function circle(x, y, r, color = "#000") {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
class Ball {
constructor(mass, x, y) {
this.position = new Vector(x, y);
this.velocity = new Vector(0, 0);
this.acceleration = new Vector(0, 0);
this.mass = mass;
this.r = this.mass * 8;
this.trail = [];
}
applyForce(force) {
const f = Vector.div(force, this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
this.trailEffect();
}
trailEffect() {
if (this.trail.length >= TRAIL_LENGTH) {
this.trail.shift();
}
this.trail.push(this.position.copy());
}
shoot(mousePos) {
const force = this.calcBallVelocity(this.angle(mousePos));
this.applyForce(force);
}
calcBallVelocity(angle) {
return new Vector(
100 * Math.cos(angle),
100 * Math.sin(angle)
);
}
angle(mousePos) {
const opposite = mousePos.y - this.position.y;
const adjacent = mousePos.x - this.position.x;
return Math.atan2(opposite, adjacent);
}
display() {
// Draw trail
for (let i = 0; i < this.trail.length; i++) {
const alpha = 1 - (i / this.trail.length);
circle(this.trail[i].x, this.trail[i].y, this.r, `rgba(91, 167, 244, ${alpha})`);
}
// Draw ball
circle(this.position.x, this.position.y, this.r, "#5ba7f4");
}
}
class GameManager {
constructor() {
this.state = {
ballPos: new Vector(width / 2, height - 100),
ballMoving: false,
ballCount: 1,
ballDowning: false,
brickMoving: false,
firstBallStop: true,
level: 1,
over: false,
};
this.balls = [];
this.initializeBalls(this.state.ballCount);
canvas.addEventListener("click", (e) => this.handleShoot(e));
}
initializeBalls(count) {
for (let i = 0; i < count; i++) {
this.balls.push(new Ball(2, this.state.ballPos.x, this.state.ballPos.y));
}
}
handleShoot(e) {
if (this.state.ballMoving || this.state.over) return;
this.state.ballMoving = true;
const mousePos = { x: e.pageX - canvas.offsetLeft, y: Math.min(e.pageY, 720) };
this.balls[0].shoot(mousePos);
}
draw() {
clear();
this.balls.forEach((ball) => {
ball.update();
ball.display();
});
}
run() {
this.draw();
requestAnimationFrame(() => this.run());
}
downBalls() {
this.state.ballDowning = true;
this.balls.forEach((ball) => {
ball.velocity.y = 10; // Custom logic for downing balls
});
}
}
// Game Operations
function startGame() {
document.getElementById("menu").style.display = "none";
document.getElementById("game").style.display = "block";
gameManager = new GameManager();
gameManager.run();
}
function selectGameMode(mode) {
console.log(`Selected game mode: ${mode}`);
// Logic for different game modes can be added here.
startGame(); // Start the game after selecting mode
}
</script>
</body>
</html>
Explanation of the Complete Script:
HTML Structure: The layout includes a main menu with buttons for starting the game and selecting game modes. When starting the game, the canvas appears.
Style: Basic CSS styles are applied to keep the design simple and readable.
JavaScript Logic:
Vector Class: For handling 2D vector operations.
Ball Class: Represents the ball, handling its movement, shooting mechanics, and trail drawing.
GameManager Class: Manages the game state, including ball creation, shooting, and the game loop with requestAnimationFrame.
The trail effect for the ball is implemented in the Ball class, storing positions and rendering with decreasing opacity.
Gameplay: The game includes a simplification of the gameplay mechanics. Players can shoot a ball, and it leaves a trail behind it.
Game Modes: The selectGameMode function currently logs the chosen mode for further implementation; gameplay can be customized based on the selected mode.
Further Customization:
You can expand the features by handling brick spawning, collisions, scoring, and more complex game mechanics. Enjoy building out your game!