Как сделать стартовое меню для Javascript игры? - PullRequest
2 голосов
/ 10 марта 2020

Хорошо, это будет долго, пожалуйста, потерпите меня (я новичок в Javascript программировании, кстати)

Итак, наша задача в школе - получить игру с открытым исходным кодом и изменить ее

один, который я нашел, хорош, это танковый стрелок, но дело в том, что игра сразу же начинается после открытия индекса. html Я хотел добавить стартовое меню / кнопку и иметь опцию для 2,3 или 4 игроков

Вот код в индексе. html, я поставлю рядом с ним свои наблюдения

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8" />
    <title>Neon Tankz</title>
    <link rel="stylesheet" href="style.css">

    <script src="p5.min.js"></script>
    <script src="p5.play.js"></script>
    <script src="Extensions/array-extensions.js"></script>
    <script src="Extensions/vector-extensions.js"></script>

    <script src="Entities/sprite-entity.js"></script>

    <script src="Entities/Map/tile.js"></script>
    <script src="Entities/Map/grid.js"></script>
    <script src="Entities/Map/game-map.js"></script>

    <script src="Entities/Scoreboard/score.js"></script>
    <script src="Entities/Scoreboard/scoreboard.js"></script>

    <script src="Entities/bullet.js"></script>
    <script src="Entities/cannon.js"></script>
    <script src="Entities/player.js"></script>

    <script src="main.js"></script>
</head>

<body style="background-color: black;display: flex; justify-content: center;">
    <div>

        <input type="button" style="position: absolute; top: 0; left: 0;" onclick="location.reload(true);"
            value="Reload">
        <button onclick="stopMusic()"> Staph Moosic</button>
        <button id="mylink" onclick="myclick()">
            Load
        </button>
    </div>
</body>

</html>

Вы можете быть озадачены load, reload и Staph Moosic

  • Загрузить = - это кнопка тестирования для запуска или загрузки игры,

  • Обновить = перезагрузить игру или обновить sh браузер,

  • Staph Moosi c = останавливает музыку c (я добавил музыку c в основной. js)

Вот наблюдения, которые я заметил, и то, что я сделал: main. js имеет функции preload() и load(), и это файл, в котором я могу изменить no. удаление игроков оставит индекс пустым

Итак, я предположил, что с кучей загруженных скриптов, main. js необходим для запуска? Поэтому я попытался сделать еще одну копию main. js (main2. js), но этот файл был изменен только для двух игроков и изменил предыдущий на

<script src= "main2.js">

, и все работает, игра началась только с двумя игроками.

На данный момент, я не знаю, какое решение я могу сделать, кроме создания нескольких копий индекса. html (переименуйте каждый из них), и у каждого есть разные основные. js в зависимости от того, сколько игроков и имеют индекс. html до html, который ссылается на эти несколько htmls

Я знаю, что это довольно странное решение, есть ли другие решения?

РЕДАКТИРОВАТЬ Это основной код. js


/*Im trying to add more maps value1 and value2 are for the maps,
Currently there are two maps (map1.txt and map2.txt)
It doesn't do anything much, don't mind this lool
*/

var value1 = "1";
var value2 = "2";

//This is for the background music
var myMusic;
//This code is to make the myMusic loop
myMusic = new Audio("Images/bgMusic.wav");
myMusic.addEventListener('ended', function () {
    this.currentTime = 0;
    this.play();
}, false);
//This code is to play music
myMusic.play();


function start() {
    decision = true;
}
const config = {

    screen: {
        width: 1000,
        height: 500,

    },
    players: [],

    groups: {},
    bullets: {
        deathTimer: 4000
    },
    mapTile: {
        dimension: 20
        //this changes the size of the map previously 22
    }
};


function preload() {


    loadStrings("Entities/Map/map" + value2 + ".txt", mapText => config.map = new GameMap(mapText));

    for (const group of ["players", "bullets", "tiles"]) {
        config.groups[group] = new Group();
    }

    function load() {

        function removePlayer() {
            config.players.remove(this);

            if (config.players.length === 1) {
                let resetBoard = false;

                for (const score in config.scoreboard.scores) {
                    if (config.scoreboard.scores[score].value > 8) {
                        config.scoreboard.reset();
                        resetBoard = true;
                        break;
                    }
                }

                if (!resetBoard) {
                    config.scoreboard.scores[config.players[0].name].increment();


                }
                //in my observation, the player score which is below will only increment if that player stays
                //removing this, will not change the score no matter who survives

                for (const player of config.players) {
                    player.destroy();

                }

                config.players.length = 0; //idk what this do but setting it to other value makes the screen hang after one wins
                load();
            }
        }
         //the no. of players can be determined
         //When you remove this config.players.push...
         //A player will be removed with no errors
        config.players.push(new Player("Player1", "Happy", {
            forward: 87, // W
            backward: 83, // S
            rotateLeft: 65, // A
            rotateRight: 68, // D
            shoot: 81 // Q      this is the fire button for the player 1
        }, removePlayer));

        config.players.push(new Player("Player2", "Neutral", {
            forward: 73, // I
            backward: 75, // K
            rotateLeft: 74, // J
            rotateRight: 76, // L
            shoot: 85 // U      // this is the fire button for the player 2
        }, removePlayer));

        config.players.push(new Player("Player3", "Smiley", {
            forward: 38, // Up arrow
            backward: 40, // Down arrow
            rotateLeft: 37, // Left arrow
            rotateRight: 39, // Right arrow
            shoot: 191 // Forward slash ('/')   this is the fire button for the player 3
        }, removePlayer));

        config.players.push(new Player("Player4", "Neo", {
            //the name "smiley" refers to the image that is provided
            forward: 84, // T
            backward: 71, // G
            rotateLeft: 70, // F
            rotateRight: 72, // H
            shoot: 82 // R   this is the fire button for the player 4
        }, removePlayer));
        //always take note when changing the controls, the program follows the ascii dec of UPPERCASE letters
    }

    load();

    config.scoreboard = new Scoreboard(config.players);
}

function setup() {
    createCanvas(config.screen.width, config.screen.height + 100);
    //the 100 was added for the position of scoreboard?

}


function draw() {
    clear();

    config.map.update();
    config.map.draw();

    config.groups.bullets.draw();
    //deleting this will make a bullet invisible

    config.groups.players.overlap(config.groups.bullets, function (player, bullet) {
        var mySound;
        mySound = new Audio("Images/boxHit.wav");
        mySound.play();
        player.spriteEntity.destroy();
        bullet.spriteEntity.destroy();

    });

    for (const player of config.players) {
        player.update(config.players);
        player.draw();
    }

    config.scoreboard.draw();
}

function keyPressed(event) {
    for (const player of config.players) {
        player.keyPressed(event.keyCode);
    }
}

//This function is to stop music
//it doesnt totally work, because when a player gets hit, then the play will go on

function stopMusic() {

    myMusic.pause();
}

function playMusic() {

    myMusic.play();
}

Должен ли я добавить все файлы js? Это может сделать вопрос длинным, я новичок в этом переполнении стека

Об этом индексе. html становится пустым Я извиняюсь за недопонимание, файл индекса не go белый и все, что я имел в виду, это быть таким

Это игра с <script src="main.js"></script> This is the game with <script src = ">

Это игра без <script src="main.js"></script> And this is when there is no <script src =">

Извините за недопонимание У меня есть уровень 0 в навыках общения xD

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...