Tetravex solving algorithm - vb.net

Well, i was thinking of making a Tetravex solving program in order to practice my code writing skills (language will propably be Visual Basic) and I need help finding an algorithm for solving it. For those that don't know what tetravex is see this http://en.wikipedia.org/wiki/TetraVex . The only algorithm I can come up with is the brute force way, place a tile randomly in one corner and try every possible tile next to it and continue the same process, if it reaches a dead end revert to a previous state and place a different tile. So can anyone come up with a better algorithm? Thank you for your time.

here some ideas.
A vanilla brute force algorithm would try to fill out the grid recursively by enumerating the grid positions in a fixed order (e.g. row major) and always trying to fit every possible piece in the current position and then recursing. This is what you mentioned and it is very inefficient.
An improvement is to always count for every free position the number of pieces that fit there, and then recurse on the position that has least fits; if one has zero fitting pieces, backtrack immediately; if there is one where only one piece fits fill that and continue (no branch created); otherwise select the one that has least fitting pieces (≥ 2) and continue from there.
Once you have this algorithm in place, the next question is how you can prune the search space more. If have, say, A pieces with "1" on the top position and B pieces with "1" on the bottom position, and A > B, then you know that at least A - B of the "1 at top position" pieces must be actually placed on the top row, so you can exclude them from any other position. This helps to reduce the branching factor and to spot dead-ends earlier.
You should also check at every recursion step that every piece has at least one spot where it fits (do this check after verifying that there is no piece that fits in only one place for speed). If there is a piece that doesn't fit anywhere you need to backtrack immediately. You can extend this to checking that every pair of pieces fits for a potentially better earlier dead-lock checking capability.
There is a also a strategy called "non-chronological backtracking" or "backjumping" which originates from research into SAT solving. This helps you to backtrack more than one level at a time when you reach a dead-end; if you want, you can google for these terms to find more, but you need to do some mental work to map the concept into your problem space.

A first improvement would be counting how many matching pairs of numbers there are, and if, say, there are 5 "1"'s on the top of squares, but only 4 on the bottom, then there must be a "1" pointing off the top of the grid.

At any given partly solved board I would
look for a place where none of the remaining tiles could be played. If found, the board must be unwound to the last place a tile was played randomly.
Look for a place where only 1 of the remaining tiles can legally be played. If found, place that tile.
Place a tile randomly at the spot on the board where the fewest number of remaining tiles can legally be played. Remember this board layout before I lay the tile, I may want to unwind back to this board and play a different tile.
In pseudocode it would be
top:
evaluate # of tiles that match at each empty square
if any square has 0 matches, unwind to <prev>
if any square has 1 match, lay tile, goto top
save current board as <prev>
play randomly at square with minimum number of matches, goto top
As an optimization, you can ignore evaluating squares that don't touch any squares that have tiles, since they will always allow all remaining tiles.

It looks like Tetravex is a Constraint Satisfaction Problem, so you want to limit your options as quickly as possible. It should be possible to do better than random placement. How about?:
Create links between all tile faces with their possible matches.
Any tile with an unlinked face must be an edge tile.
Any tile with two adjacent unlinked faces must be a corner tile.
Center tiles must have four active links.
Now, place a tile in a valid location and invalidate links that are used. If any un-placed tile contains three unlinked faces or unlinked faces on opposite sides, the move is invalid and you can backtrack.
You should be able to use tile face links to look for the next possible tile versus searching through all tiles. If there isn't one, backtrack.

I wrote a solver for Tetravex and used a different approach and it seems very efficient. I built up possible valid relationships increasing the size. So each iteration gives me larger puzzle pieces to work with while reducing the number of puzzle of pieces, so to speak.
I start by creating a list of all possible connections between tiles from bottom to top and a list of all possible connections between tiles from right to left.
From these two lists, I build a list of all possible valid 2x2 combinations.
Using the 2x2 list, I build a list of all possible valid 3x3 combinations.
From there I can go 4x4 by using the 2x2 and 3x3 lists, or do 5x5 by just using the 3x3 list.
Right now my code does each iteration separately, but should be able to be cleaned up to handle each iteration with the same code which would allow for larger grid sizes.
This also seems like a great situation for using a neural net, and I might give that a try next.

Related

Is there a visual programming language with a large/configurable stage resolution?

My 8-year-old daughter is learning to program, and was excited to create projects using Code.org. Now she wants to design a program that creates a Babylonian number chart, with numbers from 1 to 1000, but there is no way to render such a thing with any of the visual programming environments that I know of. I've looked at Hopscotch, Tynker, Scratch, so far to no avail. She does not yet type, so switching to a text based system is not yet an option, so I'm hoping that someone else knows of a good solution.
Snap! is a block-based programming language based on Scratch. It lets you configure the stage size:
Snap! also adds exciting functional programming features, such as anonymous functions and nested lists.
There's a tool for importing Scratch projects: https://djdolphin.github.io/Snapin8r2/
There are two difficulties in rendering such a chart in Scratch.
1) The screen size is too small.
2) There isn't an obvious way to render the basic characters of Babylonian numbers.
The small screen size is going to be a problem in any development environment, block-based or text-based. Even using an entire 1366 x 768 pixel display, she would only have a 30 pixel square for each number. Breaking up the chart into parts (10 pages of 100 numbers each, for instance) or rendering a single number based on user input are two possible work arounds for the screen size issue.
Both of these related projects (a smaller chart or a number converter) are possible in Scratch. Your daughter will need to create a renderer sprite which can draw the symbols on the stage. A renderer sprite can either have costumes of the Babylonian symbols and use the stamp block to create combinations, or the sprite can be draw the symbols with the pen. This project has some examples of renderer sprites and how they can be used.
The Babylonians used base 60. It appears that each numeral is composed of up to two unique sprites repeated and arranged in a base 10 paradigm.
You might want to consider an animated counter using Scratch.
At every tick of the clock, another right-hand "ones" sprite appears, and all disappear on the 10th tick).
At each 10th tick, another left-hand "tens" sprite appears (and all disappear on the 60th tick).
Then on the 60th ticks, a left-of-left numeral appears or updates in the 60th place.
To get to 1000 in base 60, you need only two numerals.
Somewhere else on the screen, a text field containing the decimal number tracks the ticks.
You could animate little Babylonians riding chariots around from ziggurat to ziggurat. (Sorry to any Babylonians if I'm making stereotypes.)
Sounds like fun, good luck.
There should be no difficulty implementing it in Scratch. But it's a big project at 8!
screen size: at 4 sprites per number, 1000 numbers, 4000 characters on screen is difficult. But that is one ugly chart to display statically anyway. You could use the dynamic characteristics of a computer display to zoom the sprites very small (fitting it all into one illegible table), or large enough but incomplete, and use the arrow keys to scroll through. This is a lesson in UI: computers don't have display the size of dining-room tables, but their displays are dynamic, so use that.
The conversion is a bit of a job.
first, get a set of images for numbers 1-9 and 10-60.
create two sprites - the first with the costumes for 1-9 images; the next for 10-60.
to show the correct image, use switch costume.
I recommend that you start with smaller numbers, first up to 9, then up to 59. After that, the generic solution would be to use stamping, then shift the sprites left, change costumes and stamp again.
to calculate the correct values given input X:
units = X modulus 10
X' = X/10-units
if your number is up to 59, that's it; X' is the number of the tens costume. If not:
tens = X' modulus 6
X'' = X'/10-units
Start again with X''. If you want a generic solution, stamp the sprites, shift them left and calculate. Otherwise, use X'' to calculate the correct costumes of two new sprites.
Pure Data is an open-source visual programming language with implementations for all the major operating systems.
This question is old but still interesting.
I think your daughter can use scratch to achieve the goal by using the "nextcostume" action associated with a sprite.
The Babylonins used base 60 meaning that we need a pair of 2 sprites to represent for 0-9 and 10,20,30,40,50,(6)0. Then we keep adding these pairs in front when the number grows larger than 59.
I did work out a poc within 30 min, including time I spent to cut/save/import the costumes.
I use the variable to show the Babylonian number count. The code is simple.
By the end, 1 tricky thing is the time sync between different sprites. To make it easy, I had to manually "adjust" the early pop by adding a sound.
You can cehck out my published project here.
https://scratch.mit.edu/projects/154836328/
Scratch project snapshots
Costume

Special Kind of ScrollView

So I have my game, made with SpriteKit and Obj-C. I want to know a couple things.
1) What is the best way to make scroll-views in SpriteKit?
2) How do I get this special kind of scroll-view to work?
The kind of scroll-view I'd like to use is one that, without prior knowledge, seems like it could be pretty complicated. You're scrolling through the objects in it, and when they get close to the center of the screen, they get larger. When they're being scrolled away from the center of the screen, they get smaller and smaller until, when their limit is met, they stop minimizing. That limitation goes for getting bigger when getting closer to the center of the screen, too.
Also, I should probably note that I have tried a few different solutions for cheap remakes of scroll views, like merely adding the objects to a SKNode and moving the SKNode's position relative to the finger's, and its movement . . . but that is not what I want. Now, if there is no real way to add a scroll-view to my game, this is what I'm asking. Will I simply have to do some sort of formula? Make the images bigger when they get closer to a certain spot, and maybe run that formula each time -touchesMoved is called? If so, what sort of formula would that be? Some complicated Math equation subtracting the node's position from the center of the screen, and sizing it accordingly? Something like that? If that's the case, will you please give me some smart Math formula to do that, and give it to me in code (possibly a full-out function) format?
If ALL else fails, and there is no good way to do this, what would some other way be?
It is possible to use UIScrollViews with your SpriteKit scenes, but there's a bit of a workaround involved there. My recommendation is to take a look at this github project, that is what I based my UIScrollView off of in my own projects. From the looks of it, most of the stuff you'd want has actually been converted to Swift now, rather than Objective-C when I first looked at the project, so I don't know how that'll fare with you.
The project linked above would result in your SKScene being larger than the screen (I assume that is why it would need to be scrolled), so determining what is and is not close to the center of the scene won't be difficult. One thing you can do is use the update loop in SpriteKit to constantly update the size of Sprites (Perhaps just those on-screen) based on their distance from a fixed, known center point. For instance, if you have a screen of width and height 10, then the midpoint would be x,y = 5,5. You could then say that size = 1.0 - (2 * distance_from_midpoint). Given you are at the midpoint, the size will be 1.0 (1.0 - (2 * 0)), the farther away you get, the smaller your scale will be. This is a crude example that does not account for a max or min fixed size, and so you will need to work with it.
Good luck with your project.
Edit:
Alright, I'll go a bit out of my way here and help you out with the equation, although mine still isn't perfect.
Now, this doesn't really give you a minimum scale, but it will give you a maximum one (Basically at the midpoint). This equation here does have some flaws though. For one, you might use this to find the x and y scale of your objects based on their distance from a midpoint. However, you don't really want two different components to your scale. What if your Sprite is right next to the x midpoint, and the x_scale spits out 0.95? Well, that's almost full-sized. But if it is far away from the midpoint on the y axis, and it gives you a y scale of, say 0.20, then you have a problem.
To solve that, I just take the magnitude or hypotenuse of the vector between the current coordinate and the coordinate of the current sprite. That hypotenuse gives me an number that represents the true distance, which eliminates the problem with clashing scale values.
I've made an example of how to calculate this inside Google's Go-Playground, so you can run the code and see what different scales you get based on what coordinate you plug in. Also, the equation used in there is slightly modified, It's basically the same thing as above but without the maxscale - part of the front part of the equation.
Hope this helps out!
Embedding Attempt:
see this code in play.golang.org

On-the-fly Terrain Generation Based on An Existing Terrain

This question is very similar to that posed here.
My problem is that I have a map, something like this:
This map is made using 2D Perlin noise, and then running through the created heightmap assigning types and color values to each element in the terrain based on the height or the slope of the corresponding element, so pretty standard. The map array is two dimensional and the exact dimensions of the screen size (pixel-per-pixel), so at 1200 by 800 generation takes about 2 seconds on my rig.
Now zooming in on the highlighted rectangle:
Obviously with increased size comes lost detail. And herein lies the problem. I want to create additional detail on the fly, and then write it to disk as the player moves around (the player would simply be a dot restricted to movement along the grid). I see two approaches for doing this, and the first one that came to mind I quickly implemented:
This is a zoomed-in view of a new biased local terrain created from a sampled element of the old terrain, which is highlighted by the yellow grid space (to the left of center) in the previous image. However this system would require a great deal of modification, as, for example, if you move one unit left and up of the yellow grid space, onto the beach tile, the terrain changes completely:
So for that to work properly you'd need to do an excessive amount of, I guess the word would be interpolation, to create a smooth transition as the player moved the 40 or so grid-spaces in the local world required to reach the next tile over in the over world. That seems complicated and very inelegant.
The second approach would be to break up the grid of the original map into smaller bits, maybe dividing each square by 4? I haven't implemented this and I'm not sure how I would in a way that would actually increase detail, but I think that would probably end up being the best solution.
Any ideas on how I could approach this? Keep in mind it has to be local and on-the-fly. Just increasing the resolution of the map is something I want to avoid at all costs.
Rewrite your Perlin noise to be a function of position. Then you can increase the octaves (and thus the detail level) and resample the area at a higher resolution.

"Find all tiles connected to this one" project

Remember MS Paint? The bucket tool? If you used it and clicked on a pixel, all pixels connected to this pixel that are the same are affected. The theory is, I suppose, to check if there is any pixel adjacent to the selected one. If such pixel is the same type as the selected one, check for more adjacent pixels in this one, and so on.
I want to implement something similar in VB.NET. Basically I have a 2D array map which represents the map. Let's assume there are only two types of tile: 0 and 1.
Now, I got pretty much everything ready: I got my 2d map and I can tell which tile is clicked and tell what array indexes are the ones that represent such tile.
Now for the "painting" process. Whenever I think about it, I can't figure a convenient way to execute such iteration. Can someone help me choosing a correct design/way/tip to achieve this?
The operation is called 'flood fill'. Possible algorithms and their implementations, there are several, are well described here.

Beat em' up game space management?

I am in the process of making my 2D engine for a Beat'em Up game (Castle Crashers is what I call Beat'em Up or Brawler kind of game ).
I will support 2D sprites and 2D particle emitters. This is all done in the engine now. But I have come to an issue that I would like to ask for advice:
It's about "space" management, what I thought was to do something as this image shows:
alt text http://img337.imageshack.us/img337/9162/spacingprototype1.png
My idea is to make a grid ( Spatial Hash or Grid ), of the ground where my Particle Emitters / 2D sprites will live. In my picture, I have enumerated this slots from 1 to N, (don't have to be 35, it's just for showing purposes ). My idea is to draw the "GameElements" (Sprites/Emitters) in order from 0 to N , ( going from bucket 0 to bucket N ) , so then I will get them to display correctly overlapped on screen (back to forward).
I know this could be done by just comparing the lower Y axis of each Element and performing a "quicksort" too, but having the Grid could allow me to perform Collision Detection in a better way , and if I do something like A* to implement some kind of AI, it could help me too.
If you want to have some sort of optimization for the number of objects you need to test against each other, you might want to think about using a Quadtree
http://en.wikipedia.org/wiki/Quadtree
The idea is to divide the screen up in 4 nodes, placing all items in the node they belong, then divide the nodes you just created up in another 4 if there are sprites/items/whatever in there that need to be tested. Keep doing this until a certain size or amount of items in a node has been reached.
You can then ask the top-node if it contains the item you want to test. This node will then ask the child-nodes if it contains the item, which in their turn will ask their children. This way a large part of the screen can be skipped already (if it's located in child 00, you can skip child 01, 10 and 11). Then you get a list of items you perform more specific collision detection on when it's desired to do so.
If you were to make it visual, it would look a bit like this:
alt text http://geodata.ethz.ch/geovite/tutorials/L2GeodataStructuresAndDataModels/en/images/quadtree.gif
Fire them out to the Z buffer and let that worry about it.
If you find that in the future it is too slow (via profiling obviously) then look at optimizing it.
Take the simplest solution and move on.
Your method fails if you have two sprites occupying the same box in the grid. Suppose you have two enemies both standing in the same box. One stands slightly in front of the other. Which do you draw first? You would need two algorithms - one which divides the sprites into the grid, and the second which looks at the z co-ordinates of all the sprites in a given grid box and draws them based on that value.
A far simpler method is to have a single collection of all sprites. It should store all sprites sorted by their z co-ordinates (from the back of the screen at the head of the list to the front of the screen at the back). Loop through the collection and draw each sprite as it appears. When a sprite moves into or out of the screen (ie. its z co-ordinate changes) you can perform a very simple sort to move that single sprite within the collection. Keep swapping it with the next sprite in the list until the next sprite's z co-ordinate is greater than/less than (as appropriate) the changed sprite's co-ordinate.