15 puzzle game: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|UNIX Shell}}: clean up final output)
m (syntax highlighting fixup automation)
Line 27:
{{trans|Python: Original, with output}}
 
<langsyntaxhighlight lang=11l>T Puzzle
position = 0
[Int = String] items
Line 140:
I g.game_over()
print(‘You WON’)
L.break</langsyntaxhighlight>
 
{{out}}
Line 149:
This is an entire Sega Genesis game, tested in the Fusion emulator. Thanks to Keith S. of Chibiakumas for the cartridge header, font routines, and printing logic. I programmed the actual game logic. This code can be copied and pasted into a text file and assembled as-is using vasmm68k_mot_win32.exe, no includes or incbins necessary (even the bitmap font is here too.)
 
<langsyntaxhighlight lang=68000devpac>;15 PUZZLE GAME
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Line 805:
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
VDPSettingsEnd:
even</langsyntaxhighlight>
 
{{out}}[https://ibb.co/4MZpL4W Screenshot of emulator]
Line 811:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program puzzle15_64.s */
Line 1,432:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight lang=Action!>DEFINE BOARDSIZE="16"
DEFINE X0="13"
DEFINE Y0="6"
Line 1,648:
FI
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/15_puzzle_game.png Screenshot from Atari 8-bit computer]
Line 1,656:
We fist define a generic package Generic_Puzzle. Upon instantiation, it can take any number of rows, any number of columns for a rows*columns-1 game. Instead of plain numbers, the tiles on the board can have arbitrary names (but they should all be of the same length). The package user can request the name for the tile at a certain (row,column)-point, and the set of possible moves. The user can move the empty space up, down, left and right (if possible). If the user makes the attempt to perform an impossible move, a Constraint_Error is raised.
 
<langsyntaxhighlight lang=Ada>generic
Rows, Cols: Positive;
with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols);
Line 1,671:
procedure Move(The_Move: Moves);
 
end Generic_Puzzle;</langsyntaxhighlight>
 
The package implementation is as follows.
 
<langsyntaxhighlight lang=Ada>package body Generic_Puzzle is
Field: array(Row_Type, Col_Type) of Natural;
Line 1,731:
end loop;
end;
end Generic_Puzzle;</langsyntaxhighlight>
 
The main program reads the level from the command line. A larger level implies a more difficult instance. The default level is 10, which is fairly simple. After randomizing the board, the user can move the tiles.
 
<langsyntaxhighlight lang=Ada>with Generic_Puzzle, Ada.Text_IO,
Ada.Numerics.Discrete_Random, Ada.Command_Line;
 
Line 1,806:
end;
end loop;
end Puzzle_15;</langsyntaxhighlight>
 
{{out}}
Line 1,848:
4 moves!</pre>
 
For other puzzles, one must just the single line with the package instantiation. E.g., for an 8-puzzle, we would write the following. <langsyntaxhighlight lang=Ada> package Puzzle is new Generic_Puzzle(Rows => 3, Cols => 3, Name => Image);</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
<langsyntaxhighlight lang=APL>fpg←{⎕IO←0
⍺←4 4
(s∨.<0)∨2≠⍴s←⍺:'invalid shape:'s
Line 1,876:
(1↓⍺)∇ n
}z
}</langsyntaxhighlight>
{{out}}
<pre> fpg 10
Line 1,925:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 2,563:
bx lr @return
 
</syntaxhighlight>
</lang>
 
=={{header|Astro}}==
<langsyntaxhighlight lang=python>type Puzzle(var items: {}, var position: -1)
 
fun mainframe(puz):
Line 2,680:
print 'You WON'
break
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>Size := 20
Grid := [], Deltas := ["-1,0","1,0","0,-1","0,1"], Width := Size * 2.5
Gui, font, S%Size%
Line 2,759:
if (Trim(gridCont, ",") = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16")
MsgBox, 262208, 15 Puzzle, You solved 15 Puzzle
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang=basic>10 REM 15-PUZZLE GAME
20 REM COMMODORE BASIC 2.0
30 REM ********************************
Line 2,878:
1130 FOR T=0 TO 400
1140 NEXT
1150 RETURN</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}{{works with|ARM BBC BASIC}}{{works with|Brandy BASIC|Matrix Brandy}}
<langsyntaxhighlight lang=bbcbasic> IF INKEY(-256)=77 OR (INKEY(-256) AND &F0)=&A0 THEN MODE 1: COLOUR 0: COLOUR 143: *FX4,1
 
SIZE=4 : DIFFICULTY=3
Line 2,926:
COLOUR 0 : COLOUR 143
PRINT
ENDPROC</langsyntaxhighlight>
 
=={{header|BQN}}==
{{trans|APL}}
<langsyntaxhighlight lang=bqn>_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
FPG←{
𝕊𝕩: 4‿4𝕊𝕩;
Line 2,971:
} _while_ ⊢ 1
@
}</langsyntaxhighlight>
<langsyntaxhighlight lang=bqn> )ex 15_puzzle.bqn
FPG 10
┌─
Line 3,002:
Out of bounds: ↓
...</langsyntaxhighlight>
 
=={{header|C}}==
===C89, 22 lines version===
The task, as you can see, can be resolved in 22 lines of no more than 80 characters. Of course, the source code in C is not very readable. The second example works exactly the same way, but it was written in much more human readable way. The program also works correctly for non-standard number of rows and/or columns.
<langsyntaxhighlight lang=C>/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, § 22 */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
Line 3,028:
RIGHT;}}}void pause(void){getchar();}int main(void){srand((unsigned)time(NULL));
do setup();while(isEnd());show();while(!isEnd()){update(get());show();}disp(
"You win"); pause();return 0;}</langsyntaxhighlight>
 
===C89, short version, TTY mode===
<langsyntaxhighlight lang=C>/*
* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC
*/
Line 3,154:
}
 
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,186:
 
===C89, long version, TTY/Winapi/ncurses modes===
<langsyntaxhighlight lang=C>/**
* RosettaCode: Fifteen puzle game, C89, MS Windows Console API, MVC
*
Line 3,496:
return EXIT_SUCCESS;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Line 3,502:
{{libheader|System.Drawing}}
{{works with|C sharp|6}}
<langsyntaxhighlight lang=csharp>using System;
using System.Drawing;
using System.Linq;
Line 3,661:
grid[positionOf[b]] = b;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>
#include <time.h>
#include <stdlib.h>
Line 3,759:
p15 p; p.play(); return 0;
}
</syntaxhighlight>
</lang>
<pre>
+----+----+----+----+
Line 3,777:
Tested with GnuCOBOL
 
<langsyntaxhighlight lang=cobol> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
Line 3,927:
end-evaluate
.
end program fifteen.</langsyntaxhighlight>
 
{{out}}
Line 3,946:
Credit to this post for help with the inversions-counting function: [http://www.lispforum.com/viewtopic.php?f=2&t=3422]
 
Run it (after loading the file) with <syntaxhighlight lang =lisp>|15|::main</langsyntaxhighlight>.
 
<langsyntaxhighlight lang=lisp>(defpackage :15
(:use :common-lisp))
(in-package :15)
Line 4,046:
(rotatef (aref *board* (first pos) (second pos))
(aref *board* (first zpos) (second zpos))))))
(format t "You win!~%"))</langsyntaxhighlight>
 
=={{header|EasyLang}}==
Line 4,133:
.
.
call init</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>
// 15 Puzzle Game. Nigel Galloway: August 9th., 2020
let Nr,Nc,RA,rnd=[|3;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3|],[|3;0;1;2;3;0;1;2;3;0;1;2;3;0;1;2|],[|for n in [1..16]->n%16|],System.Random()
Line 4,152:
[<EntryPoint>]
let main n = fL(match n with [|n|]->let g=[|let g=uint64 n in for n in 60..-4..0->int((g>>>n)&&&15UL)|] in (Array.findIndex((=)0)g,g) |_->fE()) 0
</syntaxhighlight>
</lang>
3 uses:
15 game with no parameters will generate a random game which may be solved.
Line 4,186:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: accessors combinators combinators.extras
combinators.short-circuit grouping io kernel literals math
math.matrices math.order math.parser math.vectors prettyprint qw
Line 4,262:
drop ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 4,297:
See [[15_puzzle_solver#Forth]] for a solver based on the same code.
 
<langsyntaxhighlight lang=forth>#! /usr/bin/gforth
 
cell 8 <> [if] s" 64-bit system required" exception throw [then]
Line 4,366:
 
solution 1000 shuffle play
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 4,379:
The game plan is to start with an ordered array so that each cell definitely has a unique code, then jumble them via "random" swaps. Possible arrangements turn out to have either odd or even parity based on the number of out-of-sequence squares, and as the allowed transformations do not change the parity and the solution state has even parity, odd parity starting states should not be presented except by those following Franz Kafka. The calculation is simplified by always having the blank square in the last position, thus in the last row. Once an even-parity starting state is floundered upon, the blank square is re-positioned using allowable moves so that the parity is not altered thereby. Then the game begins: single-square moves only are considered, though in practice groups of squares could be moved horizontally or vertically rather than one-step-at-a-time - a possible extension.
 
The source style uses F90 for its array arithmetic abilities, especially the functions ALL, ANY and COUNT. A statement <langsyntaxhighlight lang=Fortran>LOCZ = MINLOC(BOARD) !Find the zero. 0 = BOARD(LOCZ(1),LOCZ(2)) == BOARD(ZC,ZR)</langsyntaxhighlight> could be used but is unnecessary thanks to tricks with EQUIVALENCE. For earlier Fortran, various explicit DO-loops would have to be used. This would at least make clear whether or not the equivalents of ANY and ALL terminated on the first failure or doggedly scanned the entire array no matter what. <langsyntaxhighlight lang=Fortran> SUBROUTINE SWAP(I,J) !Alas, furrytran does not provide this.
INTEGER I,J,T !So, we're stuck with supplying the obvious.
T = I !And, only for one type at a go.
Line 4,495:
IF (ANY(BORED(1:N - 2) + 1 .NE. BORED(2:N - 1))) GO TO 20 !Are we there yet?
WRITE (MSG,*) TRY,"Steps to success!" !Yes!
END !That was fun.</langsyntaxhighlight>
 
Output: Not so good. As ever, the character cell sizes are not square so a square game board comes out as a rectangle. Similarly, underlining is unavailable (no overprints!) so the layout is not pleasing. There are special "box-drawing" glyphs available, but they are not standardised and there is still no overprinting so that a flabby waste of space results. Further, there is no ability to re-write the display, even though one could easily regard the output to the screen as a random-access file: <code>WRITE (MSG,REC = 6) STUFF</code> would rewrite the sixth line of the display. Instead, output relentlessly rolls forwards, starting as follows:
Line 4,529:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>sub drawboard( B() as ubyte )
dim as string outstr = ""
for i as ubyte = 0 to 15
Line 4,602:
print "Congratulations! You win!"
print
drawboard B()</langsyntaxhighlight>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang=gambas>'Charlie Ogier (C) 15PuzzleGame 24/04/2017 V0.1.0 Licenced under MIT
'Inspiration came from: -
''http://rosettacode.org/wiki/15_Puzzle_Game
Line 4,903:
 
End
</syntaxhighlight>
</lang>
 
[http://www.cogier.com/gambas/Copuzzle.png Click here for image of game in play]
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 5,061:
return
}
}</langsyntaxhighlight>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang=Harbour>
 
#include "inkey.ch"
Line 5,249:
SetColor(" W/N, BG+/B")
RETURN fim
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import Data.Array
import System.Random
 
Line 5,324:
randomIndex <- randomRIO (0, length moves - 1)
let move = moves !! randomIndex
shufflePuzzle (numOfShuffels - 1) (applyMove move puzzle)</langsyntaxhighlight>
Output:
<pre>Please enter the difficulty level: 0, 1 or 2
Line 5,354:
Implementation:
 
<langsyntaxhighlight lang=J>require'general/misc/prompt'
 
genboard=:3 :0
Line 5,418:
showboard board
echo 'You win.'
)</langsyntaxhighlight>
 
Most of this is user interface code. We initially shuffle the numbers randomly, then check their parity and swap the first and last squares if needed. Then, for each move, we allow the user to pick one of the taxicab neighbors of the empty square.
Line 5,424:
A full game would be too big to be worth showing here, so for the purpose of giving a glimpse of what this looks like in action we replace the random number generator with a constant:
 
<langsyntaxhighlight lang=J> game''
15 puzzle
h for help, q to quit
Line 5,461:
│13│14│15│ │
└──┴──┴──┴──┘
You win.</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang=java>package fifteenpuzzle;
 
import java.awt.*;
Line 5,678:
});
}
}</langsyntaxhighlight>
 
=={{header|Javascript}}==
Play it [http://paulo-jorente.de/webgames/15p/ here]
<langsyntaxhighlight lang=javascript>
var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
Line 5,801:
restart();
}
</syntaxhighlight>
</lang>
Html to test
<pre>
Line 5,820:
 
=={{header|Julia}}==
<langsyntaxhighlight lang=julia>
using Random
 
Line 5,928:
 
puzzle15play()
</langsyntaxhighlight>{{output}}<pre>
This puzzle is solvable.
+----+----+----+----+
Line 5,948:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>// version 1.1.3
 
import java.awt.BorderLayout
Line 6,096:
}
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
{{trans|Commodore BASIC}}
{{works with|Just BASIC}}
<syntaxhighlight lang=lb>
<lang lb>
' 15-PUZZLE GAME
' ********************************
Line 6,235:
isPuzzleComplete = pc
end function
</syntaxhighlight>
</lang>
 
=={{header|LiveCode}}==
<langsyntaxhighlight lang=liveCode>
#Please note that all this code can be performed in livecode with just few mouse clicks
#This is just a pure script exampe
Line 6,300:
end if
end checkDistance
</syntaxhighlight>
</lang>
Screenshot:
[https://s24.postimg.org/uc6fx7kph/Livecode15_Puzzle_Game.png]
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>
math.randomseed( os.time() )
local puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 }
Line 6,402:
-- [ entry point ] --
beginGame()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,434:
Also the code is not the best, because we can move from 4 position to 5 (we can't do that with real puzzle)
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module Puzzle15 {
Line 6,547:
}
Puzzle15
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=mathematica>grid = MapThread[{#1,#2} &, {Range @ 16, Range @ 16}]
 
Move[x_] := (empty = Select[grid, #[[1]]==16 &][[1,2]];
Line 6,562:
CButton[{x_,loc_}] := If[x==16, Null, Button[x,Move @ loc]]
 
Dynamic @ Grid @ Partition[CButton /@ grid,4]</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 6,568:
The ideal in Mercury is to have a declarative module that encodes the game logic, and then separate modules to implement a human player with text commands (here), or keyed commands, or some kind of AI player, and so on. fifteen.print/3 is a arguably a smudge on fifteen's interface:
<langsyntaxhighlight lang=Mercury>:- module fifteen.
:- interface.
:- use_module random, io.
Line 6,669:
move(I, right, !B) :-
not (I = 3 ; I = 7 ; I = 11 ; I = 15),
swap(I, I + 1, !B).</langsyntaxhighlight>
 
As used:
 
<langsyntaxhighlight lang=Mercury>:- module play_fifteen.
:- interface.
:- import_module io.
Line 6,753:
"
Seed = time(NULL);
").</langsyntaxhighlight>
 
=={{header|MUMPS}}==
Line 6,802:
 
=={{header|Nim}}==
<langsyntaxhighlight lang=nim>import random, terminal
 
type
Line 6,944:
 
draw board
echo "You win!"</langsyntaxhighlight>
{{out}}
<pre>┌──┬──┬──┬──┐
Line 6,958:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>module Puzzle =
struct
type t = int array
Line 6,996:
print_string " > ";
Puzzle.move p (read_line () |> int_of_string)
done</langsyntaxhighlight>
 
To move, input the number to slide into the blank. If you accidentally make an impossible move you can undo it by repeating the last input. A nice self-checked puzzle, the same as if you were physically moving the pieces around.
Line 7,046:
=={{header|Pascal}}==
This is Free Pascal(version >= 3.0.4) text mode implementation. To make a move, the user needs to enter the number of the selected tile.
<langsyntaxhighlight lang=Pascal>
program fifteen;
{$mode objfpc}
Line 7,336:
Run;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 7,345:
On verbosity shows how the solvability is calculated. The program has some extra feature like font size and color scheme but also the possibility to set the intial board disposition.
This program was originally posted by me at [http://www.perlmonks.org/?node_id=1192660 perlmonks]
<langsyntaxhighlight lang=perl>
 
use strict;
Line 7,596:
 
 
</syntaxhighlight>
</lang>
 
===console version===
This short console program just poses solvable puzzles: it achieves this shuffling a solved board n times, where n defaults to 1000 but can be passed as first argument of the program in the command line. It was originally posted by me at [http://www.perlmonks.org/?node_id=1192865 perlmonks] but here a little modification was inserted to prevent wrong numbers to make the board messy.
<langsyntaxhighlight lang=perl>
use strict;
use warnings;
Line 7,632:
[$$e[0]-1,$$e[1]],[$$e[0]+1,$$e[1]],[$$e[0],$$e[1]-1],[$$e[0],$$e[1]+1]
}
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
=== console only ===
Kept simple. Obviously, increase the 5 random moves for more of a challenge.
<!--<langsyntaxhighlight lang=Phix>-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">ESC<span style="color: #0000FF;">=<span style="color: #000000;">27<span style="color: #0000FF;">,</span> <span style="color: #000000;">UP<span style="color: #0000FF;">=<span style="color: #000000;">328<span style="color: #0000FF;">,</span> <span style="color: #000000;">LEFT<span style="color: #0000FF;">=<span style="color: #000000;">331<span style="color: #0000FF;">,</span> <span style="color: #000000;">RIGHT<span style="color: #0000FF;">=<span style="color: #000000;">333<span style="color: #0000FF;">,</span> <span style="color: #000000;">DOWN<span style="color: #0000FF;">=<span style="color: #000000;">336</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">board</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">15<span style="color: #0000FF;">)<span style="color: #0000FF;">&<span style="color: #000000;">0<span style="color: #0000FF;">,</span> <span style="color: #000000;">solve</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">board</span>
Line 7,669:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"solved!\n"<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 7,703:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/15game.htm here].
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\15_puzzle_game.exw
Line 7,828:
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
OOP and MVC design pattern has been used to facilitate any improvements, e.g. tiles with graphics instead of just numbers.
<langsyntaxhighlight lang=PHP><?php
// Puzzle 15 Game - Rosseta Code - PHP 7 as the server-side script language.
 
Line 8,057:
?></p>
</body>
</html></langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat>
import util.
 
Line 8,125:
Board[R0,C0] := S,
Board[R,C] := 0.
</syntaxhighlight>
</lang>
 
=={{header|Powershell}}==
Line 8,132:
Board is always scrambled from a solved board so it's always solvable.
Written in ISE with ISESteroids. I'm sure the code could be improved on.
<langsyntaxhighlight lang=Powershell>
#15 Puzzle Game
$Script:Neighbours = @{
Line 8,392:
# Show Window
$result = Show-WPFWindow -Window $window
</syntaxhighlight>
</lang>
 
=={{header|Processing}}==
<langsyntaxhighlight lang=java>
int number_of_grid_cells = 16; // Set the number of cells of the board here 9, 16, 25 etc
color piece_color = color(255, 175, 0);
Line 8,509:
}
}
}</langsyntaxhighlight>
 
'''It can be played on line''' :<BR> [https://www.openprocessing.org/sketch/863055/ here.]
Line 8,515:
==={{header|Processing Python mode}}===
{{trans|Processing}}
<langsyntaxhighlight lang=Python># Set the number of cells of the board here 9, 16, 25 etc
num_grid_cells = 16
piece_color = color(255, 175, 0)
Line 8,625:
# Upper bright
line(self.x + 2, self.y + 1, self.x +
piece_side_length - 1, self.y + 1)</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Line 8,631:
Numbers are displayed in Hexadecimal (ie 1 to F)
Default controls are u,d,l,r
<langsyntaxhighlight lang=PureBasic>
#difficulty=10 ;higher is harder
#up="u"
Line 8,701:
Print("Won !")
CloseConsole()
</syntaxhighlight>
</lang>
<pre>
1234
Line 8,715:
{{works with|Python|3.X}}
'''unoptimized'''
<langsyntaxhighlight lang=python>
''' Structural Game for 15 - Puzzle with different difficulty levels'''
from random import randint
Line 8,840:
print('You WON')
break
</syntaxhighlight>
</lang>
<pre>
Enter the difficulty : 0 1 2
Line 8,874:
 
===Python: using tkinter===
<langsyntaxhighlight lang=python>
''' Python 3.6.5 code using Tkinter graphical user interface.'''
 
Line 9,124:
g = Game(root)
root.mainloop()
</syntaxhighlight>
</lang>
 
=={{header|QB64}}==
<langsyntaxhighlight lang=QB64>
_TITLE "GUI Sliding Blocks Game "
RANDOMIZE TIMER
Line 9,211:
END IF
LOOP
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
The inputs are w,s,a,d and they refer to the direction in which the empty place "moves". After every prompt you can input a string of characters and submit them by pressing enter. Any characters other than w,s,a,d will be ignored, and moves will be performed according to the correct commands. Commands that would "move" the empty space off the edge of the puzzle are also ignored. For example, on a solved puzzle "asgw" would move 15 to the right, ignore 's' and 'g' and move 11 down.
<langsyntaxhighlight lang=Quackery>
( moves: 0 - up, 1 - down, 2 - left, 3 - right )
 
Line 9,305:
 
15-puzzle
</syntaxhighlight>
</lang>
 
=={{header|R}}==
The inputs are w,a,s,d and they refer to the direction in which the adjacent piece moves into the empty space. For example, on a solved puzzle, "d" would move the 15 to the right.
<syntaxhighlight lang=R>
<lang R>
puz15<-function(scramble.length=100){
m=matrix(c(1:15,0),byrow=T,ncol=4)
Line 9,398:
}
}
</syntaxhighlight>
</lang>
 
Sample output:
Line 9,445:
It uses the <code>2htdp/universe</code> package.
 
<langsyntaxhighlight lang=racket>#lang racket/base
(require 2htdp/universe 2htdp/image racket/list racket/match)
 
Line 9,493:
(to-draw (fifteen->pict))
(stop-when solved-world? (fifteen->pict #t))
(on-key key-move-space))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 9,499:
{{works with|Rakudo|2018.06}}
Most of this is interface code. Reused substantial portions from the [[2048#Raku|2048]] task. Use the arrow keys to slide tiles, press 'q' to quit or 'n' for a new puzzle. Requires a POSIX termios aware terminal. Ensures that the puzzle is solvable by shuffling the board with an even number of swaps, then checking for even taxicab parity for the empty space.
<langsyntaxhighlight lang=perl6>use Term::termios;
 
constant $saved = Term::termios.new(fd => 1).getattr;
Line 9,613:
last if $key eq 'q'; # (q)uit
new() if $key eq 'n';
}</langsyntaxhighlight>
Sample screen shot:
<pre>
Line 9,632:
 
=={{header|Rebol}}==
<langsyntaxhighlight lang=Rebol>rebol [] random/seed now g: [style t box red [
if not find [0x108 108x0 0x-108 -108x0] face/offset - e/offset [exit]
x: face/offset face/offset: e/offset e/offset: x] across
] x: random repeat i 15 [append x:[] i] repeat i 15 [
repend g ['t mold x/:i random white] if find [4 8 12] i [append g 'return]
] append g [e: box] view layout g</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight lang=Red>
Red [Needs: 'view]
system/view/screens/1/pane/-1/visible?: false ;; suppress console window
Line 9,706:
view lay
 
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 9,715:
 
Over half of the REXX program has to do with input validation and presentation of the puzzle (grid).
<langsyntaxhighlight lang=rexx>/*REXX pgm implements the 15─puzzle (AKA: Gem Puzzle, Boss Puzzle, Mystic Square, 14─15)*/
parse arg N seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/
Line 9,778:
rm=holeRow-1; rp=holeRow+1; cm=holeCol-1; cp=holeCol+1 /*possible moves.*/
!=!.rm.holeCol !.rp.holeCol !.holeRow.cm !.holeRow.cp /* legal moves.*/
if show then say pad bot; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 9,824:
=={{header|Ring}}==
 
<langsyntaxhighlight lang=ring>
# Project : CalmoSoft Fifteen Puzzle Game
# Date : 2018/12/01
Line 10,591:
return
 
</syntaxhighlight>
</lang>
 
'''Output:'''
Line 10,598:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang=ruby>require 'io/console'
 
class Board
Line 10,687:
end
 
Board.new</langsyntaxhighlight>
 
{{out}}
Line 10,707:
{{libheader|JRubyArt}}
Gui Version:-
<langsyntaxhighlight lang=ruby>DIM = 100
SOLUTION = %w[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0].freeze
 
Line 10,810:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>call SetCSS
' ---- fill 15 squares with 1 to 15
dim sq(16)
Line 10,881:
Text-Align:Center;Font-Size:24pt;Font-Weight:Bold;Font-Family:Arial;
}"
END SUB</langsyntaxhighlight>
Output:
[[File:KokengeGame15.jpg]]
Line 10,887:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang=rust>extern crate rand;
use std::collections::HashMap;
Line 11,091:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>import java.util.Random
 
import jline.console._
Line 11,170:
.foldLeft(Board.solveState) { case (state, mv) => state.move(mv) }
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang=scheme>
(import (scheme base)
(scheme read)
Line 11,260:
 
(play-game)
</syntaxhighlight>
</lang>
 
{{out}}
Line 11,377:
end
 
disp("Solved in "+string(n_moves)+" moves.");</langsyntaxhighlight>
 
{{out}}
Line 11,448:
 
=={{header|Simula}}==
<langsyntaxhighlight lang=simula>
BEGIN
CLASS FIFTEENPUZZLE(NUMTILES, SIDE, WIDTH, SEED);
Line 11,661:
P.REQUEST;
P.PRINTBOARD;
END.</langsyntaxhighlight>
{{out}}
<pre>INPUT RANDOM SEED:
Line 11,703:
{{works with|SML/NJ}}
{{works with|Moscow ML}}
<langsyntaxhighlight lang=sml>
(* Load required Modules for Moscow ML *)
load "Int";
Line 11,954:
 
val () = Console.start()
</syntaxhighlight>
</lang>
 
<b>Note:</b>
Line 11,971:
The window-title is used to show messages.
 
<langsyntaxhighlight lang=tcl> # 15puzzle_21.tcl - HaJo Gurt - 2016-02-16
# http://wiki.tcl.tk/14403
 
Line 12,108:
 
# For some more versions, see: http://wiki.tcl.tk/15067 : Classic 15 Puzzle and http://wiki.tcl.tk/15085 : N-Puzzle
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
Line 12,114:
This plays the game in an ANSI-compliant terminal using vi/nethack movement keys to slide the tiles.
 
<langsyntaxhighlight lang=bash>#!/usr/bin/env bash
main() {
local puzzle=({1..15} " ") blank moves_kv i key count total last
Line 12,210:
}
 
main "$@"</langsyntaxhighlight>
 
{{Out}}
Line 12,228:
The last move is displayed on the input box, or an error message if an invalid move is attempted. When the puzzle is solved, the move count is displayed.
 
<syntaxhighlight lang=vb>
<lang vb>
Public iSide As Integer
Public iSize As Integer
Line 12,409:
ShowGrid = s
End Function
</syntaxhighlight>
</lang>
 
Sample output:
Line 12,424:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang=vbnet>Public Class Board
Inherits System.Windows.Forms.Form
 
Line 12,519:
End Function
 
End Class</langsyntaxhighlight>
 
=={{header|Visual Prolog}}==
Line 12,526:
[https://youtu.be/rWy3AX5HjXM 15 Puzzle in Visual Prolog - video]
 
<langsyntaxhighlight lang=Visual Prolog>
/* ------------------------------------------------------------------------------------------------------
 
Line 13,461:
% end of automatic code
end implement playDialog
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
<syntaxhighlight lang=VB>
<lang VB>
'----------------15 game-------------------------------------
'WARNING: this script uses ANSI escape codes to position items on console so
Line 13,573:
usr= move(d)
end function
</syntaxhighlight>
</lang>
=={{header|Wren}}==
{{trans|Go}}
Line 13,579:
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "random" for Random
import "/dynamic" for Enum
import "/ioutil" for Input
Line 13,699:
 
var p = Puzzle.new()
p.play()</langsyntaxhighlight>
 
{{out}}
Line 13,761:
 
=={{header|x86-64 Assembly}}==
<langsyntaxhighlight lang=assembly> ; Puzzle15 by grosged (march 2019)
; How to play ?.. Just press one of the arrow keys then [enter] to valid
; ( press [Ctrl+C] to escape )
Line 13,842:
xchg ax,word[puzzle+4+rbx*4]
mov word[puzzle+4+rdx*4],ax
ret</langsyntaxhighlight>
 
=={{header|XBasic}}==
{{trans|Liberty BASIC}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang=xbasic>
PROGRAM "fifteenpuzzlegame"
VERSION "0.0001"
Line 14,003:
 
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>int Box, Hole, I;
[Box:= [^ ,^F,^E,^D, \starting configuration
^C,^B,^A,^9, \slide digits into ascending order
Line 14,036:
other []; \ignore 0 scan code prefix etc.
];
]</langsyntaxhighlight>
 
{{out}}
Line 14,047:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>dx = 4 : dy = 4 : dxy = dx * dy
dim grid(dx, dy)
 
Line 14,124:
next y
next x
end sub</langsyntaxhighlight>
 
Adaptation from Phix solution
<langsyntaxhighlight lang=Yabasic>board$ = "123456789ABCDEF0"
solve$ = board$
pos = 16
Line 14,169:
loop
print "solved!\n"
</syntaxhighlight>
</lang>
10,343

edits