Как передать локальную переменную в глобальную функцию, чтобы ее можно было прочитать из внешнего файла Index.html - PullRequest
0 голосов
/ 12 декабря 2018

Я построил игру, используя инфраструктуру Phaser.По окончании игры высокий балл игроков записывается в переменную (this.inputScore).Чтобы отправить свой высокий балл на сервер, игрок нажимает кнопку, которая переводит их на страницу Index.html, где есть форма, которую они заполняют. Чтобы избежать мошенничества, я хочу, чтобы переменная высокого балла была передана из файла JavaScript игры(Game.js) для ввода значения в форме в качестве значения только для чтения.Я создал функцию (assignValue) внутри файла Game.js для выполнения этой задачи, но из-за ее объема я не могу получить функцию, которая будет прочитана файлом Index.html.Когда я размещаю функцию в верхней части скрипта Game.js (глобально), Index.html читает функцию и выполняет ее соответствующим образом (но с жестко заданным значением для целей тестирования.) Как я могу получить файл Index.htmlпрочитать мою функцию assignValue () и передать this.inputScore входному значению в Index.html?

Файл Game.js:

  //INDEX.HTML READS THIS assignValue function AND APPLIES IT BECAUSE IT 
  //IS IN GLOBAL SCOPE. BUT I NEED THE VALUE TO BE A VARIABLE TAKEN FROM A 
  //FUNCTION INSIDE THE GAME CODE. SEE GAME CODE BELOW:

  function assignValue() {

    document.getElementById("inputScore").value = 127;

};



//GAME CODE

var CrystalRunner = CrystalRunner || {};

CrystalRunner.GameState = {

init: function() {
  //...code here
  }, 


create: function() {
 //...code here
  },  


 update: function() {  
//..code here
//check if the player needs to die
      if(this.player.top >= this.game.world.height && this.counter === 0 || this.player.left <= 0 && this.counter === 0) {
         this.gameOver();
      }
  },  


 gameOver: function(){
    this.game.time.events.stop();
    this.player.body.enable = false;
    //..code here

    this.updateHighscore();

    //..code here

   },


  updateHighscore: function(){
    this.highScore = +localStorage.getItem('highScore');


    if(this.highScore < this.myScore){
            this.highScore = this.myScore;
            this.inputScore = this.highScore;


            this.congrats = this.game.add.sprite(this.game.world.centerX-193, this.game.world.centerY-20, 'congrats');
            this.congrats.inputEnabled = true;
            this.congrats.fixedToCamera = true;

            this.submitScoreButton = this.game.add.sprite(this.game.world.centerX-135, this.game.world.centerY+100, 'submitScoreButton');
            this.submitScoreButton.inputEnabled = true;
            this.submitScoreButton.fixedToCamera = true;

            this.submitScoreButton.events.onInputUp.add(function() {

                    window.location.href = "index1.php";

              }, this);

      }


      localStorage.setItem('highScore', this.highScore);
  },

//THE FUNCTION BELOW IS NOT BEING READ BECAUSE OF SCOPE. HOW TO I MAKE INDEX.HTML READ IT?
  assignValue: function() {

                document.getElementById("inputScore").value = this.inputScore;

  },


};

Файл Index1.html:

<?php
require_once 'dbconnect.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Crystal Candy Game Login</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<link href="css/style.css" rel="stylesheet">

<script type='text/javascript' src='js/jquery-2.2.3.min.js'></script>

<script>
        $(window).on('load', function() { 
        $('#status').fadeOut();      
        $('#preloader').delay(350).fadeOut('slow'); 
        $('body').delay(350).css({'overflow':'visible'});
        })
</script>

</head>

<body onload="assignValue()" class="bg">


<div id="preloader">
    <div id="status">&nbsp;</div>
</div>


<div class="wrapper">


    <div class="texte">
        <header>
        <h1>SUBMIT YOUR SCORE</h1>
        <img id="logo" src="assets/images/logo.png">
        </header>

        <p>Submit your highscore and you could stand a chance to win a 
        prize!</p>
    </div>


    <div id="main">


      <form id="form-style" method="post" action="crystalhandle.php" 
        autocomplete="off">

        <div class="form-group"> 
          <label class="header-text"><span>First Name</span></label>
          <input class="form-control" type="text" id="name" name="username" 
            placeholder="Name" title="Please enter your Firstname" 
          required="">
        </div>

        <div class="form-group"> 
         <label class="header-text"><span>Surname</span></label>
         <input class="form-control" type="text" id="name" name="surname" 
         placeholder="Surname" title="Please enter your Lastname" 
         required="">
        </div>  

        <div class="form-group">    
         <label class="header-text"><span>Email</span></label>
         <input class="form-control" type="email" id="email" name="email" 
         placeholder="Mail@example.com" title="Please enter a Valid Email 
         Address" required="">
        </div>

        <div class="form-group"> 
         <label class="header-text"><span>Phone</span></label>
         <input class="form-control" type="tel" id="name" name="phone" 
         placeholder="Phone" title="Please enter your Phone No" required="">
        </div>

        <div class="form-group"> 
        <label class="header-text"><span>Score</span></label>
        <input class="form-control" type="tel" id="inputScore" name="score" 
        value="" readonly>
        </div>
        <!-- I need the above input value to have the variable from 
        assignValue inserted into it-->

        <div class="w3ls-btn form-group">   
        <div class="wthreesubmitaits">
        <input type="submit" name="signup" id="reg" class="button" 
        id="next1" value="Send" style="font-family: sans-serif; font-size: 
        17px; font-weight: bold;"
        </div>  
        </div> 


    </form>
  </div>
 </div>

 <script type="text/javascript" src="js/phaser.min.js"></script>

  <!--the below js file is where assignValue() is defined:-->
 <script type="text/javascript" src="js/states/Game.js"/></script>

</body>


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