는 내가 참석 해요 과정에 대한 간단한 메모리 게임을 만드는 데 필요한 나는이 함께했다 :숨기기 배경 이미지 인라인 스타일은
$(document).ready(function(){
// Set initial time to 0
var currentTime = 0;
// Set initial score to 0
var score = 0;
// Set initial attempt to 0
var attempts = 0;
// Placeholder
var timeHolder;
// Start the game when clicking the button #start
$('#start').on('click', init);
// Check if user hasn't clicked #start button yet
$('.board_cell').on('click.initialCheck', checkInitial);
function init() {
// Shuffle elements at beginning
shuffle();
// Handle click event and check if elements match
$('.board_cell').on('click', checkAccuracy).off('click.initialCheck');
$('#start').off('click', init);
$('#reset').on('click', reset);
// stop timer
clearInterval(timeHolder)
// Timer function will be called every 100ms
timeHolder = window.setInterval(timer, 100);
}
/*
* Main function to handle click events and do actions
* @checkAccuracy
*/
function checkAccuracy() {
var self = $(this),
allElements = $('.board_cell'),
// Url of background-image
bgUrl = self.children('.back').css('background-image'),
// Get relevant part (the image name) from the url
elementType = bgUrl.slice(bgUrl.lastIndexOf('/') + 1, bgUrl.lastIndexOf('.'));
// Flip the clicked element
self.addClass('flipped ' + elementType);
// Check if clicked element is already visible
if (self.hasClass('success')) {
showMessage('Das ist schon aufgedeckt ;)');
// Abort function by returning false
return false;
}
if($('.flipped').length >= 2) {
// Prevent clicking on other elements when 2 elements are already visible
allElements.off('click');
// Increase attempts
attempts++;
setAttempts();
}
if($('.'+elementType).length == 2) {
// If the same are visible
score++;
setScore();
showMessage(['That was a right one!!!', 'Now you got it!', 'Terrific!']);
toggleClasses('success', function(){
// Callback when toggleClasses has finsihed
if($('.success').length == allElements.length){
// If alle elements are visible
showMessage('Everything exposed, congrats!');
$('#overlay').fadeIn();
// Kill interval to prevent further increasing
clearInterval(timeHolder);
}
});
} else {
// If they are not the same
if($('.flipped').length == 2) {
toggleClasses();
showMessage(['Uhh that was wrong...', 'Are you drunk?', 'Try it again...', 'You better stop playing!',
'Seems like you need to train much more...', 'Annoying?', 'C\'mon!']);
}
}
}
/*
* Function to reset the game
*/
function reset() {
// turn elements and prevent clicking
$('.board_cell').removeClass('success flipped').off('click');
// hide overlay if visible
if($('#overlay').is(':visible')) {
$('#overlay').fadeOut();
}
// stop timer
clearInterval(timeHolder)
// set time to 0
currentTime = 0;
// set attempts to 0
attempts = 0;
setAttempts();
// set score to 0
score = 0;
setScore();
// hide message
showMessage('');
// set visible time to 0
$('#time span').text(currentTime);
// Check if user has clicked #start button
$('.board_cell').on('click.initialCheck', checkInitial);
$('#start').on('click', init);
}
/*
* Function to show a message
*/
function showMessage(msg) {
if(typeof msg == 'object') {
var randomNumber = Math.floor((Math.random()*msg.length)+1);
msg = msg[randomNumber-1];
}
$('#message span').html(msg);
}
/*
* Function to toggleClasses on clickable elements
*/
function toggleClasses(extraClass, callback) {
setTimeout(function(){
$('.flipped').removeClass().addClass('board_cell '+extraClass);
$('.board_cell').on('click', checkAccuracy);
if(typeof callback != 'undefined') {
callback();
}
}, 1000);
}
/*
* Function to increase score
*/
function setScore() {
$('#score span').text(score);
}
/*
* Function to increase attempts
*/
function setAttempts() {
$('#attempts span').text(attempts);
}
/*
* Function for timer
*/
function timer() {
currentTime = currentTime + 1;
$('#time span').text(currentTime/10);
}
/*
* Function for showing message when user hasn't clicked #start button yet
*/
function checkInitial() {
showMessage('You need to press the "Start Game" button to beginn');
}
/*
* Function for shuffling elements
*/
function shuffle() {
var elementsArray = [];
$('.back').each(function(index){
elementsArray.push($(this).css('background-image'))
});
elementsArray.sort(function() {return 0.5 - Math.random()})
$('.back').each(function(index){
$(this).css('background-image', elementsArray[index]);
});
}
});
숨겨진 이미지는 background-image
인라인 스타일을 통해 추가되고 각 시작/재설정시에 섞여 있지만 게임 중에 사용자가 속임수를 쓰는 것을 막을 수는 없습니다 (소스 코드를 보면 해결책을 즉시 알려줍니다).
소스 코드에서 background-image
값을 숨기는 방법이 있는지 알고 싶습니다. 나는 약간 base64
부호 매김을 시도했다 그러나 브라우저가 이것을 즉시 해석하기 때문에 전혀 봉사하지 않는다. 내가 가진 또 다른 아이디어는 background-image
을 php
으로 암호화하고, 마크 업에서 임의의 출력 (예 : 데이터베이스에 저장 됨)을 표시하고 요청을 통해 각 클릭 이벤트에서 php
파일로 통신하는 것입니다. 나는 이것이 작동하는지 모르겠지만 어쨌든 그것을 다루는 순회적인 방법처럼 보인다. ..
안전하고 효율적인 방법으로 이것을 해결하는 방법에 대한 제안이 있으십니까?
사용자가 웹 브라우저의 개발자 도구에 액세스 할 수있는 경우 클라이언트 측 JavaScript에서만 안전하게이 작업을 수행 할 수 없습니다. – Blender
나는 그것이 순수한 JavaScript 솔루션이되어야한다고 말하지 않았다 ... – enyce12
클릭하면 db에서 etrieve 이미지를 시도해보십시오 .. – Holybreath