Skip to content

Instantly share code, notes, and snippets.

@meijeru
Created March 8, 2016 11:04
Show Gist options
  • Save meijeru/00c1693a00418481b90b to your computer and use it in GitHub Desktop.
Save meijeru/00c1693a00418481b90b to your computer and use it in GitHub Desktop.
Red [
Title: "Tile game with randomizing"
Purpose: {An implementation in Red of the 4x4 sliding tile puzzle
with random start configuration
}
Author: "Rudolf W. MEIJER (meijeru)"
File: %tile-game-2.red
Needs: 'View
Usage: {
Click Random to obtain initial configuration.
Click on any tile that is adjacent to the empty space
and it will shift to that space.
Try to obtain the final configuration: 1 to 15 in order.
}
Note: {
See also http://www.tilepuzzles.com.
For the theory behind the is-even test see
https://en.wikipedia.org/wiki/15_puzzle.
Original R2 code (with helpful comments) found in
http://re-bol.com/rebol.html#section-6.3
(thanks Nick Antonaccio!).
The additions for randomizing are mine.
}
]
;---|----1----|----2----|----3----|----4----|----5----|----6----|----7----|-
pieces: ["1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15"]
is-even: func [
{Checks if a permutation is even or not
i.e. if it is produced by an even number of swaps}
perm [block!] "the permutation to be studied"
orig [block!] "the original series"
/local nsw cperm idx
][
nsw: 0
cperm: copy perm
repeat n length? perm [
idx: index? find cperm orig/:n
nsw: nsw + absolute idx - 1
cperm: head remove at cperm idx
]
even? nsw
]
randomize: has [rp i] [
until [
rp: random copy pieces
is-even rp pieces
]
repeat i 15 [
win/pane/:i/text: rp/:i
]
]
view win: layout/tight [title "Tile game"
style piece: button 60x60 [
unless find [0x60 60x0 0x-60 -60x0] face/offset - empty/offset [exit]
temp: face/offset face/offset: empty/offset empty/offset: temp]
piece "1" piece "2" piece "3" piece "4" return
piece "5" piece "6" piece "7" piece "8" return
piece "9" piece "10" piece "11" piece "12" return
piece "13" piece "14" piece "15" empty: piece "" return
button "Random" 120x40 [randomize]
button "Quit" 120x40 [quit]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment