Build a rocket game from scratch using jQuery
2 min readMar 3, 2023
Goal Setting:
- Create a dynamic online game
- Increase difficulty with time progressing
- Calculate scores and add more scores according to the difficulty
- Start and End game mechanism
Purpose:
Use the same game development concept can derive from diverse type of applications.
Gameplay:
Use mouse right and left click to control the rocket dodging the aliens, The game ends when getting caught by the aliens. The speed will increase as time goes by, as well as the scores will get more accordingly.
Click me to play: https://changwei.dev.fast.sheridanc.on.ca/Projects/jQuery%20-%20Rocket/
Source code:
Code explaination:
Main function:
- move right and and left:
function left_click_action() , function right_click_action(e) - Initial position:
#stage{position:relative;} , .sprite{position:absolute;} - Create Obstacle:
function create_enemy()
- add enemy:
$stage.append - find last tag:
$stage.find(“.enemy:last”) - store wave value:
$enemy.data(“wave”,enemy_wave); - (random position) array:
var enemy_pos=[10,110,210]; var random_index = getRandomInt(0,enemy_pos.length-1); var enemy_x = enemy_pos.splice(random_index,1)[0]; .splice(specific index, remove item number)
Game Initialization:
- return to original value: score, score_add, enemy_fallspeed, enemy_wave
- Reset:player initial position, score initial position
- create enemy, reset clock, player control
Loop:
Set function loop_func()
- control each enemy:
$stage.find(“.enemy”).each(function() - create enemies according to distance:
Store value: $enemy.data(“wave”,enemy_wave) if(enemy_y>enemy_wave_gap && $(this).data(“wave”)==enemy_wave){ enemy_wave++; create_enemy(); } - Collision:
- Set coordinate of the centre
- Collision: if(hit_r>pe_distance){ endgame();
} - Score Increase: score+=score_add
- Show on the screen: $score.html(score)
- Set in the front: z-index:order number
4.Remove from screen:
if(enemy_y>$stage.height()){ $(this).remove(); return; }
Speedup:
- function speed_func()
- set max speed
if(enemy_fallspeed>=enemy_max_fallspeed){ enemy_fallspeed=11; clearInterval(speedup); } - when speedup score added more
enemy_fallspeed+=0.1; score_add+=1.1;
End Game:
- lock player
$body.unbind(“click”); $body.unbind(“contextmenu”); - clear clock
clearInterval(fall_loop); clearInterval(speedup); - Showing image of retry
$stage.append(“<div id=‘gameover’>RETRY”);
Audio:
- Add audio:
- Add sound function:
function sound_action(){
aud.play(); aud.muted=false; - Init sound:
$body.mousedown(sound_action); - End game the sound stopped:
$body.unbind(“mousedown”); - Click retry the sound reload and play:
aud.load(); sound_action()