memory

Play Memory
Log | Files | Refs

memory.js (4764B)


      1 // UTILITIES
      2 // =========
      3 
      4 function toFullColor(col) {
      5 	// expecting either '#rrggbb' or '#rgb' and converting to '#rrggbb'
      6 
      7 	if (col.length == 7)
      8 		return col;
      9 	
     10 	let r = col[1],
     11 		g = col[2],
     12 		b = col[3];
     13 	
     14 	return '#' + r + r + g + g + b + b;
     15 }
     16 
     17 function shuffleArray(array) {
     18 	let currentIndex = array.length,
     19 		randomIndex;
     20 
     21 	// While there remain elements to shuffle.
     22 	while (currentIndex != 0) {
     23 
     24 		// Pick a remaining element.
     25 		randomIndex = Math.floor(Math.random() * currentIndex);
     26 		currentIndex--;
     27 	
     28 		// And swap it with the current element.
     29 		[ array[currentIndex], array[randomIndex] ] = [ array[randomIndex], array[currentIndex] ];
     30 	}
     31 
     32 	return array;
     33 }
     34 
     35 // CONSTANTS
     36 // =========
     37 
     38 const DOG_API = "https://dog.ceo/api/breeds/image/random";
     39 const CAT_API = "https://cataas.com/api/cats?limit=";
     40 const CAT_API_PREFIX = "https://cataas.com/cat/";
     41 
     42 const BOARD_SIZE = 36;
     43 
     44 
     45 // GLOBALS
     46 // =======
     47 
     48 let buttons, done, openButton, pairs, time, interval =null;
     49 
     50 // HELPERS
     51 // =======
     52 
     53 function getButton(btn) {
     54 	return buttons[btn.id];
     55 }
     56 
     57 function makeBoard(res) {
     58 	let board = document.getElementById("game_board");
     59 	
     60 	time = 0;
     61 	
     62 	if (interval) 
     63 		clearInterval(interval);
     64 
     65 	interval = setInterval(() => 
     66 		document.getElementById('game_time').innerText = `Time: ${time++}sec`
     67 	, 1000);
     68 
     69 	let i = 0;
     70 	for (let img of shuffleArray(res.concat(res))) {
     71 		var btn = document.createElement("div");
     72 		btn.setAttribute('area-label', 'card');
     73 		btn.classList.add('card');
     74 	
     75 		btn.id = 'card-' + i;
     76 		btn.addEventListener('click', onCardClick);
     77 		
     78 		board.appendChild(btn);
     79 			
     80 		buttons['card-' + i] = {
     81 			state: 'closed',
     82 			img: img,
     83 		};
     84 		i++;
     85 	}
     86 }
     87 
     88 
     89 // HANDLERS
     90 // ========
     91 
     92 function onSelect() {
     93 	let board = document.getElementById("game_board");
     94 	board.innerHTML = '';
     95 	
     96 	buttons = {};
     97 	openButton = null;
     98 	done = [];
     99 	pairs = 0;
    100 	
    101 	let select = document.getElementById('picture-select');
    102 	switch (select.value) {
    103 	case 'dog':
    104 		let promises = [];
    105 		for (let i = 0; i < BOARD_SIZE / 2; i++) {
    106 			promises.push(fetch(DOG_API).then(res => res.json()).then(res => res.message));
    107 		}
    108 		Promise.all(promises).then(makeBoard);
    109 		break;
    110 	case 'cat':
    111 		fetch(CAT_API + (BOARD_SIZE / 2), { mode: 'cors' }).then(res => res.json()).then(res =>
    112 			makeBoard(res.map(x => CAT_API_PREFIX + x._id))
    113 		);
    114 		break;
    115 	default: 
    116 		return;	
    117 	}
    118 }
    119 
    120 function menu(){
    121 	let m = document.getElementById('menu');
    122 	if(m.style.display == 'flex'){
    123 		m.style.display = 'none';
    124 	}else{
    125 		m.style.display = 'flex';
    126 	}
    127 	
    128 	console.log(m.getPropertyValue());
    129 }
    130 
    131 function onCardClick(evt) {
    132 	if (done.includes(this))
    133 	return;
    134 
    135 	this.innerHTML = `<img width=100% height=100% src='${getButton(this).img}' />`;
    136 
    137 	if (openButton) {
    138 		if (this != openButton && getButton(openButton).img == getButton(this).img) {
    139 			done.push(openButton);
    140 			done.push(this);
    141 			pairs++;
    142 			document.getElementById('pairs').innerHTML = pairs;
    143 	
    144 			this.classList.add('done');
    145 			openButton.classList.add('done');
    146 			
    147 			if (pairs >= BOARD_SIZE / 2) {
    148 			alert("GEFELICITEERD!!!");
    149 			}
    150 		}
    151 		openButton.classList.remove('clicked');
    152 		openButton = null;
    153 	} else {
    154 		openButton = this;
    155 		this.classList.add('clicked');
    156 	}
    157 }
    158 
    159 function colorChange() {
    160 	let color = document.getElementById("closed_card").value;
    161 //	let fcolor = document.getElementById("found_card").value;
    162 	
    163 	for (let x of document.getElementsByClassName("card"))
    164 		x.style.backgroundColor = color;
    165 
    166 //	for (let x of document.getElementsByClassName("done"))
    167 //		x.style.backgroundColor = fcolor;
    168 }
    169 
    170 function updateTop() {
    171 	let list = document.getElementById("top_5");
    172 	list.innerHTML = '';
    173 	
    174 	let players = callBackend('GET', 'scores').then(res =>
    175 		res.sort((a, b) => b.score - a.score).slice(0, 5).forEach(({ username, score }) => {
    176 			let entry = document.createElement('li');
    177 			entry.innerText = `${username} (${score})`;
    178 			list.appendChild(entry);
    179 		})
    180 	);	
    181 }
    182 
    183 function updateLogin() {
    184 	let span = document.getElementById('login');
    185 	
    186 	let user = getUser().then(user => {
    187 		if (!user) {
    188 			window.location.href = 'login.html?m=restricted';
    189 		}
    190 	
    191 		span.innerText = `Logged in as ${user.name}`;
    192 	});
    193 }
    194 
    195 function updatePref() {
    196 	getUser().then(user =>
    197 		callBackend('GET', `api/player/${user.id}/preferences`).then(({ color_found, color_closed, preferred_api }) => {
    198 			if (!preferred_api)
    199 				preferred_api = 'none';
    200 			if (!color_found)
    201 				color_found = '#00ff00';
    202 			if (!color_closed)
    203 				color_closed = '#ffff00';
    204 	
    205 			document.getElementById('found_card').value = toFullColor(color_found);
    206 			document.getElementById('closed_card').value = toFullColor(color_closed);
    207 			document.getElementById('picture-select').value = preferred_api;
    208 
    209 			onSelect();
    210 			setTimeout(colorChange, 500);
    211 		})
    212 	);	
    213 }
    214 
    215 updateTop();
    216 updateLogin();
    217 updatePref();