123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302 |
- <template>
- <div class="game-container">
- <div id="gameCanvas" class="game-canvas"></div>
- <!-- 游戏启动界面 -->
- <div v-if="currentScene === 'start'" class="gamestart">
- <img v-if="currentScene === 'start'" src="/static/images/football/game_start.jpg" class="start_bg" />
- <div class="btn rule" @click="showRules = true">查看规则</div>
- <div class="btn start" @click="startGame">开始游戏</div>
- <!-- 规则弹窗 -->
- <div v-if="showRules" class="ruleshadow">
- <div class="rulebox">
- <span class="x_rulebox" @click="showRules = false"></span>
- <h3>操作方法:</h3>
- <p>手指拖动控制人物带球奔跑的方向和速度。</p>
- <h3>道具说明:</h3>
- <div class="daoju">
- <div class="daoju_item">
- <span class="daoju_1"></span>
- <p>每收集一个,生命值+1;触碰障碍物,生命可再复活。</p>
- </div>
- <div class="daoju_item">
- <span class="daoju_2"></span>
- <p>每收集一个,能力值+1;扫除面前一切障碍,加速前进。</p>
- </div>
- <div class="daoju_item">
- <span class="daoju_3"></span>
- <p>触碰锥桶,生命值-1;成功绕过一次分数+1。</p>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- 规则说明 -->
- <div v-if="currentScene === 'rule'" class="zhiyin">
- <div class="btn start" @click="continueGame">继续游戏</div>
- </div>
- <!-- 倒计时 -->
- <div v-if="currentScene === 'countdown'" class="daoju">
- <div class="daojishibox">
- <div class="daojishinum">{{ countdownNum }}</div>
- </div>
- </div>
- <!-- 游戏结束 -->
- <div v-if="currentScene === 'gameover'" class="gameend">
- <div v-if="currentScene === 'gameover'" class="game_fenshu">
- <span>{{ score }}</span>分
- </div>
- <div class="chenghao">恭喜你获得称号<p>{{ getTitle(score) }}</p>
- </div>
- <div class="game_ogain" @click="restartGame">再次游戏</div>
- </div>
- </div>
- </template>
- <script setup>
- import { ref, onMounted, watch } from 'vue';
- import Phaser from 'phaser';
- // 游戏状态管理
- const currentScene = ref('start');
- const showRules = ref(false);
- const countdownNum = ref(3);
- const score = ref(0);
- const game = ref(null);
- const gameConfig = ref(null);
- let scoreListener = null; // 存储事件监听器引用
- // 游戏常量
- const width = document.documentElement.clientWidth;
- const height = document.documentElement.clientHeight;
- const GAME_WIDTH = width;
- const GAME_HEIGHT = height;
- // 游戏资源
- const gameAssets = {
- images: [
- { key: 'gameStart', url: 'static/images/football/game_start.jpg' },
- { key: 'grass', url: 'static/images/football/Caopi.png' },
- { key: 'playerShoot', url: 'static/images/football/QiuyuanShooting.png' },
- { key: 'pile', url: 'static/images/football/Pile.png' },
- { key: 'jersey', url: 'static/images/football/Jersey.png' },
- { key: 'broom', url: 'static/images/football/Broom.png' },
- { key: 'goalkeeper', url: 'static/images/football/Goalkeeper.png' },
- { key: 'goal', url: 'static/images/football/Goal.png' },
- { key: 'ball', url: 'static/images/football/Ball.png' },
- { key: 'line', url: 'static/images/football/Line.png' },
- { key: 'line2', url: 'static/images/football/Line2.png' },
- { key: 'goalBackground', url: 'static/images/football/GoalBackGround.png' },
- { key: 'gameOver', url: 'static/images/football/gameover.png' }
- ],
- spritesheets: [
- {
- key: 'playerAnim',
- url: 'static/images/football/Qiuyuan.png',
- frameWidth: 92.5,
- frameHeight: 92.5
- },
- {
- key: 'ballAnim',
- url: 'static/images/football/Ball.png',
- frameWidth: 31,
- frameHeight: 31
- },
- {
- key: 'goalkeeperAnim',
- url: 'static/images/football/Goalkeeper.png',
- frameWidth: 55,
- frameHeight: 56
- },
- {
- key: 'playerCollision',
- url: 'static/images/football/QiuyuanCollision.png',
- frameWidth: 92.5,
- frameHeight: 92.5
- },
- {
- key: 'playerSuper',
- url: 'static/images/football/QiuyuanSuper.png',
- frameWidth: 92.5,
- frameHeight: 92.5
- },
- ]
- };
- // 初始化Phaser游戏
- const initGame = () => {
- // 游戏配置
- gameConfig.value = {
- type: Phaser.AUTO,
- width: GAME_WIDTH,
- height: GAME_HEIGHT,
- parent: 'gameCanvas',
- physics: {
- default: 'arcade',
- arcade: {
- gravity: { y: 0 },
- debug: false
- }
- },
- scene: [
- PreloaderScene,
- GameScene
- ]
- };
- game.value = new Phaser.Game(gameConfig.value);
- // 关键:使用局部变量存储事件监听器,便于后续清理
- scoreListener = (newScore) => {
- score.value = newScore;
- };
- // 添加事件监听
- if (game.value && game.value.events) {
- game.value.events.on('scoreChanged', scoreListener);
- }
- game.value.events.on('gameOver', () => {
- currentScene.value = 'gameover';
- });
- };
- // 预加载场景
- class PreloaderScene extends Phaser.Scene {
- constructor() {
- super('PreloaderScene');
- }
- preload() {
- // 加载图片资源
- gameAssets.images.forEach(asset => {
- this.load.image(asset.key, asset.url);
- });
- // 加载精灵表
- gameAssets.spritesheets.forEach(asset => {
- this.load.spritesheet(asset.key, asset.url, {
- frameWidth: asset.frameWidth,
- frameHeight: asset.frameHeight
- });
- });
- // 显示加载进度
- const progressBar = this.add.graphics();
- const progressBox = this.add.graphics();
- progressBox.fillStyle(0x222222, 0.8);
- progressBox.fillRect(GAME_WIDTH / 2 - 160, GAME_HEIGHT / 2 - 25, 320, 50);
- const loadingText = this.make.text({
- x: GAME_WIDTH / 2,
- y: GAME_HEIGHT / 2 - 50,
- text: 'Loading...',
- style: {
- font: '20px monospace',
- fill: '#ffffff'
- }
- }).setOrigin(0.5, 0.5);
- const percentText = this.make.text({
- x: GAME_WIDTH / 2,
- y: GAME_HEIGHT / 2,
- text: '0%',
- style: {
- font: '18px monospace',
- fill: '#ffffff'
- }
- }).setOrigin(0.5, 0.5);
- this.load.on('progress', (value) => {
- percentText.setText(`${Math.round(value * 100)}%`);
- progressBar.clear();
- progressBar.fillStyle(0xffffff, 1);
- progressBar.fillRect(GAME_WIDTH / 2 - 150, GAME_HEIGHT / 2 - 15, 300 * value, 30);
- });
- this.load.on('complete', () => {
- progressBar.destroy();
- progressBox.destroy();
- loadingText.destroy();
- percentText.destroy();
- });
- }
- create() {
- // 初始化动画
- this.initAnimations();
- // 切换到游戏场景
- this.scene.start('GameScene');
- }
- initAnimations() {
- // 球员动画
- this.anims.create({
- key: 'playerLeft',
- frames: [
- { key: 'playerAnim', frame: 0 },
- { key: 'playerAnim', frame: 2 },
- { key: 'playerAnim', frame: 4 },
- { key: 'playerAnim', frame: 6 }
- ],
- frameRate: 10,
- repeat: -1
- });
- this.anims.create({
- key: 'playerRight',
- frames: [
- { key: 'playerAnim', frame: 1 },
- { key: 'playerAnim', frame: 3 },
- { key: 'playerAnim', frame: 5 },
- { key: 'playerAnim', frame: 7 }
- ],
- frameRate: 10,
- repeat: -1
- });
- // 足球动画
- this.anims.create({
- key: 'ballAnim',
- frames: this.anims.generateFrameNumbers('ballAnim', { start: 0, end: 1 }),
- frameRate: 5,
- repeat: -1
- });
- // 守门员动画
- this.anims.create({
- key: 'goalkeeperAnim',
- frames: this.anims.generateFrameNumbers('goalkeeperAnim', { start: 0, end: 1 }),
- frameRate: 3,
- repeat: -1
- });
- }
- }
- // 游戏主场景
- class GameScene extends Phaser.Scene {
- constructor() {
- super('GameScene');
- this.player = null;
- this.score = 0;
- this.lives = 3;
- this.maxLives = 5;
- this.speed = 6;
- this.acceleration = 1.9;
- this.level = 1;
- this.obstacles = [];
- this.powerUps = [];
- this.isSuper = false;
- this.gameActive = false;
- this.timer = null;
- this.isShooting = false; // 新增:初始化射门状态
- this.obstacleTimer = null; // 新增:初始化障碍物计时器
- this.obstacleEvent = null;
- this.jerseyEvent = null;
- this.broomEvent = null;
- }
- create() {
- // 创建背景
- this.createBackground();
- // 创建玩家
- this.createPlayer();
- // 创建计分板
- this.createHUD();
- // 输入控制
- this.initControls();
- // 游戏事件
- this.events.on('resume', () => {
- this.gameActive = true;
- });
- // 等待开始游戏信号
- this.gameActive = false;
- }
- createBackground() {
- // 创建滚动背景
- this.background = this.add.tileSprite(0, 0, GAME_WIDTH, GAME_HEIGHT, 'grass');
- this.background.setOrigin(0, 0);
- }
- createPlayer() {
- // 创建玩家
- this.player = this.physics.add.sprite(GAME_WIDTH / 2, GAME_HEIGHT - 100, 'playerAnim');
- this.player.setCollideWorldBounds(true);
- this.player.setScale(0.8);
- this.player.lives = this.lives;
- this.player.setDepth(9);
- }
- createHUD() {
- // 分数显示
- this.scoreText = this.add.text(10, 10, `分数: ${this.score}`, {
- fontSize: '16px',
- fill: '#ffffff',
- backgroundColor: 'rgba(0,0,0,0.5)',
- padding: { x: 5, y: 2 }
- });
- this.scoreText.setDepth(10);
- // 生命值显示
- this.livesText = this.add.text(GAME_WIDTH - 80, 10, `生命: ${this.lives}`, {
- fontSize: '16px',
- fill: '#ffffff',
- backgroundColor: 'rgba(0,0,0,0.5)',
- padding: { x: 5, y: 2 }
- });
- this.livesText.setDepth(10);
- }
- initControls() {
- // 键盘控制
- this.cursors = this.input.keyboard.createCursorKeys();
- // 触摸控制(添加垂直移动)
- this.input.on('pointermove', (pointer) => {
- if (this.gameActive && pointer.isDown && !this.isShooting) {
- // 水平移动
- this.player.x = Phaser.Math.Clamp(pointer.x, this.player.width / 2, GAME_WIDTH - this.player.width / 2);
- // 垂直移动(限制范围)
- this.player.y = Phaser.Math.Clamp(
- pointer.y,
- 0, // 最小Y值
- GAME_HEIGHT// 最大Y值
- );
- }
- });
- }
- startGame() {
- // 重置核心状态
- this.gameActive = true;
- this.score = 0;
- this.lives = 3; // 重置生命值
- this.maxLives = 5;
- this.speed = 6; // 重置基础速度
- this.acceleration = 1.9; // 重置加速度
- this.level = 1; // 重置等级
- this.isSuper = false;
- this.isShooting = false;
- this.obstacles = [];
- this.powerUps = [];
- // 更新UI显示
- this.livesText.setText(`生命: ${this.lives}`);
- this.updateScore();
- // 清理旧定时器(双重保险)
- if (this.timer) this.timer.remove();
- if (this.obstacleEvent) this.obstacleEvent.remove();
- if (this.jerseyEvent) this.jerseyEvent.remove();
- if (this.broomEvent) this.broomEvent.remove();
- // 重新开始生成障碍物和计时
- this.startSpawning();
- this.timer = this.time.addEvent({
- delay: 200,
- callback: () => {
- this.score++;
- this.updateScore();
- if (this.score % 200 === 0) {
- this.levelUp();
- }
- },
- loop: true
- });
- }
- startSpawning() {
- // 先移除旧事件(强化清除逻辑)
- if (this.obstacleEvent) {
- this.obstacleEvent.remove();
- this.obstacleEvent = null; // 置空引用
- }
- if (this.jerseyEvent) {
- this.jerseyEvent.remove();
- this.jerseyEvent = null; // 置空引用
- }
- if (this.broomEvent) {
- this.broomEvent.remove();
- this.broomEvent = null; // 置空引用
- }
- // 重新创建事件(使用安全的场景上下文)
- this.obstacleEvent = this.time.addEvent({
- delay: 1000 / this.level,
- callback: () => { if (this.gameActive) this.spawnObstacle(); },
- loop: true
- });
- this.jerseyEvent = this.time.addEvent({
- delay: 5000,
- callback: () => { if (this.gameActive) this.spawnPowerUp('jersey'); },
- loop: true
- });
- this.broomEvent = this.time.addEvent({
- delay: 8000,
- callback: () => { if (this.gameActive) this.spawnPowerUp('broom'); },
- loop: true
- });
- // 新增:立即生成第一个障碍物,确保倒计时结束后立即出现
- this.spawnObstacle();
- }
- spawnObstacle() {
- const x = Phaser.Math.Between(30, GAME_WIDTH - 30);
- const obstacle = this.physics.add.sprite(x, -50, 'pile');
- obstacle.setScale(0.7);
- // 降低速度(从原来的this.speed * this.acceleration * 10调整为)
- obstacle.setVelocityY(this.speed * this.acceleration * 5); // 速度减半
- obstacle.setDepth(8);
- obstacle.type = 'pile';
- // 碰撞检测
- this.physics.add.overlap(this.player, obstacle, this.handleObstacleCollision, null, this);
- this.obstacles.push(obstacle);
- // 替换原计时器代码
- const event = this.time.addEvent({ // 用变量接收事件引用
- delay: 100,
- loop: true,
- callback: () => {
- if (obstacle.active) {
- if (obstacle.y > GAME_HEIGHT + obstacle.height) {
- obstacle.destroy();
- this.obstacles = this.obstacles.filter(o => o !== obstacle);
- this.score++;
- this.updateScore();
- this.time.removeEvent(event); // 移除当前事件
- }
- } else {
- this.time.removeEvent(event);
- }
- }
- });
- }
- spawnPowerUp(type) {
- const x = Phaser.Math.Between(30, GAME_WIDTH - 30);
- let powerUp;
- if (type === 'jersey') {
- powerUp = this.physics.add.sprite(x, -50, 'jersey');
- powerUp.type = 'jersey';
- } else if (type === 'broom') {
- powerUp = this.physics.add.sprite(x, -50, 'broom');
- powerUp.type = 'broom';
- }
- powerUp.setScale(0.7);
- // 降低道具速度(从原来的this.speed * this.acceleration * 8调整为)
- powerUp.setVelocityY(this.speed * this.acceleration * 4); // 速度降低
- powerUp.setDepth(8);
- // 碰撞检测
- this.physics.add.overlap(this.player, powerUp, this.handlePowerUpCollision, null, this);
- this.powerUps.push(powerUp);
- // 延长道具生命周期
- this.time.addEvent({
- delay: 15000,
- callback: () => {
- if (powerUp.active) {
- powerUp.destroy();
- this.powerUps = this.powerUps.filter(p => p !== powerUp);
- }
- }
- });
- }
- handleObstacleCollision(player, obstacle) {
- if (this.isSuper) {
- // 超级状态下直接摧毁障碍物
- obstacle.destroy();
- this.obstacles = this.obstacles.filter(o => o !== obstacle);
- return;
- }
- // 扣除生命值
- player.lives--;
- this.lives = player.lives;
- this.livesText.setText(`生命: ${this.lives}`);
- // 显示受伤效果
- player.setTexture('playerCollision');
- this.time.addEvent({
- delay: 618,
- callback: () => {
- player.setTexture('playerAnim');
- }
- });
- // 销毁障碍物
- obstacle.destroy();
- this.obstacles = this.obstacles.filter(o => o !== obstacle);
- // 检查游戏是否结束
- if (player.lives <= 0) {
- this.gameOver();
- }
- }
- handlePowerUpCollision(player, powerUp) {
- if (powerUp.type === 'jersey') {
- // 增加生命值
- if (player.lives < this.maxLives) {
- player.lives++;
- this.lives = player.lives;
- this.livesText.setText(`生命: ${this.lives}`);
- }
- } else if (powerUp.type === 'broom') {
- // 激活超级状态
- this.activateSuperMode();
- }
- // 销毁道具
- powerUp.destroy();
- this.powerUps = this.powerUps.filter(p => p !== powerUp);
- }
- activateSuperMode() {
- this.isSuper = true;
- this.player.setTexture('playerSuper');
- this.acceleration = 10;
- // 3秒后结束超级状态
- this.time.addEvent({
- delay: 3000,
- callback: () => {
- this.isSuper = false;
- this.player.setTexture('playerAnim');
- this.acceleration = 1.9 + (this.level - 1) * 0.5;
- }
- });
- }
- levelUp() {
- this.level++;
- this.acceleration += 0.5;
- // 显示升级提示
- const levelUpText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, `Level ${this.level}!`, {
- fontSize: '32px',
- fill: '#ffff00',
- stroke: '#000000',
- strokeThickness: 2
- }).setOrigin(0.5);
- levelUpText.setDepth(10);
- this.time.addEvent({
- delay: 1000,
- callback: () => {
- levelUpText.destroy();
- }
- });
- }
- updateScore() {
- try {
- // 关键:检查DOM元素和场景是否存在
- if (!this.scoreText || !this.scene) return;
- this.scoreText.setText(`分数: ${this.score}`);
- // 触发全局分数更新事件(添加安全检查)
- if (this.game && this.game.events) {
- this.game.events.emit('scoreChanged', this.score);
- }
- // 每200分触发一次射门环节
- if (this.score % 200 === 0 && this.score > 0 && !this.isShooting) {
- this.enterShootingMode();
- }
- } catch (error) {
- console.error('updateScore 错误:', error);
- }
- }
- enterShootingMode() {
- this.gameActive = false;
- this.isShooting = true;
- // 关键修复:重置键盘状态,清除所有按键的按下状态
- this.input.keyboard.resetKeys();
- // 额外保险:手动清除方向键状态
- this.cursors.left.isDown = false;
- this.cursors.right.isDown = false;
- this.cursors.up.isDown = false;
- this.cursors.down.isDown = false;
- // 停止所有生成事件
- if (this.obstacleEvent) this.obstacleEvent.remove();
- if (this.jerseyEvent) this.jerseyEvent.remove();
- if (this.broomEvent) this.broomEvent.remove();
- // 清除现有障碍物和道具
- this.obstacles.forEach(obs => obs.destroy());
- this.obstacles = [];
- this.powerUps.forEach(p => p.destroy());
- this.powerUps = [];
- // 创建射门场景背景
- this.background.setTexture('goalBackground');
- // 创建球门
- this.goal = this.physics.add.sprite(GAME_WIDTH / 2, 100, 'goal');
- this.goal.setScale(0.8);
- this.goal.setImmovable(true);
- this.goal.setDepth(5);
- // 创建守门员
- this.goalkeeper = this.physics.add.sprite(GAME_WIDTH / 2, 150, 'goalkeeperAnim');
- this.goalkeeper.setScale(0.9);
- this.goalkeeper.setImmovable(true);
- this.goalkeeper.anims.play('goalkeeperAnim', true);
- this.goalkeeper.setDepth(7);
- // 让守门员左右移动
- this.tweens.add({
- targets: this.goalkeeper,
- x: [GAME_WIDTH / 2 - 50, GAME_WIDTH / 2 + 50],
- duration: 2000,
- ease: 'Sine.inOut',
- repeat: -1,
- yoyo: true
- });
- // 调整球员位置(准备射门)
- this.player.setPosition(GAME_WIDTH / 2, GAME_HEIGHT - 100);
- this.player.setTexture('playerShoot');
- // 关键修复:停止玩家所有移动
- this.player.setVelocity(0);
- // 创建足球(修复:让足球跟随玩家位置)
- this.ball = this.physics.add.sprite(this.player.x, this.player.y - 50, 'ballAnim');
- this.ball.setScale(0.8);
- this.ball.anims.play('ballAnim', true);
- this.ball.setDepth(8);
- // 显示射门提示
- this.shootHint = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT - 50, '点击或按空格键射门', {
- fontSize: '16px',
- fill: '#ffffff',
- backgroundColor: 'rgba(0,0,0,0.5)',
- padding: { x: 5, y: 2 }
- }).setOrigin(0.5);
- this.shootHint.setDepth(10);
- // 射门控制
- this.input.keyboard.on('keydown-SPACE', this.shootBall, this);
- this.input.on('pointerdown', this.shootBall, this);
- }
- shootBall() {
- if (!this.isShooting) return;
- // 禁用输入
- this.input.keyboard.off('keydown-SPACE', this.shootBall, this);
- this.input.off('pointerdown', this.shootBall, this);
- // 移除射门模式下的左右移动监听(如果添加了)
- this.input.keyboard.off('keydown-LEFT');
- this.input.keyboard.off('keydown-RIGHT');
- if (this.shootHint) {
- this.shootHint.destroy();
- this.shootHint = null;
- }
- // 计算龙门网内的目标位置
- const goalNetY = this.goal.y + 30;
- const goalNetX = this.player.x;
- // 创建射门动画
- const ballTween = this.tweens.add({
- targets: this.ball,
- x: goalNetX,
- y: goalNetY,
- duration: 1000,
- ease: 'Power1',
- onComplete: () => {
- if (!this.ball || !this.ball.active) return;
- // 判断是否成功
- const isSuccess = Phaser.Math.Between(0, 1) === 1;
- if (isSuccess) {
- this.score += 3;
- this.updateScore();
- this.ball.setDepth(6.5); // 成功:足球在守门员后方(网内)
- this.successShoot();
- } else {
- this.ball.setDepth(7.5); // 失败:足球在守门员前方
- this.failShoot();
- }
- ballTween.remove();
- }
- });
- }
- // 射门成功处理
- successShoot() {
- this.isShooting = false;
- // 显示成功提示
- const successText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, '射门成功!+3分', {
- fontSize: '24px',
- fill: '#0f0',
- stroke: '#000000',
- strokeThickness: 2
- }).setOrigin(0.5);
- successText.setDepth(10);
- // 2秒后返回奔跑场景
- this.time.addEvent({
- delay: 2000,
- callback: () => {
- if (successText && successText.active) {
- successText.destroy();
- }
- this.ball.destroy();
- this.resetToRunningScene();
- },
- callbackScope: this
- });
- }
- // 射门失败处理
- failShoot() {
- this.isShooting = false;
- // 关键修复1:解除足球的物理控制
- this.ball.setVelocity(0);
- this.ball.setImmovable(true);
- this.physics.world.disable(this.ball); // 完全禁用物理引擎对足球的控制
- // 关键修复2:调整足球位置到守门员前方固定位置,不跟随移动
- this.ball.setPosition(
- this.goalkeeper.x,
- this.goalkeeper.y + 20 // 固定在守门员前方20px处
- );
- // 显示失败提示
- const failText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, '射门失败!', {
- fontSize: '24px',
- fill: '#f00',
- stroke: '#000000',
- strokeThickness: 2
- }).setOrigin(0.5);
- failText.setDepth(10);
- // 2秒后返回奔跑场景
- this.time.addEvent({
- delay: 2000,
- callback: () => {
- if (failText && failText.active) {
- failText.destroy();
- }
- this.ball.destroy(); // 确保足球被销毁
- this.resetToRunningScene();
- },
- callbackScope: this
- });
- }
- // 重置为奔跑场景
- resetToRunningScene() {
- this.clearScene();
- // 重置玩家状态
- if (this.player) {
- this.player.setTexture('playerAnim');
- this.player.setPosition(GAME_WIDTH / 2, GAME_HEIGHT - 100);
- this.player.setVelocity(0);
- }
- // 恢复背景和游戏状态
- if (this.background) this.background.setTexture('grass');
- this.gameActive = true;
- this.isShooting = false;
- // 关键:确保所有射门场景元素被彻底清理
- if (this.ball) {
- this.ball.destroy();
- this.ball = null; // 显式置空引用
- }
- // 重新开始生成障碍物
- this.startSpawning();
- }
- gameOver() {
- this.gameActive = false;
- // 清理所有定时事件
- if (this.timer) this.timer.remove();
- if (this.obstacleEvent) this.obstacleEvent.remove();
- if (this.jerseyEvent) this.jerseyEvent.remove();
- if (this.broomEvent) this.broomEvent.remove();
- // 彻底清理计时相关资源
- if (this.timer) {
- this.timer.destroy(); // 销毁计时器(比remove()更彻底)
- this.timer = null; // 置空引用,防止残留
- }
- // 显示游戏结束画面
- this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'gameOver').setOrigin(0.5);
- // 触发游戏结束事件
- this.time.addEvent({
- delay: 2000,
- callback: () => {
- this.game.events.emit('gameOver');
- }
- });
- }
- update() {
- if (!this.gameActive) return;
- // 关键修复:射门模式下直接返回,不执行任何移动逻辑
- if (this.isShooting) return;
- // 玩家移动逻辑(原有代码保持不变)
- if (this.player && this.player.active) {
- if (this.cursors.left.isDown) {
- this.player.setVelocityX(-200);
- if (this.player.anims.currentAnim?.key !== 'playerLeft' && !this.player.anims.paused) {
- this.player.anims.play('playerLeft', true);
- }
- } else if (this.cursors.right.isDown) {
- this.player.setVelocityX(200);
- if (this.player.anims.currentAnim?.key !== 'playerRight' && !this.player.anims.paused) {
- this.player.anims.play('playerRight', true);
- }
- } else if (this.cursors.up.isDown) {
- this.player.setVelocityY(-200);
- if (this.player.anims.currentAnim?.key === 'playerLeft' && !this.player.anims.paused) {
- this.player.anims.play('playerLeft', true);
- } else if (this.player.anims.currentAnim?.key === 'playerRight' && !this.player.anims.paused) {
- this.player.anims.play('playerRight', true);
- } else {
- this.player.anims.play('playerLeft', true);
- }
- } else if (this.cursors.down.isDown) {
- this.player.setVelocityY(200);
- if (this.player.anims.currentAnim?.key === 'playerLeft' && !this.player.anims.paused) {
- this.player.anims.play('playerLeft', true);
- } else if (this.player.anims.currentAnim?.key === 'playerRight' && !this.player.anims.paused) {
- this.player.anims.play('playerRight', true);
- } else {
- this.player.anims.play('playerLeft', true);
- }
- } else {
- this.player.setVelocityX(0);
- this.player.setVelocityY(0);
- this.player.anims.stop();
- }
- }
- }
- // 添加 clearScene 方法
- clearScene() {
- // 清理射门场景的元素
- if (this.goal) this.goal.destroy();
- if (this.goalkeeper) this.goalkeeper.destroy();
- if (this.ball) {
- this.ball.destroy();
- this.ball = null; // 显式置空
- }
- if (this.shootHint) this.shootHint.destroy();
- // 清理所有障碍物和道具
- this.obstacles.forEach(obs => obs.destroy());
- this.powerUps.forEach(p => p.destroy());
- this.obstacles = [];
- this.powerUps = [];
- // 停止所有动画
- this.tweens.killAll();
- }
- // 新增:场景销毁时清理资源
- destroy() {
- // 清理所有定时器
- if (this.timer) this.timer.remove();
- if (this.obstacleEvent) this.obstacleEvent.remove();
- if (this.jerseyEvent) this.jerseyEvent.remove();
- if (this.broomEvent) this.broomEvent.remove();
- // 移除输入监听
- this.input.keyboard.off('keydown-SPACE', this.shootBall, this);
- this.input.off('pointerdown', this.shootBall, this);
- // 清理所有游戏对象
- this.obstacles.forEach(obs => obs.destroy());
- this.powerUps.forEach(p => p.destroy());
- if (this.goal) this.goal.destroy();
- if (this.goalkeeper) this.goalkeeper.destroy();
- if (this.ball) this.ball.destroy();
- // 调用父类销毁方法
- super.destroy();
- }
- }
- // 游戏控制函数
- const startGame = () => {
- currentScene.value = 'countdown';
- // 倒计时
- currentScene.value = 'countdown';
- let count = 3;
- const countdownInterval = setInterval(() => {
- count--;
- countdownNum.value = count;
- if (count <= 0) {
- clearInterval(countdownInterval);
- currentScene.value = 'game';
- // 通知游戏开始
- if (game.value) {
- const gameScene = game.value.scene.getScene('GameScene');
- if (gameScene) {
- gameScene.startGame();
- }
- }
- }
- }, 1000);
- };
- const continueGame = () => {
- startGame();
- };
- const restartGame = () => {
- // 1. 彻底销毁旧游戏实例(含场景和资源)
- if (game.value) {
- // 先停止游戏逻辑
- const gameScene = game.value.scene.getScene('GameScene');
- if (gameScene) {
- gameScene.gameActive = false;
- }
- // 销毁游戏实例(强制清理DOM)
- game.value.destroy(true);
- game.value = null; // 置空引用,避免残留
- }
- // 2. 重置全局状态
- score.value = 0;
- currentScene.value = 'start';
- countdownNum.value = 3;
- // 3. 延迟初始化新游戏(确保旧实例完全销毁)
- setTimeout(() => {
- initGame();
- }, 100); // 短暂延迟确保DOM清理完成
- };
- const getTitle = (score) => {
- if (score < 50) return '足球新手';
- if (score < 100) return '业余球员';
- if (score < 200) return '专业选手';
- if (score < 300) return '足球明星';
- return '足球传奇';
- };
- // 组件挂载时初始化游戏
- onMounted(() => {
- initGame();
- });
- // 监听场景变化
- watch(currentScene, (newVal) => {
- if (newVal === 'game' && game.value) {
- const gameScene = game.value.scene.getScene('GameScene');
- if (gameScene) {
- gameScene.scene.resume();
- }
- }
- });
- // 组件卸载时清理事件监听
- onUnmounted(() => {
- if (game.value && game.value.events && scoreListener) {
- game.value.events.off('scoreChanged', scoreListener);
- }
- });
- </script>
- <style scoped>
- .game-container {
- position: relative;
- width: 100%;
- height: 100vh;
- margin: 0 auto;
- overflow: hidden;
- }
- .game-canvas {
- width: 100%;
- height: 100%;
- background-color: #000;
- }
- .gamestart {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 100;
- }
- .start_bg {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .btn {
- width: 80%;
- height: 40px;
- border-radius: 5px;
- text-align: center;
- line-height: 40px;
- color: #333;
- box-shadow: 0 5px 0px #07942c;
- box-shadow: 0 5px 0px rgba(0, 0, 0, 0.17);
- position: absolute;
- left: 50%;
- margin: 0 0 0 -40%;
- font-size: 18px;
- }
- .rule {
- background: #fff;
- bottom: 100px;
- }
- .start {
- background: #ffff00;
- bottom: 40px;
- }
- .ruleshadow {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- z-index: 102;
- display: flex;
- justify-content: center;
- align-items: center;
- font-size: 18px;
- }
- .rulebox {
- width: 280px;
- background-color: white;
- border-radius: 10px;
- padding: 20px;
- position: relative;
- opacity: 0;
- animation: fadeIn 0.5s forwards;
- }
- @keyframes fadeIn {
- to {
- opacity: 1;
- }
- }
- .x_rulebox {
- position: absolute;
- top: 10px;
- right: 10px;
- width: 20px;
- height: 20px;
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23000'%3E%3Cpath d='M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'/%3E%3C/svg%3E");
- cursor: pointer;
- }
- .daoju {
- margin-top: 15px;
- }
- .daoju_item {
- display: flex;
- align-items: center;
- margin-bottom: 10px;
- }
- .daoju_1,
- .daoju_2,
- .daoju_3 {
- display: inline-block;
- width: 60px;
- height: 60px;
- margin-right: 10px;
- background-size: contain;
- background-repeat: no-repeat;
- flex-shrink: 0;
- }
- .daoju_1 {
- background-image: url("/static/images/football/Jersey.png");
- }
- .daoju_2 {
- background-image: url("/static/images/football/Broom.png");
- }
- .daoju_3 {
- background-image: url("/static/images/football/Pile.png");
- }
- .zhiyin {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- z-index: 100;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .daojishi {
- position: absolute;
- width: 100%;
- top: 0;
- bottom: 0;
- display: none;
- z-index: 11;
- background: url(daojishu_bg.png) repeat left top;
- background-size: 100%;
- }
- .daojishiline {
- width: 100%;
- height: 95px;
- position: absolute;
- top: 109px;
- left: 0;
- background: #ffe400;
- z-index: 1;
- }
- .daojishibox {
- width: 180px;
- height: 180px;
- position: absolute;
- left: 50%;
- top: 71px;
- margin: 0 0 0 -90px;
- background: url(daojishibox.png) no-repeat left top;
- background-size: 100%;
- z-index: 2;
- }
- .daojishipangzi {
- width: 111px;
- height: 102px;
- position: absolute;
- left: 50%;
- bottom: 50px;
- margin: 0 0 0 -55px;
- background: url(daojishipangzi.png) no-repeat left top;
- background-size: 100%;
- z-index: -1;
- }
- .daojishinum {
- width: 100%;
- text-align: center;
- font-size: 80px;
- color: #FFFFFF;
- padding: 70px 0 0 0;
- line-height: normal;
- }
- @keyframes countDown {
- 0% {
- transform: scale(3);
- opacity: 0;
- }
- 50% {
- transform: scale(1.2);
- opacity: 1;
- }
- 100% {
- transform: scale(1);
- opacity: 1;
- }
- }
- .gameend {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- z-index: 100;
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- color: white;
- }
- .game_fenshu {
- font-size: 36px;
- margin-bottom: 20px;
- }
- .chenghao {
- font-size: 24px;
- margin-bottom: 30px;
- text-align: center;
- }
- .game_ogain,
- .game_chakan,
- .game_share {
- width: 150px;
- height: 40px;
- line-height: 40px;
- text-align: center;
- background-color: #f00;
- border-radius: 20px;
- margin-bottom: 10px;
- cursor: pointer;
- font-size: 18px;
- }
- .game_chakan {
- background-color: #666;
- }
- .game_share {
- background-color: #008000;
- }
- </style>
|