Inform7: Change a room's description depending on where the player came from - inform7

I'm pretty new to Inform and it seems like this shouldn't be too hard to do but I haven't yet found a way. I want to change a room's description based on where the player came from. Something along the lines of:
The Town Square is a room. "As you enter the small town square, [if yourself came from West]
the rising sun makes silhouettes of the roofs and spires to the East.[otherwise]your long
shadow strides before you as the Sun rises behind.[end if]"
What's the best way to go about this?

I found a reasonable solution:
The last location is a room that varies.
Orientation is a direction that varies.
Before going to anywhere, now the last location is the location of the player.
After going to anywhere:
now orientation is the best route from the last location to the location, using even locked doors;
continue the action.
The Town Square is a room. "As you enter the small town square, [if orientation is east]
the rising Sun makes silhouettes of the roofs and spires to the East.[otherwise if orientation is west]
your long shadow strides before you as the Sun rises behind.[end if]"
The "using even locked doors" modifier ensures this will work even if a door closes and locks behind the player. The solution does assume that the player has come via a reversible route, which may not always be the case e.g. if the player has teleported.

Related

Computing Checkmate Correctly

When computing checkmate for a king in chess, do you determine the other players possible moves against your king? Or do you consider merely their unit's reach? If you say it's the former, then there is a contradiction like "this statement is false" Consider this image with two kings a square apart and their knights protecting from above rooks. If we assume that the definition of possible moves must prevent check based on enemy possible moves, then the logic recursively alternates.
First, we say that our king is in check from the enemy knight so we are limited from moving our own knight because we must escape.
Then we realize that the knight does not have an available move into our king's square because he will be placing his king in check with our rook. He does not have our king in check after all.
Then we realize, free from check, that we are now able to move our own knight to the enemy king forcing him to move from check and preventing further his choices.
However, we notice that we cannot do this because it will place us in check with the enemy rook.
We realize that since we cannot actually move our knight, the enemy king is not actually in check, therefore he is freely able to use his knight to attack our king.
Go to step 2 (no matter how many times you have already).
Okay, so maybe we assume that reach always counts regardless of the enemy's check status. If our king is in reach of the enemy knight's usual attack range, we consider it a check and must resolve it. Is this how the actual game is ruled though? It seems an easy solution to the problem faced when programming the game logic, but I'm not sure if it is correct or not.
I did some thinking and came up with this analysis:
I think you have proven that the scenario of both kings being in check (not necessarily the scenario of the board I showed) cannot exist by contradiction.
Only one player can make a move at a time.
Therefore, one player makes the initial move which transitions from the state of no kings being in check to some king(s) being in check.
According to the rules, this move is not allowed if that player's king results is in a check. (I will point out the significance of 'results' soon)
This means that no matter how check is defined, he cannot make any move if his king meets that condition.
Therefore, the only transition to checks from no checks is to the enemy being in check.
The enemy must escape check, still following the rule of not entering check in one move.
The remaining state would be game over or that king escaping check.
So I understand that both kings being in check is not possible.
Now the board I showed is either reachable or not reachable.
Let's assume the board is reachable and see if there is a contradiction.
Let's ambiguously assume it's white's turn since the scenario is symmetric.
This means black just moved.
Therefore, black's king is not in check.
The black king is only reachable by the white knight.
Therefore, the white knight must be restricted by some rule to not attack the black king.
The only two possible rules that can enforce that conclusion are:
The white knight is currently protecting his king from check.
The white king is in check already and that move will not solve the check.
First, assume 2 is true regardless of 1.
The white king is in check and the only piece in attack range is black knight.
The black knight cannot attack the square containing king, however, because it would place his own king in check.
Therefore 1 must be true and the white king is not in check.
So both kings are not in check.
We reverse the game board to see if this is reachable.
Assume the scenario with the following alterations:
White has a bishop 2 up and 1 right from the black rook.
The black king is one square to the left.
The white king is one square to the right.
No kings are in range of any other pieces, so it may be reasonable to assume this initial state is reachable.
The black knight is protecting his king from the bishop, so it cannot move to under the white knight.
The white king moves left.
Now the white knight is protecting the white king and cannot move to under the black knight.
The black king moves right one square.
Thus, the scenario is reachable.
The only questioned assumption standing is that when any moves are considered, it is safe to assume that the check rules are computed. Thus, a king may come in range of a unit which may not attack it due to prevention of his own king being in check. If this assumption is not made, then the pieces simply could follow the rules of not allowing kings to enter the unrestricted attack range of an enemy unit.
Now, it is interesting to see if this scenario is computable without infinite loops.
For dependencies, I will use arrows.
For the initial white king moving left,
white king -> black knight stopped -> white bishop attack black king
Those are single step computations, no loops in dependencies so far.
For the black king to move right,
black king -> white knight stopped -> black rook attack white king
Still no dependencies.
What about when we now try to check white knight's available moves including attacking the black king?
white knight stopped -> black rook attack white king
What about if the white rook attacks the black rook?
white rook stopped -> black knight attack white king
White's remaining options are to move the king to the right or down.
Our conclusion,
Moving to this board state is possible without breaking the 'don't move into check' rule.
This board state obviously assumes that computing check depends on possible enemy moves, not their simple native attack ranges.
When this state is reached, both kings are not in check.
It is at least possible that this is not a stalemate. (Unknown if always)
So I finally found rules on wikipedia about placing another king in check even if it compromises one's own king. So, we cannot make our assumption in part 2, thus the board state is not reachable.
"A piece unable to move because it would place its own king in check (it is pinned against its own king) may still deliver check to the opposing player."
Thus our final conclusion for the apparent actual rules of chess, the board state is not reachable as it follows the check rules.
I am going to choose icedtrees answer because of the valuable logic which follows the game rules:
if for every move for player X (ignoring rules about king threats),
player Y can capture player X's king next turn,
then player X is in checkmate.
However, I would fix them to be the following:
{X is checkmate}
if and only if {
For all legal moves:(move according to rule definition) X {
There exists a generic move:(legal move A ignoring rules of protecting king A) Y such that {
X king is captured
}
}
}
I may be misunderstanding, but I think your problem is easily fixed by noting that it is only possible to be in check if it is your own turn. Check in chess is associated strongly with a compulsion to defend the check, and you cannot do that if it is not your turn.
For any chess position, it is VERY IMPORTANT to define whose turn it is, because that lies behind so many mechanics in the game. In your board position, if it is black's turn, then black is in check, and if it is white's turn, then white is in check.
Even if the position is impossible, you can still define some good rules about positions that are good for chess computations.
Some notes on checkmate in chess:
Checkmate is actually not very intuitive, and when you play the game you start to notice funny checkmate situations that do not make much sense.
Here is a good way of thinking about checkmate, in my opinion:
In a legal chess game, when checkmate occurs, the checkmated player is unable to prevent his king being captured the successive turn by the opposing player. That is, checkmate in chess is nothing but "ending the game one turn early", so to speak. If you ignore all rules in chess about threats to the king, but preserve the movement patterns of the pieces, a computer could calculate checkmate by looking forward.
The logic would be as follows:
if for every move for player X (ignoring rules about king threats), player Y can capture player X's king next turn, then player X is in checkmate.
Here is a more complete version of "check and escaping check":
Given it is player X's turn:
if player X's king is in movement range of player Y's piece, it is in check. If the piece cannot escape check, it is checkmate.
There are three ways of escaping check:
Moving your king to a non-attacked square
Blocking the piece(s) delivering check
Capturing the checking piece.
Maybe you're over-thinking this :-)
Here's the algorithm from a working chess program that's relatively strong in human terms:
Generate the list of pseudo-legal moves for the side to move. By pseudo-legal, I mean don't bother to verify whether the generated move leaves that side's King in check. Omitting this verification can save time validating moves that are never searched.
For each move that is searched, validate that it doesn't leave the side to move in check.
If every move leaves the King in check, then the side to move has either been mated or it's stalemate.
If the side to move is currently in check, then it's mate. Otherwise it's stalemate.
My naïve approach would probably go like this.
player.startTurn();
if (player.isInCheck()
if(player.king.hasNoLegalMoves() && player.cannotProtectKing())
game.checkMate(player);
function isInCheck() {
boolean isInCheck = false;
for (Piece p : player.Opponent)
if (p.canAttack(player.king) {
isInCheck = true;
return;
}
I may be missing something here, but I don't understand why it wouldn't be this simple.
For one thing, this board position isn’t even REMOTELY possible.
1) How did you get the rooks and kings off the first and eighth ranks without moving any pawns?
2) Check is defined as the state where your king is under attack by an opposing piece. CheckMATE is the situation where you are in check and cannot legally get out of check.
3) If it’s your turn and one of your pieces is capable of capturing the opponent’s king, it doesn’t matter if you would put yourself in check to do so: it’s whose king would die first?
4) Notwithstanding that, if it’s your turn and your opponent is in check, it either means neither player noticed that your opponent was in check (in which case you go back and make sure they can—and do—get out of check before you do anything else) or that nobody noticed that it was checkmate.
So, when it’s your turn you can’t finish in check, but when determining a threat to the king, the opposing king’s safety is irrelevant.

A* Pathfinding - closest to unwalkable destination

I already have an A* Implementation that works. The problem is that if you pick a destination that is unwalkable, no path is returned. I want to be able to get the 'closest' I can get.
The preferable option would be completely dynamic (not just checking the 8 tiles around the destination to try to find one). That way, even if they click an unwalkable tile surrounded by a huge square of unwalkable tiles, it will still get as close as it can.
While the simple answers provided here MIGHT be sufficient enough, I think it depends on your game type and what you're trying to achieve.
For example, take this play field (sorry I'm reusing the same software I used to show you the fog of war :)) :
As you can see, an Angry Chicken is blocking the path between the left side and the right side. The Angry Chicken could be anything... if it's a static obstacle, then going with the lowest h node might be enough, but if it's a dynamic object (like a locked door, draw bridge, etc...) the following examples might help you find out how you want to solve your problem.
If we set the destination for our Hero on the other side
We need to think what we want the path to be, since obviously we can't reach it. Using a standard heuristic like manhattan distance or euclidian distance, you will get this result:
Which might be good enough, but if there's any way our little Hero could interact with the chicken to pass, it doesn't make sense at all, what you want is this
How can you do this? Well, an easy way to do this is to pathfind on hierarchical graphs. This sounds complicated but it isn't. First, you want to be able to build a new set of high level nodes and edges that will contain multiple grid nodes (or other representation, wouldn't change a thing)
As you can see, we now have a right blue node and a left red node. The arrow represents the edge between the two nodes. How to build this graph you ask? It's easy, simply start from an open node, expand all of its neighbors and add them to a high level node, when you're done, open the dynamic nodes that could lead to another part of the graph and do the same.
Now, when you ask for a path from our Hero to the red X, you first do the pathfinding on the high level... is there a way from blue node to red node? Yes! Through the chicken.
You can now easily know how to navigate on the blue side by going to the edge that will allow you to cross, which is the chicken.
If it was just a plain wall, you could determine very quickly, by visiting a single node, that there is NO way to reach on the other side and then handle it the way you want, possibly still performing an A* and returning the lowest h node.
You could keep a pointer which holds a tile with the lowest h-value, then if no path is returned simply generate a path to the tile you're holding onto instead.

Collision reaction in a 2D side-scroller game similar to "Mario"

This has been greatly bothering me in the past few weeks. In this time I've been researching online, even reading books in the Computers section at Borders to try to find an answer, but I haven't had much luck.
I programmed a 2D level editor for side-scroller video games. Now I want to turn it into a game where I have a player who can run and jump to explore the level, similar to "Mario".
The thing that is really giving me trouble is the collision response (not detection: I already know how to tell if two blocks are colliding). Here are some scenarios that I am going to illustrate so that you can see my problems (the shaded blocks are the ground, the arrow is the velocity vector of the player, the dashed lines are the projected path of the player).
See this collision response scenarios image:
http://dl.dropbox.com/u/12556943/collision_detection.jpg
Assume that the velocity vectors in scenarios (1) and (2) are equal (same direction and magnitude). Yet, in scenario (1), the player is hitting the side of the block, and in scenario (2), the player is landing on top of the block. This allows me to conclude that determining the collision response is dependent not only on the velocity vector of the player, but also the player's relative position to the colliding block. This leads to my first question: knowing the velocity vector and the relative position of the player, how can I determine from which direction (either left side, right side, top, or bottom) the player is colliding with the block?
Another problem that I'm having is how to determine the collision response if the player collides with multiple blocks in the same frame. For instance, assume that in scenario (3), the player collides with both of those blocks at the same time. I'm assuming that I'm going to have to loop through each block that the player is colliding with and adjust the reaction accordingly from each block. To sum it up, this is my second question: how do I handle collision response if the player collides with multiple blocks?
Notice that I never revealed the language that I'm programming in; this is because I'd prefer for you to not know (nothing personal, though :] ). I'm more interested in pseudo-code than to see language-specific code.
Thanks!
I think the way XNA's example platform game handles collisions could work well for you. I posted this answer to a very similar question elsewhere on Stack Overflow but will relay it here as well.
After applying movement, check for and resolve collisions.
Determine the tiles the player overlaps based on the player's bounding box.
Iterate through all of those tiles doing the following: (it's usually not very many unless your player is huge compared to your world tiles)
If the tile being checked isn't passable:
Determine how far on the X and Y axes the player is overlapping the non-passable tile
Resolve collision by moving the player out of that tile only on the shallow axis (whichever axis is least penetrated)
For example, if Y is the shallow axis and the collision is below, shift the player up to no longer overlap that tile.
Something like this: if(abs(overlap.y) < abs(overlap.x)) { position.y += overlap.y; } else { position.x += overlap.x; }
Update the bounding box's position based on the player's new position
Move on to the next tile...
If the tile being checked is passable, do nothing
If it's possible that resolving a collision could move the player into another collision, you may want to run through the above algorithm a second time. Or redesign your level.
The XNA version of this logic is in player.cs in the HandleCollisions() function if you are interested in grabbing their code to see what they specifically do there.
So what makes this a little more tricky is the constant force of gravity adjusting your players position. If your player jumps on top of a block they shouldn't bounce off they should land on top of the block and stay there. However, if the player hits a block on the left or right they shouldn't just stay there gravity must pull them down. I think that's roughly your question at a high level.
I think you'll want to separate the two forces of gravity and player velocity from collision detection/response algorithm. Using the velocity of the player if they collide with a block regardless of direction simply move the player's position to the edge of the collision, and subtract equal and opposite vector from the player's velocity since not doing this would cause them to collide yet again with the object. You will want to calculate the intersection point and place the player's position there on the block.
On a side note you could vary that really big force by what type of block the player collided with allowing for interesting responses like the player can break through the block if they are running fast enough (ie the player's velocity > than the force of the block)
Then continue to apply the constant force gravity to the player's position and continue doing your normal calculation to determine if the player has reached a floor.
I think by separating these two concepts you have a really simple straight forward collision response algorithm, and you have a fairly simple gravity-floor algorithm. That way you can vary gravity without having to redo your collision response algorithm. Say for example a water level, space level, etc and collision detection response is all the same.
I thought about this for a long time recently.
I am using the separating axis theorem, and so if I detected a collision I proceeded to project the object onto the normalized velocity vector and move the object by that distance in the direction of the negative velocity vector. Assuming the object came from a safe place this solution will position the object in a safe place post collision.
May not be the answer you're looking to get, but hopefully it'll point you in the right direction?

Image capturing continuously

I am a final year student making a project in which I take a image from camera placed at car and my objective is through image processing on Matlab. I have to take image of different colour ball until my desired image (which is red) comes and the car stop through micro controller. How can I continuously take a image of ball with millisecond time delay?
The For-A VFC-1000SB High Speed -- only about $12k :-)
However, on the "cheap" end there is the Exilim line (e.g. EX-F1). One of the features is a movie mode up to 1200fps. Note that as the fps goes up the resolution goes down. I know nothing more about this other than the adverting. YMMV.
Now, even if the camera can take frames at this speed, getting it to the host and processed "somewhat timely" is unlikely without additional specialty hardware (and I doubt it is doable at all with the Exilim).

How to fade out volume naturally?

I have experimented with a sigmoid and logarithmic fade out for volume over a period of about half a second to cushion pause and stop and prevent popping noises in my music applications.
However neither of these sound "natural". And by this I mean, they sound botched. Like an amateur engineer was in charge of the sound decks.
I know the ear is logarithmic when it comes to volumes, or at least, twice as much power does not mean twice as loud. Is there a magic formula for volume fading? Thanks.
I spent many of my younger years mixing music recordings, live concerts and being a DJ for my school's radio station and the one thing I can tell you is that where you fade is also important.
Fading in on an intro or out during the end of a song sounds pretty natural as long as there are no vocals, but some of these computerized radio stations will fade ANYWHERE in a song to make the next commercial break ... I don't think there's a way to make that sound good.
In any case, I'll also answer the question you asked ... the logarithmic attenuation used for adjusting audio levels is generally referred to as "audio taper". Here's an excellent article that describes the physiology of human hearing in relation to the electronics we now use for our entertainment. See: http://tangentsoft.net/audio/atten.html.
You'll want to make sure that the end of the fade out is at a "zero crossing" in the waveform.
Half a second is pretty fast. You might just want to extend the amount of time, unless it must be that fast. Generally 2 or 3 seconds is more natural.
More on timing, it should really be with the beat rate of the music, and end at a natural point in the rhythm. Try getting the BPM of the song (this can be calculated roughly), and fading out over an interval equal to a whole or half note in that timing.
You might also try slowing down the playback speed while you're fading out. This will give a more natural vinyl record or magnetic tape sounding stop/pause. Linearly reduce playback speed while logarithmically reducing volume over the period of 1 second.
If you're just looking to get a clean sound sound when pausing or stopping playback then there's no need to fade at all - just find a zero-crossing point and stop there (or more realistically just fill the rest of that final buffer with silence). Fading out when the user expects the sound to stop immediately will sound unnatural, as you've noticed, because the result is decoupled from the action.
The reason for stopping at a zero-crossing point is that zero is the steady state value while the audio is stopped, so the transition between the two states is seamless. If you stop playback when the last sample's amplitude is large then you are effectively introducing transients into the audio from the point of view of the audio hardware when it reconstructs the analogue signal, which will be audible as pops and/or clicks.
Another approach is to fade to zero very fast (~< 10mS), which effectively achieves the same thing as the zero-crossing technique.

Resources