//constants var CANVAS_WIDTH = 800; var CANVAS_HEIGHT = 600; var NINJA_WIDTH = 181; var NINJA_HEIGHT = 229; var GROUND_Y = 540; var NINJA_Y_ACCELERATION = 1; var SPACE_KEYCODE = 32; var NINJA_JUMP_SPEED = 20; var NINJA_X_SPEED = 5; var BACKGROUND_WIDTH = 1000; //var NINJA_NR_FRAMES_PER_ROW = 5; старая функция рисовани_я спрайтов var NINJA_NR_ANIMATION_FRAMES = 7; //var NINJA_NR_ANIMATION_FRAMES = 10;старая функция рисования спрайтов var NINJA_ANIMATION_SPEED = 5; var ROBOT_ANIMATION_SPEED = 5; var ROBOT_X_SPEED = 5; var ROBOT_NR_ANIMATION_FRAMES = 3; var ROBOT_WIDTH = 141; var ROBOT_HEIGHT = 139; var MIN_DISTANCE_BETWEEN_ROBOTS = 400; var MAX_DISTANCE_BETWEEN_ROBOTS = 1200; var MAX_ACTIVE_ROBOTS = 3; var SCREENSHAKE_RADIUS = 16; var NINJA_MAX_HEALTH = 100; var PLAY_GAME_MODE =0; var GAME_OVER_GAME_MODE =1; //setup var gameMode = PLAY_GAME_MODE; var ninjaHealth = NINJA_MAX_HEALTH; var canvas = document.createElement('canvas'); var c = canvas.getContext('2d'); canvas.width= CANVAS_WIDTH; canvas.height= CANVAS_HEIGHT; //198 ,229 var bush1Image = new Image(); //bush1Image.src = 'bush1.png'; bush1Image.src = 'treesmall.png'; var bush2Image = new Image(); bush2Image.src = 'bush2.png'; //bush2Image.src = 'grootsmall.png'; //заменяем на массив //var bushXCoordinates = [550,750,1000, 1200]; //var bushYCoordinates = [GROUND_Y-95,GROUND_Y-89,GROUND_Y-80,GROUND_Y-100]; var bushData = generatedBushes(); var ninjaX = CANVAS_WIDTH / 2; var ninjaY = GROUND_Y - NINJA_HEIGHT; var ninjaYSpeed = 0; var spaceKeyIsPressed =false; var ninjaFrameNr = 0; var NinjaIsInTheAir =false; var gameFrameCounter = 0; var cameraX = 0; var cameraY = 0; var backgroundImage = new Image(); backgroundImage.src = 'background.png'; // для коллизий var ninjaCollisionRectangle = { xOffset: 60, yOffset: 20, width: 50, height: 200 }; var robotCollisionRectangle = { xOffset: 50, yOffset: 20, width: 50, height: 100 }; // собираем константы для универсальной логики отрисовки спрайтов var ninjaImage = new Image(); //ninjaImage.src = 'animatednanonaut.png'; ninjaImage.src= 'peppa10.png'; var ninjaSpriteSheet = { nrFramesPerRow: 5, spriteWidth: NINJA_WIDTH, spriteHeight: NINJA_HEIGHT, image: ninjaImage } var robotImage = new Image (); robotImage.src = 'animatedRobot.png'; var robotSpriteSheet = { nrFramesPerRow:3, spriteWidth: ROBOT_WIDTH, spriteHeight: ROBOT_HEIGHT, image: robotImage} //массив из роботов для тестирования var robotData = [{ x:400, y:GROUND_Y - ROBOT_HEIGHT, frameNr: 0 }]; //запускаем обработчики событий window.addEventListener('keydown',onKeyDown); window.addEventListener('keyup',onKeyUp); window.addEventListener('load',start); function start(){ window.requestAnimationFrame(mainLoop); } //генерируем случайно деревья и кусты function generatedBushes() { var generatedBushData = []; var bushX = 0; while (bushX < (2 * CANVAS_WIDTH)){ var bushImage; if (Math.random() >= 0.5) { bushImage = bush1Image; //функция случайной генерации кустов и деревьев generatedBushData.push({ x:bushX, y:300 + Math.random() * 5, image: bushImage }); bushX += 150 + Math.random() * 200; } else { bushImage = bush2Image; generatedBushData.push({ x:bushX, y:80 + Math.random() * 20, image: bushImage }); bushX += 150 + Math.random() * 200; } //добавляем управление расстоянием между кустами } return generatedBushData; } //main loop function mainLoop (){ update(); draw(); window.requestAnimationFrame(mainLoop)} //player input function onKeyDown(event){ if (event.keyCode === SPACE_KEYCODE){ spaceKeyIsPressed = true; } } function onKeyUp(event){ if (event.keyCode === SPACE_KEYCODE){ spaceKeyIsPressed=false; } } //updating function update (){ if (gameMode != PLAY_GAME_MODE) return; gameFrameCounter = gameFrameCounter + 1; ninjaX = ninjaX + NINJA_X_SPEED; if (spaceKeyIsPressed && !ninjaIsInTheAir){ ninjaYSpeed = - NINJA_JUMP_SPEED; ninjaIsInTheAir = true; } ninjaY = ninjaY + ninjaYSpeed; ninjaYSpeed = ninjaYSpeed + NINJA_Y_ACCELERATION; //update bushes for (var i=0; i= NINJA_NR_ANIMATION_FRAMES){ ninjaFrameNr = 0;} } //обновляем камеру cameraX = ninjaX - 150; if (ninjaY>(GROUND_Y-NINJA_HEIGHT)){ ninjaY=GROUND_Y-NINJA_HEIGHT; ninjaYSpeed = 0; ninjaIsInTheAir = false; } //обновляем роботов на экране с функцией если их коснулся игрок screenshake = false; var ninjaTouchedRobot = updateRobots (); if (ninjaTouchedRobot) {screenshake = true; if (ninjaHealth >0) ninjaHealth -=1; } //проверяем если игра закончилась if (ninjaHealth <= 0) { gameMode = GAME_OVER_GAME_MODE; screenshake = false; } } // конец Update () // рисуем столкновения с роботом //Добавляем описание функции добавления роботов function updateRobots (){ //Учим их передвигаться var ninjaTouchedRobot = false; for (var i=0;i= ROBOT_NR_ANIMATION_FRAMES){ robotData[i].frameNr = 0; } } } // удаляем роботов с экрана var robotIndex = 0; while (robotIndex < robotData.length){ if (robotData[robotIndex].x < cameraX - ROBOT_WIDTH){ robotData.splice(robotIndex,1); console.log ("I removed a robot!"); } else { robotIndex += 1; } } //добавляем новых роботов if (robotData.length < MAX_ACTIVE_ROBOTS){ var lastRobotX = CANVAS_WIDTH; if (robotData.length >0) { lastRobotX = robotData [robotData.length -1].x; } var lastRobotX = robotData [robotData.length -1].x; var newRobotX = lastRobotX + MIN_DISTANCE_BETWEEN_ROBOTS + Math.random() * (MAX_DISTANCE_BETWEEN_ROBOTS - MIN_DISTANCE_BETWEEN_ROBOTS); robotData.push ({ x: newRobotX, y: GROUND_Y - ROBOT_HEIGHT, frameNr: 0 }); } return ninjaTouchedRobot; } // конец updateRobots //рисуем спрайты function doesNinjaOverlapRobotAlongOneAxis (ninjaNearX, ninjaFarX,robotNearX,robotFarX){ var ninjaOverlapNearRobotEdge = (ninjaFarX >= robotNearX) && (ninjaFarX <= robotFarX); var ninjaOverlapFarRobotEdge = (ninjaNearX >= robotNearX) && (ninjaFarX >= robotFarX); var ninjaOverlapEntireRobot = (ninjaNearX <= robotNearX) && (ninjaFarX >= robotFarX); return ninjaOverlapNearRobotEdge||ninjaOverlapFarRobotEdge||ninjaOverlapEntireRobot; } function doesNinjaOverlapRobot (ninjaX, ninjaY, ninjaWidth, ninjaHeight,robotX,robotY, robotWidth, robotHeight){ var ninjaOverlapRobotonXAxis = doesNinjaOverlapRobotAlongOneAxis ( ninjaX, ninjaX + ninjaWidth, robotX, robotX+ robotWidth ); var ninjaOverlapRobotonYAxis = doesNinjaOverlapRobotAlongOneAxis ( ninjaY, ninjaY + ninjaHeight, robotY, robotY+robotHeight ); return ninjaOverlapRobotonXAxis && ninjaOverlapRobotonYAxis } //drawing function draw () { //рисуем тряску экрана при столкновении var shakenCameraX = cameraX; var shakenCameraY = cameraY; var screenshake = false; if (screenshake){ // нужно изменить камеру Х и Y чтобы камера тряслась shakenCameraX += (Math.random() -.5) * SCREENSHAKE_RADIUS; shakenCameraY += (Math.random() -.5) * SCREENSHAKE_RADIUS; } //c.clearRect (0,0, CANVAS_WIDTH, CANVAS_HEIGHT); //рисуем небо c.fillStyle = 'LightSkyBlue'; c.fillRect (0,0,CANVAS_WIDTH,GROUND_Y-40); //рисуем гравитацию var backgroundX = - (cameraX % BACKGROUND_WIDTH); c.drawImage(backgroundImage,backgroundX,-210); c.drawImage(backgroundImage,backgroundX + BACKGROUND_WIDTH,-210); //рисуем землю c.fillStyle = 'ForestGreen'; c.fillRect(0,GROUND_Y-40,CANVAS_WIDTH,CANVAS_HEIGHT-GROUND_Y+40); //рисуем кусты из массива //for (var i=0;i
Made on
Tilda