- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试根据第一个 javascript 文件中 game.timesGuessed 的值更改第二个 javascript 文件中的 _this.velocity 值。
我是否必须使游戏对象全局化,或者是否有办法将对象或特定变量传递到其他文件的函数中?
提前谢谢您!
我的 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 = '';
}
};
})();
运行动画背景的我的文件
(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>
最佳答案
在 app.js 中,通过不为 game
变量指定 var
关键字,您已经将其作为全局对象提供,可供其他 js 文件访问.
在 index.html 中,app.js 脚本应先于需要使用 game
对象的其他脚本加载。
关于javascript - 如何在另一个 Javascript 文件中使用我的游戏对象及其函数/变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37107549/
我的一位教授给了我们一些考试练习题,其中一个问题类似于下面(伪代码): a.setColor(blue); b.setColor(red); a = b; b.setColor(purple); b
我似乎经常使用这个测试 if( object && object !== "null" && object !== "undefined" ){ doSomething(); } 在对象上,我
C# Object/object 是值类型还是引用类型? 我检查过它们可以保留引用,但是这个引用不能用于更改对象。 using System; class MyClass { public s
我在通过 AJAX 发送 json 时遇到问题。 var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Wil
当我尝试访问我的 View 中的对象 {{result}} 时(我从 Express js 服务器发送该对象),它只显示 [object][object]有谁知道如何获取 JSON 格式的值吗? 这是
我有不同类型的数据(可能是字符串、整数......)。这是一个简单的例子: public static void main(String[] args) { before("one"); }
嗨,我是 json 和 javascript 的新手。 我在这个网站找到了使用json数据作为表格的方法。 我很好奇为什么当我尝试使用 json 数据作为表时,我得到 [Object,Object]
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我听别人说 null == object 比 object == null check 例如: void m1(Object obj ) { if(null == obj) // Is thi
Match 对象 提供了对正则表达式匹配的只读属性的访问。 说明 Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。所有的
Class 对象 使用 Class 语句创建的对象。提供了对类的各种事件的访问。 说明 不允许显式地将一个变量声明为 Class 类型。在 VBScript 的上下文中,“类对象”一词指的是用
Folder 对象 提供对文件夹所有属性的访问。 说明 以下代码举例说明如何获得 Folder 对象并查看它的属性: Function ShowDateCreated(f
File 对象 提供对文件的所有属性的访问。 说明 以下代码举例说明如何获得一个 File 对象并查看它的属性: Function ShowDateCreated(fil
Drive 对象 提供对磁盘驱动器或网络共享的属性的访问。 说明 以下代码举例说明如何使用 Drive 对象访问驱动器的属性: Function ShowFreeSpac
FileSystemObject 对象 提供对计算机文件系统的访问。 说明 以下代码举例说明如何使用 FileSystemObject 对象返回一个 TextStream 对象,此对象可以被读
我是 javascript OOP 的新手,我认为这是一个相对基本的问题,但我无法通过搜索网络找到任何帮助。我是否遗漏了什么,或者我只是以错误的方式解决了这个问题? 这是我的示例代码: functio
我可以很容易地创造出很多不同的对象。例如像这样: var myObject = { myFunction: function () { return ""; } };
function Person(fname, lname) { this.fname = fname, this.lname = lname, this.getName = function()
任何人都可以向我解释为什么下面的代码给出 (object, Object) 吗? (console.log(dope) 给出了它应该的内容,但在 JSON.stringify 和 JSON.parse
我正在尝试完成散点图 exercise来自免费代码营。然而,我现在只自己学习了 d3 几个小时,在遵循 lynda.com 的教程后,我一直在尝试确定如何在工具提示中显示特定数据。 This code
我是一名优秀的程序员,十分优秀!