0
最初のjavascriptファイルのgame.timesGuessedの値に応じて、2番目のjavascriptファイルの_this.velocity値を変更しようとしています。ゲームオブジェクトとその関数/変数を別のJavascriptファイルで使用するには
ゲームオブジェクトをグローバルにする必要がありますか、オブジェクトまたは特定の変数を他のファイルの関数に渡す方法はありますか?
ありがとうございます!
ゲームオブジェクトを含む私のapp.jsファイル。
(function(){
// Players
// Goals
// Obstacles
// Timer
// Number of
// Scoring System
// Points
// UI for game
// Game flow scroing -> points -> etc
// Hot or cold depending on closness to computerNumbers
// Sound!
game = {
init: function() {
console.log('init');
// Set Constants
this.timesGuessed = 0;
this.guessLimit = 6;
this.userAnswers = [];
this.computerNumbers = [];
this.userScore = 0;
// Set Point System
this.firstPlace = 100;
this.secondPlace = 75;
this.thirdPlace = 50;
this.fourthPlace = 25;
this.fifthPlace = 10;
this.sixthPlace = 5;
this.lastPlace = 0;
// Calls
this.cacheDom();
this.setName();
this.screenTransition();
this.bindEvents();
},
cacheDom: function() {
// Background
this.gameBackground = $('.large-header');
//Inputs
this.enterNameInput = $('#name');
// Number Placeholder
this.chosenNumber = $('.number-chosen');
this.totalPoints = $('.total-points');
// Screens
this.gameScreen = $('.game');
this.winScreen = $('.win-screen');
this.loseScreen = $('.lose-screen');
this.enterName = $('.enter-name');
this.leaderboardScreen = $('.leaderboard-screen');
// Number Pad
this.numbers = $('.numbers-to-guess');
// Points Awarded
this.pointsAwarded = $('.points-awarded');
// Buttons
this.playAgainBtn = $('.play-again');
this.newPlayerBtn = $('.new-player');
this.leaderboardBtn = $('.leaderboards');
this.goBackBtn = $('.go-back');
console.log(this.pointsAwarded);
// console.log(this.numbers);
},
setName: function() {
// get name from input
this.userName = $('#name').val();
// Set name to the UI
this.setNameOnGame(this.userName);
// Set object for to send to API
var user = {
name: this.userName,
score: 0,
};
// Send Object to API
$.ajax({
type: 'POST',
url: 'http://rest.learncode.academy/api/guessinggame/scores',
data: user,
success: function(data) {
console.log("User added!", data); //the new item is returned with an ID
game.userId = data.id;
return game.userId;
}
});
},
bindEvents: function() {
// console.log(this.numbers.find('li'));
this.numbers.find('li').on('click', this.setVariables);
this.playAgainBtn.on('click', this.restartGame);
this.newPlayerBtn.on('click', this.newPlayer);
this.leaderboardBtn.on('click', this.showLeaderboardScores);
this.goBackBtn.on('click', this.restartGame);
},
screenTransition: function() {
this.enterName.addClass('hidden');
this.gameScreen.removeClass('hidden');
},
setVariables: function() {
// console.log('set');
// console.log($(this));
console.log($(this).val());
// Sets the user answer
game.userAnswer = $(this).val();
// adds answer to answers array
game.userAnswers.push(game.userAnswer);
// Generates a random number between 1 and 10
game.randNumber = Math.floor(Math.random() * 10) + 1;
game.computerNumbers.push(game.randNumber);
// Checks the users number vs the random number
game.checkAnswer(game.userAnswer, game.randNumber);
// Animate Guessed Number Behind
game.animateChosenNumber(game.userAnswer);
},
setNameOnGame: function(userName) {
// document.getElementById('user-name').innerHTML = 'Player Name: ' + userName;
// document.getElementById('user').innerHTML = userName + ' Answers';
document.getElementById('display-name').innerHTML = 'Hi ' + userName + '!';
document.getElementById('number-guess-name').innerHTML = userName;
},
checkAnswer: function(userAnswer, randNumber) {
this.getDifference(userAnswer, randNumber);
// this.changeBackgroundColor(userAnswer, randNumber);
this.timesGuessed++;
this.render(userAnswer, randNumber, this.timesGuessed);
if (userAnswer > randNumber && this.timesGuessed <= this.guessLimit) {
// alert('You Guessed To High, Guess Again...');
document.getElementById('message').innerHTML = "You guessed to high";
// this.setVariables();
} else if (userAnswer < randNumber && this.timesGuessed <= this.guessLimit) {
// alert('You Guessed To Low, Guess Again...')
document.getElementById('message').innerHTML = "You guessed too low";
// this.setVariables();
} else if(userAnswer == randNumber && this.timesGuessed <= this.guessLimit) {
document.getElementById('message').innerHTML = "You Guessed Right!";
this.showWinScreen(this.timesGuessed);
} else if (this.timesGuessed > this.guessLimit) {
this.showLoseScreen(this.timesGuessed);
}
// this.score(this.timesGuessed);
//this.showAnswers();
// this.restartGame();
},
animateChosenNumber: function(userAnswer) {
console.log('animate');
this.chosenNumber.html(userAnswer);
this.chosenNumber.addClass('animate');
setTimeout(function(){
console.log('dis');
game.chosenNumber.removeClass('animate');
}, 800);
},
getDifference: function(userAnswer, randNumber) {
this.difference = Math.abs(userAnswer - randNumber);
console.log(this.difference);
this.changeBackgroundColor(this.difference);
},
changeBackgroundColor: function(difference) {
console.log('change');
if(difference <= 3) {
this.gameBackground.removeClass('normal');
this.gameBackground.removeClass('you-won');
this.gameBackground.removeClass('luke-warm');
this.gameBackground.removeClass('you-lost');
this.gameBackground.removeClass('ice-cold');
this.gameBackground.addClass('red-hot');
// Circle.velocity = Math.random()*20;
} else if(difference >= 4 && difference <= 6) {
this.gameBackground.removeClass('normal');
this.gameBackground.removeClass('you-won');
this.gameBackground.removeClass('you-lost');
this.gameBackground.removeClass('red-hot');
this.gameBackground.removeClass('ice-cold');
this.gameBackground.addClass('luke-warm');
// Circle.velocity = Math.random()*6;
} else if(difference >= 7) {
this.gameBackground.removeClass('normal');
this.gameBackground.removeClass('you-won');
this.gameBackground.removeClass('you-lost');
this.gameBackground.removeClass('red-hot');
this.gameBackground.removeClass('luke-warm');
this.gameBackground.addClass('ice-cold');
// Circle.velocity = Math.random()*1;
}
},
render: function(userAnswer, randNumber, timesGuessed) {
document.getElementById('guessed').innerHTML = timesGuessed;
document.getElementById('user-answer').innerHTML = userAnswer;
document.getElementById('computer-number').innerHTML = randNumber;
},
showAnswers: function() {
// Show all answers
for (var f = 0; f < this.computerNumbers.length; f++) {
this.listItem = document.createElement('TD');
this.listItemText = document.createTextNode(this.computerNumbers[f]);
this.listItem.appendChild(listItemText);
document.getElementById('computer-answers').appendChild(listItem);
}
// Show all guesses
for (var i = 0; i < this.userAnswers.length; i++) {
this.listItem = document.createElement('TD');
this.listItemText = document.createTextNode(this.userAnswers[i]);
this.listItem.appendChild(this.listItemText);
document.getElementById('user-answers').appendChild(this.listItem);
}
},
showWinScreen: function(timesGuessed) {
this.calculatePoints(timesGuessed);
this.gameScreen.addClass('hidden');
this.winScreen.removeClass('hidden');
this.gameBackground.removeClass('luke-warm');
this.gameBackground.removeClass('ice-cold');
this.gameBackground.removeClass('red-hot');
this.gameBackground.addClass('you-won');
this.totalPoints.html('Total Points <br/>' + game.userScore);
},
showLoseScreen: function(timesGuessed) {
this.calculatePoints(timesGuessed);
this.gameScreen.addClass('hidden');
this.loseScreen.removeClass('hidden');
this.gameBackground.removeClass('luke-warm');
this.gameBackground.removeClass('ice-cold');
this.gameBackground.removeClass('red-hot');
this.gameBackground.addClass('you-lost');
this.totalPoints.html('Total Points <br/>' + game.userScore);
},
calculatePoints: function(timesGuessed) {
console.log('calculate', timesGuessed);
if(timesGuessed == 1) {
this.pointsAwarded.html('You have earned<br/> + ' + this.firstPlace + 'pts');
this.userScore = this.userScore + this.firstPlace;
} else if (timesGuessed == 2) {
this.pointsAwarded.html('You have earned<br/> + ' + this.secondPlace + 'pts');
this.userScore = this.userScore + this.secondPlace;
} else if (timesGuessed == 3) {
this.pointsAwarded.html('You have earned<br/> + ' + this.thirdPlace + 'pts');
this.userScore = this.userScore + this.thirdPlace;
} else if (timesGuessed == 4) {
this.pointsAwarded.html('You have earned<br/> + ' + this.fourthPlace + 'pts');
this.userScore = this.userScore + this.fourthPlace;
} else if (timesGuessed == 5) {
this.pointsAwarded.html('You have earned<br/> + ' + this.fifthPlace + 'pts');
this.userScore = this.userScore + this.fifthPlace;
} else if (timesGuessed == 6) {
this.pointsAwarded.html('You have earned<br/> + ' + this.sixthPlace + 'pts');
this.userScore = this.userScore + this.sixthPlace;
} else if (timesGuessed > 6) {
this.pointsAwarded.html('You have earned<br/> + ' + this.lastPlace + 'pts');
this.userScore = this.userScore + this.lastPlace;
}
console.log('User Score: ', this.userScore);
this.updateData(this.userScore, this.userName, game.userId);
},
updateData: function(userScore, userName, userId) {
console.log('ID', userId);
console.log('Name', userName);
var user = {
name: userName,
score: userScore,
};
$.ajax({
type: 'PUT',
url: 'http://rest.learncode.academy/api/guessinggame/scores/' + userId,
data: user,
success: function(data) {
console.log("Score updated!", data); //the new item is returned with an ID
}
});
},
newPlayer: function() {
// Reset screens
game.enterName.removeClass('hidden');
game.loseScreen.addClass('hidden');
game.winScreen.addClass('hidden');
game.leaderboardScreen.addClass('hidden');
game.enterNameInput.val('');
// Reset Times Guessed
game.timesGuessed = 0;
console.log('new player!');
// Empty leaderboards list
$('.score-list').empty();
// Reset amount of times guessed on game to 0
document.getElementById('guessed').innerHTML = '';
},
showLeaderboardScores: function() {
// Set Screen
game.winScreen.addClass('hidden');
game.loseScreen.addClass('hidden');
game.leaderboardScreen.removeClass('hidden');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/guessinggame/scores',
success: function(data) {
// console.log("Scores!", data); //the new item is returned with an ID
// Sort Array to for highest score first
data.sort(function(a, b) {
return b.score - a.score;
});
console.log('Scores', data);
// Display the top 5 scores
var counter = 1;
$.each(data, function(i, score) {
$('.score-list').append('<li> Name: ' + score.name + '<br/>' + 'Score: ' + score.score);
if(counter == 5) {
return false;
} else {
counter++;
}
});
}
});
},
restartGame: function() {
// Reset screens
game.gameScreen.removeClass('hidden');
game.loseScreen.addClass('hidden');
game.winScreen.addClass('hidden');
game.leaderboardScreen.addClass('hidden');
// Reset LeaderBoards
$('.score-list').empty();
// Reset Times Guessed to 0
game.timesGuessed = 0;
document.getElementById('guessed').innerHTML = '';
}
};
})();
アニメーションbackgound app.jsで
(function() {
var width, height, largeHeader, canvas, ctx, circles, target, animateHeader = true;
// Main
initHeader();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {x: 0, y: height};
largeHeader = document.getElementById('large-header');
largeHeader.style.height = height+'px';
canvas = document.getElementById('demo-canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create particles
circles = [];
for(var x = 0; x < width*0.5; x++) {
var c = new Circle();
circles.push(c);
}
animate();
}
// Event handling
function addListeners() {
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height+'px';
canvas.width = width;
canvas.height = height;
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in circles) {
circles[i].draw();
}
}
requestAnimationFrame(animate);
}
// Canvas manipulation
function Circle() {
var _this = this;
// constructor
(function() {
_this.pos = {};
init();
// console.log(_this);
})();
function init() {
_this.pos.x = Math.random()*width;
_this.pos.y = height+Math.random()*100;
_this.alpha = 0.1+Math.random()*0.1;
_this.scale = 0.1+Math.random()*2;
_this.velocity = Math.random()*6;
}
this.draw = function() {
if(_this.alpha <= 0) {
init();
}
_this.pos.y -= _this.velocity;
_this.alpha -= 0.0005;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.scale*10, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(255,255,255,'+ _this.alpha+')';
ctx.fill();
};
}
})();
私のindex.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Animated Background Headers | Demo 2</title>
<meta name="description" content="Examples for creative website header animations using Canvas and JavaScript" />
<meta name="keywords" content="header, canvas, animated, creative, inspiration, javascript" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.1/foundation.min.css">
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" />
<link rel="stylesheet" type="text/css" href="dist/css/app.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:200,400,800|Clicker+Script' rel='stylesheet' type='text/css'>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div class="container demo-2">
<div class="content">
<div id="large-header" class="large-header normal">
<canvas id="demo-canvas"></canvas>
<div class="row enter-name">
<div class="large-12 columns">
<h1>Hot or Cold</h1>
<p>This is a simple guessing game.</p>
<h5>Please enter your name below</h5>
<input type="text" id="name" value="" placeholder="Budd Hole">
<input onclick="game.init()" type="submit" id="submit-name">
</div>
</div>
<div class="row game hidden">
<div class="large-6 small-12 small-centered columns">
<div class="number-chosen"></div>
<h1 id="display-name" data-id="" class="text-center"></h1>
<h4 class="text-center">Try to guess the number in less than 6 tries!</h4>
<hr>
<div class="user-answer small-6 large-6 columns text-center">
<h3 id="number-guess-name"></h3>
<span id="user-answer">0</span>
</div>
<div class="computer-number small-6 large-6 columns text-center">
<h3 id="computer-rand-number">Computer</h3>
<span id="computer-number">0</span>
</div>
<ul class="numbers-to-guess">
<li value="1">1</li>
<li value="2">2</li>
<li value="3">3</li>
<li value="4">4</li>
<li value="5">5</li>
<li value="6">6</li>
<li value="7">7</li>
<li value="8">8</li>
<li value="9">9</li>
<li value="10">10</li>
</ul>
<hr />
<h2>Times Guessed: <span id="guessed"></span></h2>
<hr />
<h1 id='message'></h1>
</div>
<!-- <div class="large-5 columns answers">
<table class="large-5 text-center columns">
<tr>
<th>Computer's Answers</th>
</tr>
<tr id="computer-answers">
</tr>
</table>
<table class="large-5 text-center columns">
<tr>
<th id="user">User's Answers</th>
</tr>
<tr id="user-answers">
</tr>
</table>
</div> -->
</div><!--- End Game --->
<div class="win-screen hidden text-center">
<h1>You Won!</h1>
<h1 class="total-points"></h1>
<span class="points-awarded"></span>
<br/>
<br/>
<button class="play-again">Play Again?</button>
<br/>
<br/>
<button class="new-player">New Player</button>
<br/>
<br/>
<button class="leaderboards">Scores</button>
</div>
<div class="lose-screen hidden text-center">
<h1>Sorry you lost!</h1>
<h1 class="total-points"></h1>
<span class="points-awarded"></span>
<br/>
<br/>
<button class="play-again">Play Again?</button>
<br/>
<br/>
<button class="new-player">New Player</button>
<br/>
<br/>
<button class="leaderboards">Leaderboards</button>
</div>
<div class="leaderboard-screen hidden">
<h1>Top 5 Scores</h1>
<ol class="score-list">
</ol>
<br/>
<br/>
<button class="play-again">Play Again?</button>
<br/>
<br/>
<button class="new-player">New Player</button>
</div>
</div>
</div>
</div>
</div><!-- /container -->
<script src="js/rAF.js"></script>
<script src="js/demo-2.js"></script>
<script src="js/app.js"></script>
</body>
</html>
ありがとうございました。自己実行機能でゲーム変数を持っているにもかかわらず、ありがとうございました。 –