How do you make computer lose in a pong game? - pong

So me and my partner are trying to make a pong game that's player vs. computer, but we just couldn't figure out how to make the computer lose.
We already have the basic stuff done and it works fine but the computer just never loses. And we also tried slow down the computer peddle using sleep, but whenever the paddle moves slow, the ball also moves slow.
any advice would help!
Thanks

And we also tried slow down the
computer peddle using sleep, but
whenever the paddle moves slow, the
ball also moves slow.
You need to make it slower by moving it a shorter distance each time it moves.

In the original Pong game, the paddle was perfectly in sync with the ball, that is whenever the ball went down a line, the paddle did too. Obviously, that would make the game unwinnable so the solution used by the developers was to skip an update cycle every few cycles.
In layman's terms, on every frame, you adjust the paddle's location to follow the ball, except on the fifth, tenth, fifteenth, etc. By doing that, your paddle will seem to follw the ball nicely, but with some kind of delayed reaction.

I assume that the computer never loses because it "knows" where the ball is going to go. In that case, why can't you make it go to the wrong place some percentage of the time?
As well, if you just wanted to slow it down, rather than sleeping, you could intersperse "moves" of "don't go anywhere" along with the movement towards what it thinks is the right place to be. So instead of "down 1, down 1, down 1", you could have "down 1, down 0, down 0, down 1, down 0, down 0..." or something along those lines.

I think there is a game site for problems like this https://gamedev.stackexchange.com/. But my answer would be to try and cycle the top speed of the AI bat. And to make the bat short sited. (Only respond to the ball position once it is in its half.)

Computer must make mistakes to lose. The catch is, the mistake must be realistic. If the mistakes seems too artificial, the human player loses interest after a while. The human must believe the cause of the mistake is his good play.
The computer may occacionally react late. I mean, freezes when the human hit the ball. This may especially happen if the human hit the ball with the edges.
Intentional going slow would be unrealistic. But sometimes the computer may go a little bit slower while defending a ball that would bounce.
The computer may plain react to wrong side (for example, go up instead of down) when the ball hit with the middle of the bat.
The computer may wait a ball at the wrong place (off by 1), especially if the ball would bounce.

When you use Sleep the whole program stop for some milliseconds.
Do you have a game loop ? If so, try decreasing the translation amount, and do not forget to normalize
the acceleration vector.
cpuPadlle.Position += amount * acceleration;
Where :
amount in [0..1]
acceleration is a 2d
vector

Related

Pepper right shoulder pitch wont respond in timeline ir inspector

I'm trying to make some reach-grasp trajectories in timeline. They work fine with the virtual robot. On the real Pepper, sometimes they execute fine, then, next try, the right arm doesnt move in the complete trajectory. If I then use the inspector to move the right shoulder pitch, it gets stuck around 50°.
I wonder if there is some stiffness, or force, parameter: it is as if the robot does not have the strength to make the movement.
You may debug the hand movement with a simple command line Python script that we have made for us. See https://nlp.fi.muni.cz/trac/pepper/wiki/SetArmPosition with a link to souce code.
Pepper has barely the strength to lift its arms when stretched.
When it does so, these motors get hot, and the power fed to them is reduced, to the point where the motion cannot be performed.
Prefer more complex motion, that requires less instantaneous strength to perform, for instance by using a bit of the roll motion, and by stretching the arms only at the last moment.

Writing an efficient game-loop

I have recently asked a question here about programming a game so it will be efficient and won't lag.
I have made a game that lags like hell. I suspect that the way that I programmed it's game-loop, could be the source of the problem.
I want to describe to you in general the situation in my game, and then present my way of programming it's game loop.
It's a game for two players. Each player controls a tank. Each tank can shoot missiles. Each tank can collect 'gifts' from the field.
Each missile of tank1 can collide with tank2, and each missile of tank2 can collide with tank1.
Each missile can collide with a boundary of the screen.
Each tank can collide with the other tank.
Each tank can collide with 'gifts'.
All missiles constantly move.
Tanks move when specific buttons on the keyboard are pushed.
My game loop (Each stage is inside a method called from the game loop):
Loop through all the missiles on the screen, and update their location (move them).
Loop through all of tank1's missiles, and for every one check if collides with tank2.
Loop through all of tank2's missiles, and for every one check if collide with tank1.
Loop through all the missiles on the screen, and check if collide with screen boundaries.
Check if specific keys are pressed on the keyboard. If so, move tanks.
Check if the two tanks collide.
Loop through all of the 4 'gifts' on the screen, and check if they touch a tank.
Questions:
This game-loop is probably inefficient. How inefficient is it? A little, or a lot?
How can I improve the game loop and/or the way it's methods work? How can I achieve the same thing, more efficiently?
How likely is it for a game-loop to be the main cause for poor performance level? How common is it in games for this to be the source of the problem?
Appreciate your help.
I wouldn't necessarily say it's inefficient since you're just giving us the general idea of what might be done in several other games. It sounds like all you're doing is moving objects and checking for collisions, which I'm assuming uses AABB collision detecting. Nothing really expensive here. Of course it has room for improvement. See #2.
You're probably getting input more than once, so what you could do is get the input at the beginning of each frame and store it in some way. I don't know what form of input you're using, but if you're using a keyboard for example, you'd get and store the state of the WASD keys and check those states when handling tank input.
The most notable optimization you could make is you loop through every missile 3 times. The first time is to move them, the second to check their collisions, and the third time to check if they are outside the screen. In one loop, you can move them, check if they're outside of the screen, and then check if they collide with the opposing tank. I recommend doing it in this order, because if the bullet does happen to move outside the screen you can avoid doing an unnecessary collision check.
Finally, you only have to check if the two tanks collide when they move, and you only have to do it once. If you need it so something happens for every frame the two tanks are on top of each other, you can store the state of the collision and you only need to update it again when one tank moves.
It really depends. You're probably locking the frame rate by sleeping, so you could be sleeping for too long. Try to remove your method of frame rate limiting and seeing what happens.

Is there a random factor in AwayPhysics, or in physics engines generally?

Let's say I throw a cube and it falls on the ground with 45, 45, 0 rotations (on it's corner). Now in a 'perfect' world, the cube wouldn't consist of atoms, and it would be 'perfect', there would be no wind (or any lesser movement of air) etc. And in the end the cube would stay on it's corner. But we don't live in such a boring 'perfect' world, and the physics emulators should take this into account and they do quite nicely. So the cube falls on it's side.
Now my question is, how random is that? Does the cube always fall on it's left side? Or maybe it depends on Math.random()? Or maybe it depends on current time? Or maybe it depends on some custom random function, that takes not time, but parameters of objects on stage, as it's seed?
Why I am making this question is, that if the randomness wasn't based on time, I probably could cache results of collisions (when objects stop) for their particular initial position to optimize my animation? If I cached the whole animation, I wouldn't care, but If I only cached the end result, I could be surprised that two exactly same situations can evaluate to different results and then the other wouldn't fit my cached version.
I could just check the source for Math.random functions, but that would be a shallow method, as the code is surely optimized, and as such sophisticated randomization isn't needed there, I personally would use something like fallLeft = time % 2. Also, the code could change with time.
Couldn't find anything about AwayPhysics here, so probably it's something new for everyone - that's why I added the parentheses part; the world won't explode if I'll assume one thing and it happens that in AwayPhysics it's opposite, just what's the standard?
I, personally, don't use pre-made physics engines. Instead, when I want one, I write it myself, so I know how they work inside. The reason that the cube tips over is because the physics engine is inaccurate. It can only approximate things like trig functions, square-roots, integrals, et cetera, so instead it estimates them to a few digits of accuracy (15 in Javascript). If you have the case of, say, two perfect circles stacked on top of each other, the angle between them (pi/2) would slowly change to some seemingly random value based on the way the program was approximating pi. Eventually, this tiny error would grow as the circles rolled off of each other, and the top one would just fall. So, in answer to your question, the cube should fall the same way each time if thrown in the same way, but the direction in which it always fell would be effectively random.

Hourglass visualization algorithm

How can I program hourglass behavior (similar like on picture) for my game?
Should I make something like gravitation and process each grain of sand?
What about digital hourglass (like on this clocks)?
Wasting effort on a "proper" simulation for grains of sand for the sake of an in-game hourglass is serious over-engineering.
Get an artist to produce a high-quality animation and either render it as a series of static images or as a movie.
Seriously, don't simulate the sand.
Tangentially, you can model falling sand with cellular automata. I'd not considered using it for an hourglass simulation, but in principle it might work quite nicely, and be a fun project.
Looking at your digital hourglass -- either the grains move in set patterns, or it might use something like this CA.
Modelling it is making a rod for your own back, you'd be better off just drawing the frames by hand and playing them back.
But -- if maths is your thing you could:
work out the volume of sand in the top.
define a rate of volume flow through the neck (keep this arbitrary as you'll want to tweak it).
at any given time you can use the flow rate to work out how much sand has left the top.
if you know the shape of the top vessel you can work out the current height of sand given the current volume of sand.
if you know the shape of the bottom vessel you can work out the current height of sand given the volume of sand that's flowed through the neck.
I will play devil's advocate here and assume you actually want to simulate sand in your game not just create a simple hour glass loading indicator (as people have said it would be a waste of effort).
So I go back to my initial comment. What kind of resolution are you looking for?
Chances are you don't need to simulate each granule of sand. So keep it simple and leave the physics out of it and just simulate the effect.
For example, off the top of my head you can use 3 simple rules:
Gravity: If the pixel below a "sand pixel" is empty shift that column down.
Cave In: If there is a empty space between two columns of "sand pixels" fill it in if the space below it is not empty (ie. not falling)
Pile Up: if there is empty space beside a column of "sand pixels" spread it out if the space below it is not empty.
These are just some example of rules that might work. The point is to experiment to come up with a simulation that will give the desired effect. Typically it is less work and processor intensive than modeling the physics.

Pong: How does the paddle know where the ball will hit?

After implementing Pacman and Snake I'm implementing the next very very classic game: Pong.
The implementation is really simple, but I just have one little problem remaining. When one of the paddle (I'm not sure if it is called paddle) is controlled by the computer, I have trouble to position it at the correct position.
The ball has a current position, a speed (which for now is constant) and a direction angle. So I could calculate the position where it will hit the side of the computer controlled paddle. And so Icould position the paddle right there. But however in the real game, there is a probability that the computer's paddle will miss the ball. How can I implement this probability?
If I only use a probability of lets say 0.5 that the computer's paddle will hit the ball, the problem is solved, but I think it isn't that simple.
From the original game I think the probability depends on the distance between the current paddle position and the position the ball will hit the border.
Does anybody have any hints how exactly this is calculated?
Quoting from the very enjoyable book "Racing the Beam" (Google Books: http://books.google.co.uk/books?id=DqePfdz_x6gC&lpg=PP1&dq=racing%20the%20beam&pg=PA40#v=onepage&q&f=false) the original technique was:
To help simulate the human error inherent in precise paddle positioning, The AI paddle skips its adjustment every eight frames. The resulting behaviour is visibly unnoticeable, but it allows the computer player's aim to drift enough that it occasionally misses the ball. It is also technically trivial to implement, requiring only a single mask and the binary AND operation, for which there exists a corresponding 6502 instruction. The programmer can test if the result is zero with another single opcode, branching if needed to skip the instructions that move the paddle.
Even this behaviour must be modified slightly for the game to work at all. If the AI player simply stopped tracking the ball every eight frames, it would be hopelessly out of sync within a few seconds. To prevent this, the AI follows a secondary ball-tracking scheme near the top and bottom of the playfield. If the ball collides with one of these walls while the paddle is also aligned with it, the paddle readjusts, recovering from any drift that had accumulated since the ball last struck the wall. The result is a stochastic misalignment and realignment of computer paddle and ball.
We made a (pseudo-)3D ping-pong game for our high school CS class. What we did was, we made the computer always move the paddle toward the ball, but with a maximum speed -- that way, it could miss the ball if it's too far, but it's still smart. Does this help?
I would think you should have the paddle always move from its current position to a specific point, which would be where the ball is expected to align vertically with the paddle. You could then have a 50% chance that the paddle will move to this exact point and deflect the ball, a 25% chance that it will overshoot, perhaps by some X pixels, and 25% chance that it will undershoot. An even better way to do it might be to have it move to that position on a bell curve so that it misses by different amounts each time.
Other answers discuss how to decide the correct direction to move in in different circumstances. You can also add a lag time before the computer player "reacts" by starting to move in this direction -- that mirrors the typical response of human players.
I'm not sure what the 'official' way to do this is, but I've always just used (pseudocode)
if (ball is above paddle) {
move paddle up
}
if (ball is below paddle) {
move paddle down
}
Then I gave the paddle a slightly varying speed that was slow enough that it couldn't always keep up with the ball. Kind of crude, but it works.
This thread also has some interesting ideas you might want to look at: http://www.gamedev.net/community/forums/topic.asp?topic_id=439576
It just so happens I wrote a pong clone the other day just for fun.
You can play it here and view the source code here.
The AI takes the ball's current speed and multiplies the x-distance away from the wall. It then moves towards that calculated position at a capped speed. It doesn't account for vertical bounces, but that's sort of intended (to make the AI beatable).
Here is the relevant snippet:
/* Update enemy based on simple AI */
enemy.update = function (delta) {
var impactDistance, impactTime, targetY, speed;
speed = .25; // a little slower than the human player
if (ball.vx < 0) {
// Ball is moving away, AI takes a nap ..
return;
}
// Figure out linear trajectory ..
impactDistance = width - ball.width - ball.x;
impactTime = impactDistance / (ball.vx * .25 * 1000);
targetY = ball.y + (ball.vy * .25 * 1000) * impactTime;
if (Math.abs(targetY - (this.y + this.height/2)) < 10) {
// AI doesn't need to move
return;
}
if (targetY < this.y + (this.height / 2)) {
// Move up if ball is going above paddle
speed = -speed;
}
this.y += speed * delta;
this.keepInBounds();
};
after several iterations, if your paddle (that is yours or the AI's depending on your perspective) is too close to the top or bottom of the screen it is simply impossible to cover the distance required. The paddle can easily just follow the y-value of the ball. If you are too far you'll miss.
Alternatively, you can have the AI reset to center after each hit, or travel toward the center as long as the ball is moving away (i.e. toward the opponent)
Or more briefly:
- move toward the center while the ball is moving away
- imitate y-coordinate of ball while it is approaching.
from here you can change the difficulty by making the y-coord imitation mechanism slower than the ball (more consistent, and probably what the original implementation was like; as difficulties are abstracted into simple speed coefficients), or adding random error to each movement or otherwise.

Resources