In this tutorial we will use a database of images previously scraped from a Reddit JSON document to create a simple game based on an idea of guessing which of two images has a better upvotes score (karma).
The database is generated by the Reddit Image Scraper tool and consists of 250 data records of book covers fetched from the Terrible Book Covers subreddit. More about this tool including its source code you can find in the previous part of this tutorial – How to create an HTML5 Reddit’s Image Scraper using Phaser!
Here is the game prototype. In each of ten rounds try to guess which of two book covers is more terrible by tapping on it.
Here is the almost fully commented source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
/***********************************************************************************/ var game; // define all App states var STATE_TITLE_SCREEN = 1; var STATE_GAME_INIT = 2; var STATE_NEXT_ROUND = 3; var STATE_LOAD_IMAGES = 4; var STATE_LOAD_COMPLETE = 5; var STATE_GAME_PLAY = 6; var STATE_SHOW_RESULT = 7; var STATE_GAME_OVER = 8; var MAX_ROUNDS = 10; // number of rounds for playing one game var MAX_TIME_MSEC = 10000; // a starting period of time in miliseconds for playing one round var MAX_COVER_HEIGHT = 360; // maximum height of the cover image that can be displayed var APP_TITLE = 'WHAT IS THE MOST\nTERRIBLE COVER\n\n'+ 'by Srdjan Susnic\n\n'+ 'www.askforgametask.com\n'+ 'version 0.1 (c) 2015\n\n'+ '----------------------------------------------\n\n'; /***********************************************************************************/ window.onload = function () { // Google Chrome and Firefox are blocking cross-domain image in WebGL (because of a security issue). // To bypass this use Phaser.CANVAS! game = new Phaser.Game(480, 800, Phaser.CANVAS, 'game'); game.state.add('GamePlay', GamePlay); game.state.start('GamePlay'); }; /***********************************************************************************/ var GamePlay = function(game){}; GamePlay.prototype = { preload : function(){ game.load.json('database', 'assets/database.json'); game.load.image('imgTrue', 'assets/img_true.png'); game.load.image('imgFalse', 'assets/img_false.png'); game.load.image('imgVotes', 'assets/img_votes.png'); game.load.image('imgTimer', 'assets/img_timer.png'); game.load.image('imgLoadMsg', 'assets/img_loadmsg.png'); game.load.bitmapFont('fonts', 'assets/fonts.png', 'assets/fonts.fnt'); }, create : function(){ // set maximum number of pointers allowed to be active at any one time game.input.maxPointers = 1; // set scale options game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignVertically = true; game.scale.pageAlignHorizontally = true; game.scale.setScreenSize(true); // set stage options game.stage.backgroundColor = "#000"; // put all data from the json input file in array aImages = game.cache.getJSON('database').data; // create a text for displaying info txtInfo = game.add.bitmapText(game.width/2, 50, 'fonts', '', 28); txtInfo.align = "center"; drawTextInfo( APP_TITLE+ 'INSTRUCTIONS\n\n'+ 'You get a pair of book covers\nwith their hidden votes from\nreddit.com/r/TerribleBookCovers\n\n'+ 'Go through '+MAX_ROUNDS+' rounds and\ntap on more terrible cover\nas fast as possible!\n\n\n'+ 'Tap to play...\n\n\n' ); // create a sprite for displaying 1. cover image sprCover1 = game.add.sprite(game.width/2, 10+MAX_COVER_HEIGHT/2, ''); sprCover1.anchor.setTo(0.5, 0.5); sprCover1.inputEnabled = true; sprCover1.events.onInputDown.add(onClickCover1, this); // create a sprite for displaying background of the 1. cover votes sprVotes1 = game.add.sprite(sprCover1.x, sprCover1.y, 'imgVotes'); sprVotes1.anchor.setTo(0.5, 0.5); sprVotes1.scale.set(0); // create a text for displaying total number of the 1. cover votes txtVotes1 = game.add.bitmapText(sprCover1.x, sprCover1.y, 'fonts', '', 36); txtVotes1.anchor.setTo(0.5, 0.5); txtVotes1.scale.set(0); // create a sprite for displaying 2. cover image sprCover2 = game.add.sprite(game.width/2, 20+MAX_COVER_HEIGHT*3/2, ''); sprCover2.anchor.setTo(0.5, 0.5); sprCover2.inputEnabled = true; sprCover2.events.onInputDown.add(onClickCover2, this); // create a sprite for displaying background of the 2. cover votes sprVotes2 = game.add.sprite(sprCover2.x, sprCover2.y, 'imgVotes'); sprVotes2.anchor.setTo(0.5, 0.5); sprVotes2.scale.set(0); // create a text for displaying total number of the 2. cover votes txtVotes2 = game.add.bitmapText(sprCover2.x, sprCover2.y, 'fonts', '', 36); txtVotes2.anchor.setTo(0.5, 0.5); txtVotes2.scale.set(0); // create a sprite for displaying true/false icon as a result of clicking on a cover sprResult = game.add.sprite(game.width/2, (game.height-50)/2, 'imgTrue'); sprResult.anchor.setTo(0.5, 0.5); sprResult.scale.set(0); // create a sprite for displaying timer sprTimer = game.add.sprite(0, game.height, 'imgTimer'); sprTimer.anchor.setTo(0, 1); sprTimer.kill(); // create a text for displaying score txtScore = game.add.bitmapText(game.width/2, 777, 'fonts', '', 40); txtScore.anchor.setTo(0.5, 0.5); // create a sprite for displaying message about loading next images sprLoadMsg = game.add.sprite(game.width/2, (game.height-50)/2, 'imgLoadMsg'); sprLoadMsg.anchor.setTo(0.5, 0.5); sprLoadMsg.kill(); // create timer timer = game.time.create(false); timer.start(0); // set initial App state state = STATE_TITLE_SCREEN; }, update : function(){ switch(state){ case STATE_TITLE_SCREEN: // show the title screen until mouse down is pressed to start the game if (isMouseDown()) state = STATE_GAME_INIT; break; case STATE_GAME_INIT: // init new game score = 0; hits = 0; round = 0; txtInfo.kill(); // hide info txtScore.text = '0'; // show score state = STATE_NEXT_ROUND; break; case STATE_NEXT_ROUND: // init next round round++; sprLoadMsg.revive(); // show loading message // change alternately key names of new cover images from round to round key_cover1 = (round % 2 == 0) ? 'imgCover1a' : 'imgCover1b'; key_cover2 = (round % 2 == 0) ? 'imgCover2a' : 'imgCover2b'; state = STATE_LOAD_IMAGES; break; case STATE_LOAD_IMAGES: // start to load a pair of images with a difference of 15 votes at least idx1 = game.rnd.integerInRange(0, aImages.length-1); do { idx2 = game.rnd.integerInRange(0, aImages.length-1); } while (Math.abs(aImages[idx2].score - aImages[idx1].score) < 15) txtVotes1.setText(aImages[idx1].score); txtVotes2.setText(aImages[idx2].score); var loader = new Phaser.Loader(game); loader.image(key_cover1, checkUrl(aImages[idx1].url)); loader.image(key_cover2, checkUrl(aImages[idx2].url)); isLoadCompleted = false; isErrorCover1 = false; isErrorCover2 = false; loadAttempt = 1; loader.onFileError.add(onFileError, this); loader.onLoadComplete.addOnce(onLoadComplete, this); loader.start(); state = STATE_LOAD_COMPLETE; break; case STATE_LOAD_COMPLETE: // wait on loading images to be completed and then check status of the loaded images if (isLoadCompleted){ if (isErrorCover1 || isErrorCover2){ // if there are file errors... if (loadAttempt == 1){ // if this was the first loading attempt then try to load cover thumb instead of bad image var loader = new Phaser.Loader(game); if (isErrorCover1) loader.image(key_cover1, checkUrl(aImages[idx1].icon)); if (isErrorCover2) loader.image(key_cover2, checkUrl(aImages[idx2].icon)); isLoadCompleted = false; isErrorCover1 = false; isErrorCover2 = false; loadAttempt = 2; loader.onFileError.add(onFileError, this); loader.onLoadComplete.addOnce(onLoadComplete, this); loader.start(); } else { // if this was the second loading attempt then go back to start loading another pair of images state = STATE_LOAD_IMAGES; } } else { // else if everything is OK with loaded images then show it! // update covers with new images updateCover(sprCover1, key_cover1); updateCover(sprCover2, key_cover2); sprLoadMsg.kill(); // hide loading message // reset timer and show it time_start = timer.ms; sprTimer.height = game.height; sprTimer.revive(); state = STATE_GAME_PLAY; } } break; case STATE_GAME_PLAY: // play the game listening mouse click on a image cover drawTimer(); // update timer break; case STATE_SHOW_RESULT: if (tweenResult.isRunning){ // if tween of result sprite is running then scale votes objects equally to it sprVotes1.scale = txtVotes1.scale = sprResult.scale; sprVotes2.scale = txtVotes2.scale = sprResult.scale; } else if (round == MAX_ROUNDS) { // else if this is the last round then init the game over screen sprCover1.kill(); // hide cover 1 sprCover2.kill(); // hide cover 1 sprTimer.kill(); // hide timer txtScore.text = ''; // hide score drawTextInfo( APP_TITLE+ '\nGAME OVER\n\n\n\n'+ 'Score: ' + score + '\n\n'+ 'Hits: ' + hits + ' of ' + MAX_ROUNDS + '\n\n\n\n'+ 'Tap to play again!' ); txtInfo.revive(); // show info state = STATE_GAME_OVER; } else { // else go to init the next round. state = STATE_NEXT_ROUND; } break; case STATE_GAME_OVER: // show the game over screen until mouse down is pressed to play again if (isMouseDown()) state = STATE_GAME_INIT; break; } } } // Sets isLoadCompleted flag to true when loading is completed. function onLoadComplete(){ isLoadCompleted = true; } //Sets error flag to true for any image that cannot be loaded. function onFileError(key_name){ if (key_name == key_cover1) isErrorCover1 = true; if (key_name == key_cover2) isErrorCover2 = true; } //Triggers mouse click on the 1. cover image but just if we are in Game Play State. function onClickCover1(){ if (state == STATE_GAME_PLAY){ checkVotes(aImages[idx1].score, aImages[idx2].score); } } // Triggers mouse click on the 2. cover image but just if we are in Game Play State. function onClickCover2(){ if (state == STATE_GAME_PLAY){ checkVotes(aImages[idx2].score, aImages[idx1].score); } } // Returns true on mouse click anywhere inside the screen. // (used for starting new game when there is displayed title or game over screen) function isMouseDown(){ return game.input.mousePointer.isDown || game.input.pointer1.isDown; } // Compares number of votes of both cover images, updates score and shows the result of guessing. function checkVotes(votes1, votes2){ var points = MAX_TIME_MSEC - (timer.ms-time_start); if (points<0) points=1; if (votes1 > votes2){ // hit: increase score sprResult.loadTexture('imgTrue'); score += points; hits++; } else { // miss: decrease score sprResult.loadTexture('imgFalse'); score -= (points/2) >> 0; } txtScore.text = '' + score; tweenResult = game.add.tween(sprResult.scale); tweenResult.to({x: 1, y: 1}, 1, Phaser.Easing.Linear.None, false); tweenResult.to({x: 1, y: 1}, 1500, Phaser.Easing.Linear.None, false); tweenResult.to({x: 0, y: 0}, 100, Phaser.Easing.Linear.None, true); state = STATE_SHOW_RESULT; } // Ensures that url is not an empty strings, otherwise loader can freeze the game! function checkUrl(strUrl){ return strUrl.length === 0 ? 'empty_url' : strUrl; } // Updates cover sprite with a new image and scales it to an appropriate dimension. function updateCover(sprite_cover, key_name){ sprite_cover.loadTexture(key_name); sprite_cover.scale.setTo(1); sprite_cover.scale.setTo(MAX_COVER_HEIGHT / sprite_cover.height); sprite_cover.revive(); } // Draws timer bar updating its height. function drawTimer(){ var ratio = 1 - (timer.ms-time_start) / MAX_TIME_MSEC; if (ratio < 0) ratio = 0; sprTimer.height = game.height * ratio; } // Draws info text to be aligned in center. function drawTextInfo(strMessage){ txtInfo.text = strMessage; txtInfo.updateText(); txtInfo.x = (game.width - txtInfo.textWidth)/2; } |
You can use the source code as you wish. With adding some tweens, graphics, sounds, high scores and so on this could be a nice game. For an example try to play What Is The Most Terrible Cover game.