Flappy bird

Материал из Department of Theoretical and Applied Mechanics
Перейти к: навигация, поиск

Описание

Реализация игры "Flappy bird" на языке программирования JavaScript.

Исполнители: Рязанов Павел, Шумов Кристиан

Математическая модель

Поле представляет собой прямоугольник, в котором движется птичка в сторону блоков, при столкновении с которыми вы проигрываете.
Задача игры: пролететь, не задев ни одного блока, как можно дольше.
Справа от игрового поля располагается таблица рейтинга, в которую заносятся результаты лучших попыток в порядке убывания.

Визуализация

Код программы

Код программы на языке JavaScript:

  1  ==window.addEventListener('load', program_code, false);
  2 
  3 function program_code() {
  4 
  5     var cvs = document.getElementById("canvas");
  6     var ctx = cvs.getContext("2d");
  7 
  8     var bird = new Image();
  9     var bg = new Image();
 10     var fg = new Image();
 11     var pipeUp = new Image();
 12     var pipeBottom = new Image();
 13 	var gap = 90;
 14 	var dt = 0.01;
 15 	var vy = 250;
 16     var LOOSE = false;
 17 	var arr=[];
 18 	var interv;
 19 	var polet = true;
 20 	//var arr = JSON.parse(localStorage.getItem("arr"));
 21 	var score = 0;
 22     if(localStorage.getItem("arr")== null){
 23     localStorage.setItem("arr", JSON.stringify(arr));
 24     }
 25 	//if (!localStorage.getItem('arr')) return;
 26 	
 27 // Картинки
 28 	bird.src = "birdwh3.png";
 29     bg.src = "bg.png";
 30     fg.src = "fg.png";
 31     pipeUp.src = "pipeUp.png";
 32     pipeBottom.src = "pipeBottom.png";
 33 	
 34 // Звуковые файлы
 35     // var fly = new Audio();
 36     // var score_audio = new Audio();
 37 
 38     // fly.src = "fly.mp3";
 39     // score_audio.src = "score.mp3";
 40 
 41    
 42    // Движение бёрда
 43     document.addEventListener("keydown", moveUp);
 44     function moveUp() {
 45 		if (polet == true) {
 46 		function movebird () { 
 47 		yPos -= vy*dt;
 48        // fly.play();
 49 		}
 50 		// if (yPos = bird.height/2) {
 51 			// function stopBird {
 52 				// yPos >= bird.height/2;
 53 			// }
 54 		// }
 55 	 interv = setInterval(movebird, 1000*dt);
 56 	 polet = false;
 57 		}
 58     }
 59 	document.addEventListener ("keyup", moveDown);
 60 	function moveDown () {
 61 		clearInterval(interv);
 62 		polet = true;
 63 	}
 64 
 65 
 66 // Создание блоков
 67     var pipe = [];
 68     pipe[0] = {
 69         x: cvs.width,
 70         y: 0
 71     }
 72 
 73     // Начальная озиция бёрда
 74     var xPos = 10;
 75     var yPos = 150;
 76     var grav = 1.6;
 77 	
 78     // Логика игры
 79     function draw() {
 80         if (!LOOSE) {
 81             ctx.drawImage(bg, 0, 0);
 82 			
 83             //положение новых блоков			
 84             for (var i = 0; i < pipe.length; i++) {
 85                 ctx.drawImage(pipeUp, pipe[i].x, pipe[i].y);
 86                 ctx.drawImage(pipeBottom, pipe[i].x, pipe[i].y + pipeUp.height + gap);
 87 
 88                 pipe[i].x--;
 89 
 90                 if (pipe[i].x == 95) {
 91                     pipe.push({
 92                         x: cvs.width,
 93                         y: Math.floor(Math.random() * pipeUp.height) - pipeUp.height
 94                     });
 95                 }
 96 
 97                  // Отслеживание прикосновений(услович проигрыша)
 98                 if (xPos + bird.width*0.75 + 2.5 >= pipe[i].x
 99                     && xPos <= pipe[i].x + pipeUp.width
100                     && (yPos <= pipe[i].y + pipeUp.height
101                         || yPos + bird.height*0.75 + 1.75 >= pipe[i].y + pipeUp.height + gap) || yPos + bird.height >= cvs.height - fg.height) {
102                     LOOSE = true;  }
103                 if (pipe[i].x == 5) {
104                     score++;
105                     // score_audio.play();
106                 }
107             }
108 
109             ctx.drawImage(fg, 0, cvs.height - fg.height);
110             ctx.drawImage(bird, xPos, yPos);
111 
112             yPos += grav;
113 
114             ctx.fillStyle = "#000";
115             ctx.font = "24px Verdana";
116             ctx.fillText("Счет: " + score, 10, cvs.height - 20);
117 
118             requestAnimationFrame(draw);
119 			
120         } else {
121 			//records
122             arr=JSON.parse(localStorage.getItem("arr"));
123 			arr.push(score)
124 			arr.sort((a, b) => a - b)
125             arr.reverse()
126 			console.log(score)
127 			console.log(arr)
128 			localStorage.setItem("arr", JSON.stringify(arr));
129             records.innerHTML="<tr><td> Место</td><td>Счёт</td></tr>";
130 			
131 			for(var i=0; i<9; i++){
132         if(arr.length>i){
133         records.innerHTML+="<tr><td>"+(i+1)+"</td><td>"+arr[i]+"</td></tr>";
134             }
135             else{
136                 records.innerHTML+="<tr><td>"+(i+1)+"</td><td></td></tr>";
137             }
138     }
139      records.innerHTML+='<tr><td><input border="100" id="clearStorage" onclick="localStorage.clear();" type=button value = "Сбросить" ></td><td><input id="reset" onclick="location.reload();" type=button value = "Restart" ></td></tr>';
140 			
141 			
142 			//табло проигрыша
143             ctx.fillStyle = "#ffffff";
144             ctx.fillRect(45, 223, 205, 70)
145             ctx.fillStyle = "#9ACD32"
146             ctx.font = "24px Verdana";
147             ctx.fillText("КОНЕЦ ИГРЫ!", 50, 250);
148 			ctx.fillText("СЧЕТ: " + score, 50, 280);
149 			ctx.fillRect(50, 252, 170, 2);
150 			
151         }
152 		//(a, b) => a — b
153     }
154 
155    pipeBottom.onload = tmp;
156    function tmp(){
157        arr=JSON.parse(localStorage.getItem("arr"));
158 			arr.sort((a, b) => a - b)
159 			arr.reverse()
160 			console.log(score)
161 			console.log(arr)
162 			localStorage.setItem("arr", JSON.stringify(arr));
163             records.innerHTML="<tr><td> Место</td><td>Счёт</td></tr>";
164 			for(var i=0; i<9; i++){
165         if(arr.length>i){
166         records.innerHTML+="<tr><td>"+(i+1)+"</td><td>"+arr[i]+"</td></tr>";
167             }
168             else{
169                 records.innerHTML+="<tr><td>"+(i+1)+"</td><td></td></tr>";
170             }
171     }
172      records.innerHTML+='<tr><td><input border="100" id="clearStorage" onclick="localStorage.clear();" type=button value = "Сбросить"></td><td><input id="reset" onclick="location.reload();" type=button value = "Restart" ></td></tr>';
173      draw();
174 }
175    draw;
176    
177    
178 	reset.onclick = function() {
179 location.reload() }
180 } ==