Puzzle!
Making games (even simple games) is a challenge. The creation process is not very difficult and may be fun of course if you know what you are doing (or writing). When I have a new idea I’m asking myself if I know how to do it. This is very important thing! I have to be sure if I know how to make the key elements of the code, before writing any line I must know the algorithm which will describe these elements. So I’m making a few tests, searching for solutions on the internet, in books, or trying to figure out by myself how to create it. And the last step is writing the code (hmm, someone could say that is the first step).
Today I want to present my new project based on YUI library and Flickr API. I think the title say everything - PUZZLE. Each photo which you can find by searching Flickr, is divided in sixteen pieces and placed on the square board. All pieces are randomly set and the last piece is empty. All you have to do, is to set the pieces in their correct places by swapping empty piece with near placed pieces.
The hardest thing while creating this game was figure out how to divide images into pieces using only JavaScript. CSS give us very helpful attribute called - “background-position“. If you have image with size, for example 640×480 pixels, and you want divide it into 16 squares you have to do something like this:
640 / 4 = 160;
480 / 4 = 120;
- .square1 { background-position: 0 0; }
- .square2 { background-position: 0 160px; }
- .square3 { background-position: 0 320px; }
- .square4 { background-position: 0 480px; } - the last square on the first line
- .square5 { background-position: 120 0; }
- .square6 { background-position: 120 160px; }
- .square7 { background-position: 120 320px; }
- .square8 { background-position: 120 480px; } - the last square on the second line
- .square9 { background-position: 240 0; }
- .square10 { background-position: 240 160px; }
- .square11 { background-position: 240 320px; }
- .square12 { background-position: 240 480px; } - the last square on the third line
- .square13 { background-position: 360 0; }
- .square14 { background-position: 360 160px; }
- .square15 { background-position: 360 320px; }
- .square16 { background-position: 360 480px; } - the last square on the fourth line
This technique works well on a small images (640×480 or less), you can use it also with the largest images, however the loading time will be longer (especially in IE).
Have a nice puzzling!
Web
Blog
News
Video
Wiki