Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sliding puzzle #1237

Merged
merged 11 commits into from
Jun 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
generate valid games
  • Loading branch information
kostmo committed Jun 16, 2023
commit 4274efaca0b0eac4002b5a31da276b5130aa5527
11 changes: 11 additions & 0 deletions data/scenarios/Challenges/_sliding-puzzle/design-commentary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Design

The objective is to arrange the tiles in ascending (row-major) order.

We want to generate a random game upon starting the scenario.
However, [not all](https://en.wikipedia.org/wiki/15_puzzle#Solvability) permutations of tiles avail themselves to a solution.

Assuming that the empty tile is initially in the lower-right position, the criteria for a solvable puzzle is that the number of "inversions" is even.

So, to guarantee solvability we can perform a random shuffle of tiles, count the inversions, and then make a single swap of adjacent tiles if necessary. Swapping adjacent tiles will either
increase the inversions by one or decrease by one, both of which invert the parity.
165 changes: 149 additions & 16 deletions data/scenarios/Challenges/_sliding-puzzle/judge.sw
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ def id = \t. t end
def elif = \t. \then. \else. {if t then else} end
def else = id end

def mod : int -> int -> int = \i.\m.
i - m * (i / m)
end

def isEven = \n.
mod n 2 == 0;
end

def sumTuples = \t1. \t2.
(fst t1 + fst t2, snd t1 + snd t2);
end;

/** Teleports to a new location to execute a function
then returns to the original location before
returning the functions output value.
*/
def atLocation = \newLoc. \f.
prevLoc <- whereami;
teleport self newLoc;
retval <- f;
teleport self prevLoc;
return retval;
end;

/**
Returns true if should terminate the parent
function's recursion due to goal being met.
Expand Down Expand Up @@ -277,11 +301,70 @@ def auditNeighbors = \depth.
};
end;

def observe = \boardWidth. \boardHeight.
def getIndexesTotal = \n.
if (n > 0) {
let idx = n - 1 in
teleport self (idx/4, -(mod idx 4));
valueHere <- getValueHere;

// This reassignment has to happen before the
// recursive call due to #1032
let valueHereBlah = valueHere in
runningTotal <- getIndexesTotal $ n - 1;
return $ valueHereBlah + runningTotal;
} {
return 0;
}
end;

/** If we iterate over all of the tiles, assigning each a contiguous index
starting with one, we can determine whether a single tile is missing
by subtrating the observed sum of indices from the expected sum.
*/
def findMissingIndex = \indicesSum.
mySum <- getIndexesTotal 16;
return $ indicesSum - mySum;
end;

def getLetterEntityByIndex = \idx.
let letter = toChar $ idx - 1 + charAt 0 "a" in
letter ++ "-tile";
end;

def teleportToDetectResult = \referenceLoc. \relativeLoc.
let newLoc = sumTuples referenceLoc relativeLoc in
teleport self newLoc;
end;

/**
If the player has "drilled" a location that doesn't make
sense to move, find it and restore it to its original value.

Preconditions:
* We have already attempted to move a "sensibly"-marked tile.
* We are located at the bottom-left corner of the board.
*/
def findNonsensicalMarker = \indicesSum.
detectReferenceLoc <- whereami;
result <- detect "sliding-tile" ((0, 0), (3, 3));
case result (\_. return ()) (\badLoc.
missingIdx <- findMissingIndex indicesSum;
if (missingIdx > 0) {
// Fix it:
teleportToDetectResult detectReferenceLoc badLoc;
let entName = getLetterEntityByIndex missingIdx in
create entName;
_ <- swap entName;
return ();
} {};
);
end;

def observe = \indicesSum. \boardWidth.
// We expect to begin each iteration on an empty tile.
// If we are not, reposition ourselves.
mt <- isempty;
if mt {} {
emptyHere <- isempty;
if emptyHere {} {
// Will return false
moveToBlankTile boardWidth;
return ();
Expand All @@ -291,32 +374,82 @@ def observe = \boardWidth. \boardHeight.
auditNeighbors 4;
return ();
} {};

observe boardWidth boardHeight;

atLocation (0, -3) $
findNonsensicalMarker indicesSum;
end;

def observeRec = \indicesSum. \boardWidth. \boardHeight.
observe indicesSum boardWidth;

// For efficiency; otherwise we will loop a large number of times each tick
// (until a certain instruction-per-tick limit is reached)
// wait 1;

observeRec indicesSum boardWidth boardHeight;
end;

def prepareArray = \boardWidth. \boardHeight.
let arrayLoc = (-3, -6) in
def fixInversions = \arrayLoc. \arrayLength.
teleport self arrayLoc;
inversionCount <- countInversions arrayLength 0;

if (isEven inversionCount) {} {
teleport self arrayLoc;
swapRelative 1;
};
end;

def prepareArray = \arrayLoc. \boardWidth. \boardHeight.

teleport self arrayLoc;

let cellCount = boardWidth * boardHeight in
let arrayLength = cellCount - 1 in

instant $ shuffle arrayLength 0;
shuffle arrayLength 0;
fixInversions arrayLoc arrayLength;
end;

teleport self arrayLoc;
inversionCount <- countInversions arrayLength 0;
say $ "Inversion count: " ++ format inversionCount;
def relocateEnt = \from. \to.
teleport self from;
emptyHere <- isempty;
if emptyHere {} {
e <- grab;
teleport self to;
place e;
};
end;

def placeSingleRow = \sourceRow. \boardWidth. \rowIndex. \colIndex.
if (colIndex >= 0) {
relocateEnt (rowIndex*boardWidth + colIndex, sourceRow) (colIndex, -rowIndex);
placeSingleRow sourceRow boardWidth rowIndex $ colIndex - 1;
} {};
end;

def placeRandomizedPuzzle = \arrayLoc. \boardWidth. \rowIndex.
if (rowIndex >= 0) {
placeSingleRow (snd arrayLoc) boardWidth rowIndex $ boardWidth - 1;
placeRandomizedPuzzle arrayLoc boardWidth $ rowIndex - 1;
} {};
end;

def setupGame = \boardWidth. \boardHeight.
let arrayLoc = (0, -6) in
prepareArray arrayLoc boardWidth boardHeight;
placeRandomizedPuzzle arrayLoc boardWidth $ boardHeight - 1;

teleport self (4, -4);

// Sentinel to indicate we are ready to start checking goal condition
create "flower";
end;

def go =
let boardWidth = 4 in
let boardHeight = 4 in

prepareArray boardWidth boardHeight;

teleport self (0, 0);
observe boardWidth boardHeight;
instant $ setupGame boardWidth boardHeight;
observeRec 120 boardWidth boardHeight;
end;

go;
7 changes: 6 additions & 1 deletion data/scenarios/Challenges/_sliding-puzzle/validate-board.sw
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,9 @@ def loopMonotonicityCheck : int -> int -> int -> int -> cmd bool = \boardWidth.
}
end;

loopMonotonicityCheck 4 4 0 1;
hasFlower <- has "flower";
if hasFlower {
loopMonotonicityCheck 4 4 0 1;
} {
return false;
};
20 changes: 10 additions & 10 deletions data/scenarios/Challenges/sliding-puzzle.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ robots:
system: true
dir: [1, 0]
display:
invisible: false
invisible: true
attr: 'iron'
inventory:
- [1, a-tile-ordinal]
Expand Down Expand Up @@ -442,12 +442,12 @@ world:
'n': [grass, n-tile]
'o': [grass, o-tile]
map: |
...............
..xxxxxx.......
B.xabcdx.......
..xefghx.......
..xijkzx.......
..xmnolx.......
..xxxxxx.......
...............
abcdefghijklmno
..................
..xxxxxx..........
B.x....x..........
..x....x..........
..x....x..........
..x....x..........
..xxxxxx..........
..................
.z.abcdefghijklmno