Cheat for hidden game "Atari Breakout" in Google Image Search - javascript

How would a cheat/auto moving paddle in this hidden html game look like?
There is a
<div id="breakout-ball"><span>●</span></div>
and a
<div id="breakout-paddle"></div>
when moving the mouse the paddle is moved horizontally. How can I connect the movement of the ball with the paddle?
This question will become "community wiki" as soon as possible.

function cheat() {
var ball = document.getElementById('breakout-ball');
var paddle = document.getElementById('breakout-paddle');
paddle.style.left = ball.style.left;
setTimeout(cheat, 20);
}
cheat();
// Add this via the FireBug console.

I modified your solution slightly to account for the scenario of the ball going off screen and breaking the hack and also the ball getting jammed into the corner.
function cheat() {
var ball = document.getElementById('breakout-ball');
var paddle = document.getElementById('breakout-paddle');
var buffer = Math.floor((Math.random()*100)+1);
var leftVal = parseInt(ball.style.left, 10);
if (ball.style.left) {
paddle.style.left = (leftVal - buffer) + 'px';
}
setTimeout(cheat, 100);
}
cheat();
To be honest though, if you are going down that road why not do this?
function cheat() {
var paddle = document.getElementById('breakout-paddle');
paddle.style.width = '100%';
}
cheat();
Anyway I'm going to continue to dig into the code and do some deeper manipulation

in chrome, search the game, ctrl+J, paste the following in, and press enter.
This is a simple goal:
//get the ball's X position from its CSS
function ballx(){
return parseFloat(document.querySelector("#breakout-ball").style.left.split("px")[0]);
}
function update(e){
//throws an exception when the game isn't up. Can be really annoying.
try{document.querySelector("#breakout-paddle").style.left = (ballx() - 75)+"px";}
catch(ex){}
}
var intervalTimer = setInterval(update, 125);//let it have a single weakness in case someone else tries it while I am around.
The lower the interval rate, the faster the paddle will move relative to the ball, but the slower the game goes. The maximum rate can be given with a simple requestAnimationFrame cycle, but that slows the browser down a lot(at least on my laptop).
I tried changing the paddle's size. It doesn't really work.
I'm sure it would be simpler with jQuery, but why make cheating easy when doing it hard core is already so easy?

I have come up with a new way to solve this problem. Whenever the screen size or window size changes, the paddle changes size based on the screen size. To combat this, I simply just added another section that splits the size of the paddle in half then uses that value to find the centre of the paddle. Very simple and very effective.
function autoMove() {
var ball = document.getElementById('breakout-ball')
var paddle = document.getElementById('breakout-paddle')
var leftVal = parseInt(ball.style.left, 10)
var paddleWidth = parseFloat(paddle.style.width, 10) / 2
paddle.style.left = (leftVal - paddleWidth) + 'px'
setTimeout(autoMove, 20)
}
autoMove();
Also, didn't like the function name. It looks way too suspicious so changed it. Hope this helps.

Related

Collectibles not appearing in canvas

As I've ditched using Phaser, I've gotten more work done to the point of the sprite moving, and I finished programming the collision detection, but I need something more... I decided to make coins to collect for a currency. I tried programming them to appear at random points on the map using a randomRange function. I managed to get one coin spawn in the upper left corner of the canvas, but I made one slight change, and the coin just stopped spawning in the canvas at all. I've called the coins under the function collectibles, which I've called upon in the update and draw functions. Just adding them to the update and draw functions made my player sprite be locked in place! Do I need a JS library just to make the coins spawn?
Here's the code:
function collectibles () {
this.srcX = 0;
this.srcY = 0;
this.width = 20; //how wide the sprite is in pixels
this.height = 20; //how tall the sprite is in pixels
this.drawX = this.randomRange;
this.drawY = this.randomRange;
this.centerX = this.drawX + (this.width / 2);
this.centerY = this.drawY + (this.height / 2);
}
Any errors in console? If 'randomRange' is a function it lacks braces() at the end where you call it. 'this' might differ depending on where you call the function 'collectibles'.

Javascript sprites moving between two points

I'm wanting to get some sprites moving between two points in my (very basic) javascript game. Each sprite is randomly placed in the level, so I want them to move back and forth between their base position. I have the code below
function Taniwha(pos) {
this.basePos = this.pos;
this.size = new Vector(0.6, 1);
this.move = basePos + moveDist(5,0));
}
Taniwha.prototype.type = "taniwha"
var moveSpeed = 4;
Taniwha.prototype.act = function(step) {
this.move = ???
and this is where I get stuck. I'm not sure how to tell it to go left, back to base pos, right then back to base pos again (I plan to loop this). Does anyone have any advice? (also using Eloquen Javascript's example game as an outline/guide for this, if how I'm doing things seems odd!)
For horizontal movement, change x coordinate of the position.
var pos = { x: 1, y: 2 };
pos.x++ ; // This will move right
pos.x-- ; // This will move left
Likewise for vertical movement. You also need to update the coordinates after change for the object which you are drawing.
In truth ,there are lots of library to develop a game.
Use those, control a sprite is very easy.
Like:
Pixijs
CreateJS
Both of them are opensource project, you can watch and learn the source.
And have lots of examples and document.

Improving collision detection performance in HTML5/Javascript

I'm currently creating a game that involves coins that come up from the bottom of the screen in a random X position. If the hero overlaps/collides with the coins, the user gets a point.
My issue is, when I put my collision detection in a fast interval function, it seems that the collision is not registering at some instances.
I've replicated the game in the jsfiddle below (originally it uses the phone's accelerometer to move the hero but for this example I've quickly made it a left/right key based control) -
http://jsfiddle.net/wpavxn6k/1/
Snippet of the interval below -
//keep checking to see if collision has occured
window.setInterval(function () {
if (hitTest(app.hero, app.coinClassUnique) == true) {
app.coinClassUnique.css('display', 'none');
app.score++;
$("h2").html(app.score);
}
}, 5);
//measure the width/height and position of the coin div and the hero image to determine if they are overlapping
function hitTest(a, b) {
var aPos = a.offset();
var bPos = b.offset();
var aLeft = aPos.left;
var aRight = aPos.left + a.width();
var aTop = aPos.top;
var aBottom = aPos.top + a.height();
var bLeft = bPos.left;
var bRight = bPos.left + b.width();
var bTop = bPos.top;
var bBottom = bPos.top + b.height();
return !(bLeft > aRight || bRight < aLeft || bTop > aBottom || bBottom < aTop);
}
My question is whether you can see an obvious flaw in my code that may be affecting performance, or if there are any tips of how I can improve performance and collision detection in a real-time based game like this.
I just wanted to post the answer for this question incase someone encounters a similar issue. The interval of the game was happening at different times so I rebuilt the game inside a Canvas element with requestFrameAnimation. This way, all the elements reload at once.
I had some issues like images not loading properly etc. at first, which is why I avoided using canvas - but with the help of preloading and rendering the images into separate canvases that are hidden off screen - I was able to tackle these issues.

Unfreeze bodies in Box2Djs or prevent from exiting world

I am working on a server side physics experiment where the user controls an object through a socket. The problem I am running into results when the user moves the object outside the boundaries of the world.
I am using Box2Djs as installed through npm.
I create world 500x500 and then attach the following listener to it:
var boundaryListener = new b2d.b2BoundaryListener();
boundaryListener.Violation = function (body) {
//we will move this body to the opposite side
var position = body.GetWorldCenter();
//snap to opposite side
if (position.x < 0) {
position.x = worldAABB.upperBound.x + position.x;
}
if (position.y < 0) {
position.y = worldAABB.upperBound.y + position.y;
}
if (position.x > worldAABB.upperBound.x) {
position.x -= worldAABB.upperBound.x;
}
if (position.y > worldAABB.upperBound.y) {
position.y -= worldAABB.upperBound.y;
}
body.m_flags = body.m_flags & (~b2d.b2Body.e_frozenFlag); //does nothing :(
}
this.world.SetBoundaryListener(boundaryListener);
worldAABB is the b2AABB that the world uses as a boundary.
The problem is that I have noticed that when the boundary listener is fired, the flags are set to 22 which is allowSleep, frozen, and island flags. It would seem that when a b2Body passes outside the world boundary, it is frozen. That last line is an attempt to unfreeze the body by messing with the internal flags, but I have a distinct feeling that's the wrong way to do it.
How can I unfreeze the body? There are no functions that clear the frozen flags that I can see (the javascript is over 10,000 lines long so I honestly haven't read the whole thing) and placing some bodies as walls seems to have no effect (the user's object passes right through them).
My walls are created like so:
//create walls
var wallShape = new b2d.b2PolygonDef();
wallShape.SetAsBox(500, 10);
wallShape.density = 0.0;
wallShape.friction = 0.3;
var bodyDef = new b2d.b2BodyDef();
bodyDef.position.Set(250, 20);
var north = this.world.CreateBody(bodyDef);
north.CreateShape(wallShape);
bodyDef = new b2d.b2BodyDef();
bodyDef.position.Set(250, 499);
var south = this.world.CreateBody(bodyDef);
south.CreateShape(wallShape);
bodyDef = new b2d.b2BodyDef();
bodyDef.position.Set(499,250);
bodyDef.angle = Math.PI / 2;
var east = this.world.CreateBody(bodyDef);
east.CreateShape(wallShape);
bodyDef = new b2d.b2BodyDef();
bodyDef.position.Set(1, 250);
bodyDef.angle = Math.PI / 2;
var west = this.world.CreateBody(bodyDef);
west.CreateShape(wallShape);
Does anyone have any insights on how to fix this? There is very very little documentation I can find on using Box2D in javascript aside from the flash documentation that the website points to (which doesn't match half the time) and the C++ documentation which doesn't even talk about freezing.
It would probably be helpful to mention that the world has no gravity and all the objects have some linear and angular damping (its supposed to be a psuedo-in-space feel).
I had investigated Box2Djs source, and found next thing. Every time step Box2Djs checks if the body is inside the world boundaries. If body is out of range, then it "frozing", i.e. its excluding from collision detection. There this code (Body.js line 414):
Freeze: function(){
this.m_flags |= b2Body.e_frozenFlag;
this.m_linearVelocity.SetZero();
this.m_angularVelocity = 0.0;
for (var s = this.m_shapeList; s != null; s = s.m_next)
{
s.DestroyProxy();
}
}
Pay attention, this check performs every time step (b2Island.js 244). So, if you set e_frozenFlag at boundary listener, it will do nothing: flag will be set up at next time step. Thats more, after body had frozen, it losses its veolcity and its shapes looses theirs proxies in broad phase (as you can see from code above). Looks like proxies are not restroing automaticly, so, reseting flag is not enough.
I also not found somewhere in Box2Djs interface or logic for unfreezing bodies. Doing this manually is some kind of dirty trick, because you should acces BroadPhase, which is Box2Djs internal. Thats more, it dont help you, because on freezing body losses its velociy. But, as I see, you need continue body moving.
Solution is next. You should prevent body frozing at all in order to keep body in simulation after it moved out of world boundaries. It may be done by next trick. First, set world boundary with some large value. Then, set contact listener, and when body touches the walls, perform your boundary violation logic.
How to set contact listener in C++ you can see there: https://www.iforce2d.net/b2dtut/collision-callbacks Sory, I dont know java script and can't say, how to do this in Box2Djs.

Vectors, calculate movement forces with max speed

Im building a small space shooter game. I have how ever stubbed on a math problem when it come to the space physics.
Describing this with words is following:
There is a max speed.
So if you give full full speed you ship will move with this over the screen over and over again like in the old asteroids games.
If then release the rocket boost you ship should be keep moving with that speed over the screen.
Then the tricky part where Im stuck right now.
If you rotate the ship ANY angle and gives boost again the ship should try to get to this direction and NEVER surpas the max speed when it comes to how fast it is moving. so my question is. anyone have a good idea formula for this issue? feels like it has been done before if you know what to look for. :)
Ill add this small image to illustrate what is tried to be done with some vector calculations.
Red ring: Max speed
Green line: current ship direction.
Black line: direction(s) and how fast the ship is moveing in x and y.
Black ring: origin of movement.
Can illustrate it but hard to find a good math solution for this. :)
EDIT
This is the code Im using right now in every frame. It gives movement to the ship but does not give the force of movement the user has to counter-react with its rocket boosters to get the ship to stop or slow down. With this it stops the instant you release the accelerating speed for the ship.
//Calculates ship movement rules
var shipVelocityVec = GetVectorPosByAngle(shipMoveSpeed, shipRotationAngle);
var shipUnitVec =$V([Math.cos(shipRotationAngle),Math.sin(shipRotationAngle),0]);
var rawAccel = shipAccelSpeed / shipMass;
var scale = (shipUnitVec.dot(shipVelocityVec))/(shipTopSpeed * shipTopSpeed);
var v1 = shipUnitVec.subtract(shipVelocityVec.multiply(scale));
var finalAccelVec = v1.multiply(rawAccel);
console.log(finalAccelVec);
//move ship according to rules
var shipPosVector = $V([shipxPos, shipyPos, 0]);
var movementVector = shipPosVector.add(finalAccelVec);
shipxPos = movementVector.elements[0];
shipyPos = movementVector.elements[1];
To give the acceleration speed the user has to keep the button pressed. the instance the user releases the button the acceleration is set to zero and have to boost over again to give maximum acceleration throttle.
Solution found! Posted it here how it was done.
You seem to be confusing something - there is no issue capping the velocity to a maximum speed, even when the acceleration is at a different angle, if you are using vectors correctly.
Your setup should look something like this:
Your ship should have a position, a velocity, and an acceleration. Each of these can be represented as a 2D vector (with separate x and y components).
Every frame, add the velocity to the position, and the acceleration to the velocity.
Every frame, check that the speed does not exceed some maximum. If it does, cap the speed by normalizing the velocity vector and multiplying it by the max speed.
That's it! There are no special cases to consider - that's the magic of vector algebra!
#BlueRaja's solution should work, although you will get an abrupt change in behavior when you hit the max speed.
If you want a solution with no "seams", I believe you can do what you're looking for by adding the right kind of adjustment to the acceleration, as follows:
ship_unit_vec = [cos(ship_angle), sin(ship_angle)]
raw_accel = (engine_thrust / ship_mass)
scale = dot_product(ship_unit_vec, ship_velocity_vec) / max_speed^2
final_accel_vec = raw_accel * (ship_unit_vec - scale * ship_velocity_vec)
Notes:
If |ship_velocity_vec|<<max_speed, the scale * ship_velocity_vec component is negligable.
If |ship_velocity_vec|==max_speed, the scale * ship_velocity_vec component cancels all additional acceleration in the "wrong" direction, and aids acceleration in the "right" direction.
I've never tried this out, so I don't know how it will feel to the player...
More generally, if there are more sources of acceleration than just the ship thrusters, you can add them all together (say, as raw_accel_vec), and perform the above operation all at once:
scale_forall = dot_product(raw_accel_vec, ship_velocity_vec) / max_speed^2
final_accel_vec = raw_accel_vec - scale_forall * ship_velocity_vec
Rather than just imposing an ad hoc maximum speed, you could use some actual physics and impose a drag force. This would be an extra force acting on the spaceship, directed opposite to the velocity vector. For the magnitude of the drag force, it's simplest to just take it proportional to the velocity vector.
The overall effect is that the drag force increases as the spaceship moves faster, making it harder to accelerate in the direction of motion when the ship moves faster. It also makes acceleration easier when it is opposed to the direction of motion.
One point where this diverges from your description is that the spaceship won't continue at maximum speed forever, it will slow down. It won't, however, come to a halt, since the drag force drops as the ship slows down. That matches my memory of asteroids better than the ship continuing forever at constant velocity, but it has been quite a while since I've played.
I did it! Thank you for your help.
Finally found the solution. the problem was I was trying to modify the ships current movement when it comes to speed and then of this calculate the "drag" forces that would be the product of this movement when the user tried to go another direction. The solution was like #BlueRaja and #Comingstorm mentioned. All forces should be added together when it comes to the movement. This should be what then alter the ships position. Should not be added to the ships current movement. You might be able to effect a current movement to but then you have to do this differently. So I thought I share my solution for this how it looks.
This function is run each time the user accelerates the ship.
function CalcShipMovement() {
//Calculates ship movement rules
shipPosVector = $V([shipxPos, shipyPos, 0]);
var shipVelocityVec = GetVectorPosByAngle(shipAccelSpeed, shipRotationAngle);
var shipUnitVec = $V([Math.cos(shipRotationAngle), Math.sin(shipRotationAngle), 0]);
if(currentShipMoveVector != null && Get2DVectorLength(currentShipMoveVector) > 0) {
var nextMove = currentShipMoveVector.add(shipVelocityVec);
var nextSpeed = Get2DVectorLength(nextMove);
//check if topspeed of movement should be changed
if(nextSpeed > shipTopSpeed) {
var scale = nextSpeed / shipTopSpeed;
currentShipMoveVector = DevideVector(nextSpeed, scale);
} else {
currentShipMoveVector = currentShipMoveVector.add(shipVelocityVec);
}
}
if(currentShipMoveVector != null && Get2DVectorLength(currentShipMoveVector) == 0) {
currentShipMoveVector = currentShipMoveVector.add(shipVelocityVec);
}}
This code is run in every frame the graphics for the ship is generated to alter its position.
function SetShipMovement() {
if(currentShipMoveVector != null && Get2DVectorLength(currentShipMoveVector) > 0) {
shipMoveSpeed = Get2DVectorLength(currentShipMoveVector);
shipPosVector = shipPosVector.add(currentShipMoveVector);
shipxPos = shipPosVector.elements[0];
shipyPos = shipPosVector.elements[1];
//Makes the ship slow down if no acceleration is done for the ship
if(shipAccelSpeed == 0) {
currentShipMoveVector = currentShipMoveVector.subtract(DevideVector(currentShipMoveVector, 50));
}
} else {
currentShipMoveVector = $V([0, 0, 0]);
}}

Categories