1 Star 0 Fork 0

itlantu/demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
game.js 13.39 KB
一键复制 编辑 原始数据 按行查看 历史
itlantu 提交于 2024-04-25 08:58 . 对话6
// 全局变量
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let gameInterval;
let score = 0;
let lives = 2;
let level = 1;
let gameStatus = '游戏未开始';
let paddle, ball, bricks;
let powerBallProbabilityThreeLives = 10;
let powerBallProbabilityTwoLives = 15;
const paddleWidth = 75;
const brickWidth = 75;
const brickHeight = 20;
const brickPadding = 10;
const brickOffsetTop = 30;
const brickOffsetLeft = 30;
let bricksRowCount = 3;
let isGameStarted = false;
const paddleHeight = 10;
const ballRadius = 10;
let rightPressed = false;
let leftPressed = false;
let time = { minutes: 0, seconds: 0 };
let timeInterval;
const brickRowCount = 3; // 根据游戏要求,初始时砖块的行数是3
let brickColumnCount = Math.floor((canvas.width - brickOffsetLeft * 2) / (brickWidth + brickPadding));
// 对话5,新增功能小球
const powerBallDropProbabilityThreeLives = 40; // 三格生命掉落功能小球概率
const powerBallDropProbabilityTwoLives = 40; // 两格生命掉落功能小球概率
// 对话6,一格生命掉落功能小球概率
let powerBallDropProbabilityOneLife = 10; // 一格生命掉落功能小球概率
let powerBalls = []; // 功能小球数组
function PowerBall(x, y, type) {
this.x = x;
this.y = y;
this.radius = 5; // 功能小球半径
this.type = type; // 功能小球类型
this.dy = 2; // 功能小球下落速度
}
// 对话5,新增功能小球
function drawPowerBalls() {
for (let i = 0; i < powerBalls.length; i++) {
let pb = powerBalls[i];
ctx.beginPath();
ctx.arc(pb.x, pb.y, pb.radius, 0, Math.PI * 2);
ctx.fillStyle = pb.type; // 根据功能小球的类型设置颜色
ctx.fill();
ctx.closePath();
}
}
// 对话5,新增功能小球
function movePowerBalls() {
for (let i = 0; i < powerBalls.length; i++) {
let pb = powerBalls[i];
pb.y += pb.dy;
if (pb.y > canvas.height - pb.radius) {
powerBalls.splice(i, 1); // 功能小球出界时移除
i--; // 索引调整
} else if (pb.x > paddle.x && pb.x < paddle.x + paddle.width && pb.y + pb.radius > canvas.height - paddle.height) {
activatePowerBall(pb.type); // 激活功能小球效果
powerBalls.splice(i, 1); // 功能小球被捡到时移除
i--; // 索引调整
}
}
}
function activatePowerBall(type) {
switch (type) {
case 'green':
if (lives < 5) lives++;
break;
case 'blue':
// 使小球分裂为两个(需要进一步实现小球分裂逻辑)
break;
case 'red':
if (paddle.width <= paddleWidth + 3 * 20) paddle.width += 20;
break;
}
updateLives(); // 更新生命值显示
}
function dropPowerBall(x, y) {
let dropChance = Math.random() * 100;
let powerBallType = Math.random() < 0.5 ? 'green' : (Math.random() < 0.5 ? 'blue' : 'red');
if (b.status === 2 && dropChance < powerBallDropProbabilityTwoLives) {
powerBalls.push(new PowerBall(x, y, powerBallType));
} else if (b.status === 3 && dropChance < powerBallDropProbabilityThreeLives) {
powerBalls.push(new PowerBall(x, y, powerBallType));
}
}
// 游戏对象
function Paddle() {
this.height = paddleHeight;
this.width = paddleWidth;
this.x = (canvas.width - paddleWidth) / 2;
this.dx = 7; // 挡板移动速度
}
function Ball() {
this.radius = ballRadius;
this.x = canvas.width / 2;
this.y = canvas.height - 30;
this.dx = 2; // 小球水平移动速度
this.dy = -2; // 小球垂直移动速度
}
function Brick(x, y, status) {
this.x = x;
this.y = y;
this.status = status; // 生命数
}
// 按键事件监听器
document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);
function keyDownHandler(e) {
if (e.key === 'Right' || e.key === 'ArrowRight' || e.key === 'd') {
rightPressed = true;
} else if (e.key === 'Left' || e.key === 'ArrowLeft' || e.key === 'a') {
leftPressed = true;
} else if (e.key === 'p' || e.key === 'P') {
togglePause();
} else if (e.key === 'r' || e.key === 'R') {
restartGame();
}
}
function keyUpHandler(e) {
if (e.key === 'Right' || e.key === 'ArrowRight' || e.key === 'd') {
rightPressed = false;
} else if (e.key === 'Left' || e.key === 'ArrowLeft' || e.key === 'a') {
leftPressed = false;
}
}
// 游戏功能函数
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddle.x, canvas.height - paddle.height, paddle.width, paddle.height);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < bricksRowCount; r++) {
if (bricks[c][r].status > 0) {
let brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
let brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
switch (bricks[c][r].status) {
case 3:
ctx.fillStyle = 'rgb(255, 0, 0)';
break;
case 2:
ctx.fillStyle = 'rgb(153, 68, 68)';
break;
case 1:
default:
ctx.fillStyle = 'rgb(128, 128, 128)';
break;
}
ctx.fill();
ctx.closePath();
}
}
}
}
// 计时器
function startTimer() {
timeInterval = setInterval(() => {
if (gameStatus !== '游戏暂停中') {
time.seconds++;
if (time.seconds >= 60) {
time.minutes++;
time.seconds = 0;
}
updateTimerDisplay();
}
}, 1000);
}
function updateTimerDisplay() {
const timerElement = document.getElementById('timer');
let formattedMinutes = time.minutes < 10 ? '0' + time.minutes : time.minutes;
let formattedSeconds = time.seconds < 10 ? '0' + time.seconds : time.seconds;
timerElement.textContent = `${formattedMinutes}${formattedSeconds}秒`;
}
// 更新游戏状态
function updateGameStatus() {
document.getElementById('game-status').textContent = gameStatus;
}
// 更新得分显示
function updateScore() {
document.getElementById('score').textContent = score.toString();
}
// 更新生命值显示
function updateLives() {
document.getElementById('lives').textContent = lives.toString();
}
// 初始化砖块
function initBricks() {
bricks = [];
for (let c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (let r = 0; r < bricksRowCount; r++) {
let brickStatus = getBrickStatus(level);
bricks[c].push(new Brick(0, 0, brickStatus));
}
}
}
// 根据关卡获取砖块的生命数
function getBrickStatus(currentLevel) {
// 根据当前关卡数调整砖块的生命数
let chance = Math.random();
if (chance < 0.5 - currentLevel * 0.05) {
return 1; // 一格生命砖块
} else if (chance < 0.8 - currentLevel * 0.03) {
return 2; // 两格生命砖块
} else {
return 3; // 三格生命砖块
}
}
// 游戏循环
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
collisionDetection();
if (rightPressed && paddle.x < canvas.width - paddle.width) {
paddle.x += paddle.dx;
} else if (leftPressed && paddle.x > 0) {
paddle.x -= paddle.dx;
}
// 球的反弹逻辑
if (ball.x + ball.dx > canvas.width - ball.radius || ball.x + ball.dx < ball.radius) {
ball.dx = -ball.dx;
}
if (ball.y + ball.dy < ball.radius) {
ball.dy = -ball.dy;
} else if (ball.y + ball.dy > canvas.height - ball.radius) {
if (ball.x > paddle.x && ball.x < paddle.x + paddle.width) {
ball.dy = -ball.dy;
} else {
lives--;
updateLives();
if (lives === 0) {
gameStatus = '游戏结束, 请点击重新开始';
updateGameStatus();
clearInterval(gameInterval);
clearInterval(timeInterval);
isGameStarted = false;
alert('游戏结束');
return;
} else {
ball.x = canvas.width / 2;
ball.y = canvas.height - 30;
ball.dx = 2;
ball.dy = -2;
paddle.x = (canvas.width - paddle.width) / 2;
}
}
}
// 更新球的位置
ball.x += ball.dx;
ball.y += ball.dy;
// 对话5,新增功能小球
drawPowerBalls(); // 绘制功能小球
movePowerBalls(); // 移动功能小球
// 检查游戏是否继续
checkGameContinue();
}
// 对话5,新增功能小球
function collisionDetection() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < bricksRowCount; r++) {
let b = bricks[c][r];
if (b.status > 0) {
if (ball.x > b.x && ball.x < b.x + brickWidth && ball.y > b.y && ball.y < b.y + brickHeight) {
ball.dy = -ball.dy;
b.status--;
if (b.status === 0) {
score++;
updateScore();
dropPowerBall(b.x, b.y); // 尝试掉落功能小球
if (isLevelCompleted()) {
levelCompleted();
}
}
}
}
}
}
}
// 检查当前关卡是否完成
function isLevelCompleted() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < bricksRowCount; r++) {
if (bricks[c][r].status > 0) {
return false;
}
}
}
return true;
}
// 当前关卡完成处理
function levelCompleted() {
// 对话6
powerBallDropProbabilityOneLife += 2; // 每通关一次,增加2%
clearInterval(gameInterval);
clearInterval(timeInterval);
if (level < 5) {
level++;
bricksRowCount++;
document.getElementById(`level${level - 1}-time`).textContent = `第${level - 1}关: ${time.minutes}${time.seconds}秒`;
startLevel(level);
} else {
gameStatus = '游戏结束, 请点击重新开始';
updateGameStatus();
isGameStarted = false;
alert('游戏胜利');
}
}
// 开始新的关卡
function startLevel(currentLevel) {
initBricks();
ball.x = canvas.width / 2;
ball.y = canvas.height - 30;
ball.dx = 2;
ball.dy = -2;
paddle.x = (canvas.width - paddle.width) / 2;
time = { minutes: 0, seconds: 0 };
updateTimerDisplay();
gameStatus = '游戏进行中';
updateGameStatus();
startTimer();
gameInterval = setInterval(gameLoop, 10);
}
// 切换暂停状态
function togglePause() {
if (gameStatus === '游戏暂停中') {
gameStatus = '游戏进行中';
gameInterval = setInterval(gameLoop, 10);
startTimer();
} else if (gameStatus === '游戏进行中') {
gameStatus = '游戏暂停中';
clearInterval(gameInterval);
clearInterval(timeInterval);
}
updateGameStatus();
}
// 对话4, 修复了startButtion按钮按下不会重新开始游戏的问题
document.getElementById('startButton').addEventListener('click', function () {
if (!isGameStarted) {
isGameStarted = true;
startLevel(level);
this.textContent = '重新开始游戏';
} else {
restartGame();
}
});
// 重新开始游戏
function restartGame() {
// 对话5,新增功能小球
powerBalls = []; // 清空功能小球
// 对话6
powerBallDropProbabilityOneLife = 10;
clearInterval(gameInterval);
clearInterval(timeInterval);
score = 0;
lives = 2;
level = 1;
bricksRowCount = 3;
powerBallProbabilityThreeLives = 10;
powerBallProbabilityTwoLives = 15;
document.getElementById('startButton').textContent = '重新开始游戏';
for (let i = 1; i <= 5; i++) {
document.getElementById(`level${i}-time`).textContent = `第${i}关: -分钟-秒`;
}
updateScore();
updateLives();
updateTimerDisplay();
startLevel(level);
}
// 初始化游戏
function initGame() {
paddle = new Paddle();
ball = new Ball();
initBricks();
document.getElementById('startButton').addEventListener('click', function () {
if (!isGameStarted) {
isGameStarted = true;
startLevel(level);
this.textContent = '重新开始游戏';
}
});
}
// 检查游戏是否继续
function checkGameContinue() {
if (lives === 0) {
gameStatus = '游戏结束, 请点击重新开始';
updateGameStatus();
clearInterval(gameInterval);
clearInterval(timeInterval);
isGameStarted = false;
alert('游戏结束');
}
}
// 页面加载完成时初始化游戏
window.onload = initGame;
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/itlantu/demo.git
[email protected]:itlantu/demo.git
itlantu
demo
demo
master

搜索帮助