Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have tried to figure out whats wrong with my code for a simple platform game. I am brand new to coding. Anyway, if someone

I have tried to figure out whats wrong with my code for a simple platform game. I am brand new to coding. Anyway, if someone could post their own version of the assignment for me to compare I'd greatly appreciate it (This is javascript/css).

My code:

DOMDisplay.prototype.drawFrame = function() { if (this.actorLayer) this.wrap.removeChild(this.actorLayer); this.actorLayer = this.wrap.appendChild(this.drawActors()); // Update the status each time with this.level.status" this.wrap.className = "game " + (this.level.status || ""); this.scrollPlayerIntoView(); };

DOMDisplay.prototype.scrollPlayerIntoView = function() { var width = this.wrap.clientWidth; var height = this.wrap.clientHeight;

// We want to keep player at least 1/3 away from side of screen var margin = width / 3;

// The viewport var left = this.wrap.scrollLeft, right = left + width; var top = this.wrap.scrollTop, bottom = top + height;

var player = this.level.player; // Change coordinates from the source to our scaled. var center = player.pos.plus(player.size.times(0.5)) .times(scale);

if (center.x < left + margin) this.wrap.scrollLeft = center.x - margin; else if (center.x > right - margin) this.wrap.scrollLeft = center.x + margin - width; if (center.y < top + margin) this.wrap.scrollTop = center.y - margin; else if (center.y > bottom - margin) this.wrap.scrollTop = center.y + margin - height; };

// Remove the wrap element when clearing the display // This will be garbage collected DOMDisplay.prototype.clear = function() { this.wrap.parentNode.removeChild(this.wrap); };

// Return the first obstacle found given a size and position. Level.prototype.obstacleAt = function(pos, size) { // Find the "coordinate" of the tile representing left bound var xStart = Math.floor(pos.x); // right bound var xEnd = Math.ceil(pos.x + size.x); // top bound var yStart = Math.floor(pos.y); // Bottom bound var yEnd = Math.ceil(pos.y + size.y);

// Consider the sides and top and bottom of the level as walls if (xStart < 0 || xEnd > this.width || yStart < 0) return "wall"; if (yEnd > this.height) return "lava";

// Check each grid position starting at yStart, xStart // for a possible obstacle (non null value) for (var y = yStart; y < yEnd; y++) { for (var x = xStart; x < xEnd; x++) { var fieldType = this.grid[y][x]; if (fieldType) return fieldType; } } };

// Collision detection for actors is handled separately from // tiles. Level.prototype.actorAt = function(actor) { // Loop over each actor in our actors list and compare the // boundary boxes for overlaps. for (var i = 0; i < this.actors.length; i++) { var other = this.actors[i]; // if the other actor isn't the acting actor if (other != actor && actor.pos.x + actor.size.x > other.pos.x && actor.pos.x < other.pos.x + other.size.x && actor.pos.y + actor.size.y > other.pos.y && actor.pos.y < other.pos.y + other.size.y) // check if the boundaries overlap by comparing all sides for // overlap and return the other actor if found return other; } };

// Update simulation each step based on keys & step size Level.prototype.animate = function(step, keys) { // Have game continue past point of win or loss if (this.status != null) this.finishDelay -= step;

// Ensure each is maximum 100 milliseconds while (step > 0) { var thisStep = Math.min(step, maxStep); this.actors.forEach(function(actor) { // Allow each actor to act on their surroundings actor.act(thisStep, this, keys); }, this); // Do this by looping across the step size, subtracing either the // step itself or 100 milliseconds step -= thisStep; } };

Lava.prototype.act = function(step, level) { var newPos = this.pos.plus(this.speed.times(step)); if (!level.obstacleAt(newPos, this.size)) this.pos = newPos; else if (this.repeatPos) this.pos = this.repeatPos; else this.speed = this.speed.times(-1); };

var maxStep = 0.05;

var wobbleSpeed = 8, wobbleDist = 0.07;

Coin.prototype.act = function(step) { this.wobble += step * wobbleSpeed; var wobblePos = Math.sin(this.wobble) * wobbleDist; this.pos = this.basePos.plus(new Vector(0, wobblePos)); };

var maxStep = 0.05;

var wobbleSpeed = 8, wobbleDist = 0.07;

Coin.prototype.act = function(step) { this.wobble += step * wobbleSpeed; var wobblePos = Math.sin(this.wobble) * wobbleDist; this.pos = this.basePos.plus(new Vector(0, wobblePos)); };

var wobbSpeed = 3, wobbDist = 0.4; Health.prototype.act = function(step) { this.wobble += step * wobbSpeed; var wobbPos = Math.sin(this.wobble) * wobbDist; var wobbPosY = Math.cos(this.wobble) * wobbDist; this.pos = this.basePos.plus(new vector(wobbPos. wobPosY)); }; var maxStep = 0.05;

var maxStep = 0.05;

var playerXSpeed = 7;

Player.prototype.moveX = function(step, level, keys) { this.speed.x = 0; if (keys.left) this.speed.x -= playerXSpeed; if (keys.right) this.speed.x += playerXSpeed;

var motion = new Vector(this.speed.x * step, 0); // Find out where the player character will be in this frame var newPos = this.pos.plus(motion); // Find if there's an obstacle there var obstacle = level.obstacleAt(newPos, this.size); // Handle lava by calling playerTouched if (obstacle) level.playerTouched(obstacle); else // Move if there's not an obstacle there. this.pos = newPos; };

var gravity = 20; var jumpSpeed = 18; var playerYSpeed = 200;

Player.prototype.moveY = function(step, level, keys) { // Accelerate player downward (always) this.speed.y += step * gravity;; var motion = new Vector(0, this.speed.y * step); var newPos = this.pos.plus(motion); var obstacle = level.obstacleAt(newPos, this.size); // The floor is also an obstacle -- only allow players to // jump if they are touching some obstacle. if (obstacle) { level.playerTouched(obstacle); if (keys.up && this.speed.y > 0) this.speed.y = -jumpSpeed; else this.speed.y = 0; } else { this.pos = newPos; } };

Player.prototype.act = function(step, level, keys) { this.moveX(step, level, keys); this.moveY(step, level, keys);

var otherActor = level.actorAt(this); if (otherActor) level.playerTouched(otherActor.type, otherActor);

// Losing animation if (level.status == "lost") { this.pos.y += step; this.size.y -= step; } else if (type == "health") { this.actors = this.actors.filter(function(other)) { return other != actor; }}; };

Level.prototype.playerTouched = function(type, actor) {

// if the player touches lava and the player hasn't won // Player loses if (type == "lava" && this.status == null) { this.status = "lost"; this.finishDelay = 1; } else if (type == "coin") { this.actors = this.actors.filter(function(other) { return other != actor; }); // If there aren't any coins left, player wins if (!this.actors.some(function(actor) { return actor.type == "coin"; })) { this.status = "won"; this.finishDelay = 1; if (type == "spike" && this.status == null) { this.status = "lost"; this.finishDelay = 1; } else if (type == "coin") { this.actors = this.actors.filter(function(other) { return other != actor; }); } } };

// Arrow key codes for readibility var arrowCodes = {37: "left", 38: "up", 39: "right"};

// Translate the codes pressed from a key event function trackKeys(codes) { var pressed = Object.create(null);

// alters the current "pressed" array which is returned from this function. // The "pressed" variable persists even after this function terminates // That is why we needed to assign it using "Object.create()" as // otherwise it would be garbage collected

function handler(event) { if (codes.hasOwnProperty(event.keyCode)) { // If the event is keydown, set down to true. Else set to false. var down = event.type == "keydown"; pressed[codes[event.keyCode]] = down; // We don't want the key press to scroll the browser window, // This stops the event from continuing to be processed event.preventDefault(); } } addEventListener("keydown", handler); addEventListener("keyup", handler); return pressed; }

// frameFunc is a function called each frame with the parameter "step" // step is the amount of time since the last call used for animation function runAnimation(frameFunc) { var lastTime = null; function frame(time) { var stop = false; if (lastTime != null) { // Set a maximum frame step of 100 milliseconds to prevent // having big jumps var timeStep = Math.min(time - lastTime, 100) / 1000; stop = frameFunc(timeStep) === false; } lastTime = time; if (!stop) requestAnimationFrame(frame); } requestAnimationFrame(frame); }

// This assigns the array that will be updated anytime the player // presses an arrow key. We can access it from anywhere. var arrows = trackKeys(arrowCodes);

// Organize a single level and begin animation function runLevel(level, Display, andThen) { var display = new Display(document.body, level);

runAnimation(function(step) { // Allow the viewer to scroll the level level.animate(step, arrows); display.drawFrame(step); if (level.isFinished()) { display.clear(); if (andThen) andThen(level.status); return false; } }); }

function runGame(plans, Display) { function startLevel(n) { // Create a new level using the nth element of array plans // Pass in a reference to Display function, DOMDisplay (in index.html). runLevel(new Level(plans[n]), Display, function(status) { if (status == "lost") startLevel(n); else if (n < plans.length - 1) startLevel(n + 1); else console.log("You win!"); }); } startLevel(0); }}

Information:

For Project Two, we'll be working with a JavaScript-based platfomer that creates a DOM-based Javascript game engine. I'll be providing the foundation code for your game, which is adapted from the code in Chapter 15 on Eloquent JavaScript (Links to an external site.)Links to an external site.. You will take this foundation and make it your own through changing the design and adding additional interactive elements. Your final game will resemble this game (Links to an external site.)Links to an external site.. This project will demand your careful attention to a complex code system, as you will have to master reading and understanding code logic in order to make the appropriate changes and bring your own design to life. The process will prepare you to work with more complex libraries and resources as you move forward with scripting, whether for games or web.

You will:

Update the game levels arrays to reflect three of your own original levels. Delete the provided designs, just leave your own levels in the file. (This was started in the first lab)

Add an original hazard to the game. One simple option is a portal that teleports the user backwards: to add a portal of this kind, start by following the lab exercise to add a new symbol to the level grid. Then, alter the collision detection for that object to change the player's position to a modified version of their current position. The hazard will need its own symbol in your level grids and its own CSS.

Add an original interactive element to the game. This was started in the coin collection lab, as your interactive element needs to be an object so it can move. You might make this object a speed boost that modifies the player's speed in one direction, or changes the jump speed. This actor needs to be added to the actors list and will need a constructor, act function, and its own CSS.

Alter the win / lose conditions to fit your game. You might consider using something other than coin collection, like reaching a specific object, to trigger winning a level. Add a final message, event, or screen for when the player reaches the end of the game. (The easiest way to do this is by adding an additional level design and using the grid to "write" a message like "YOU WIN" using the level blocks.)

Customize the aesthetics. Remember, you can replace any CSS color with an image by changing to use background-image. Your character doesn't need to be animated: a static pixel image is fine. You can also use color and CSS gradients if you prefer, as long as you've fully customized your design.

Make sure you are clear on how to either create a repository or upload to Sulley, as you'll need to submit your final link using one of those methods. The best way to do this is to go through your solutions to each lab, and integrate them into the provided code. LEAVE TIME FOR DEBUGGING, as you will introduce errors and you will need to use the console log to find them. I can help you interpret error messages, but I will not hunt down bugs for you!

We will be building the foundation together over several in-class demos and lab exercises that will help you understand and expand on the existing code base. All of the code necessary to start the project is available for download in a Github repository (Links to an external site.)Links to an external site.. For your final project, you should be submitting either a Github repository or a Sulley link with your working game. File uploads will not be accepted: you will need to provide a link.

Github:

https://github.com/AMSUCF/JSPlatformer/tree/fbf2d057d1bc20a7d9e326b380fb625d1f1fce03

Thank you for your response.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Domain Transfer Learning With 3q Data Processing

Authors: Ahmed Atif Hussain

1st Edition

B0CQS1NSHF, 979-8869061805

More Books

Students also viewed these Databases questions

Question

8. Describe how cultural spaces are formed.

Answered: 1 week ago