15 puzzle game: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 27:
{{trans|Python: Original, with output}}
 
<syntaxhighlight lang="11l">T Puzzle
position = 0
[Int = String] items
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.)
 
<syntaxhighlight lang="68000devpac">;15 PUZZLE GAME
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Line 811:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program puzzle15_64.s */
Line 1,435:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">DEFINE BOARDSIZE="16"
DEFINE X0="13"
DEFINE Y0="6"
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.
 
<syntaxhighlight lang=Ada"ada">generic
Rows, Cols: Positive;
with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols);
Line 1,675:
The package implementation is as follows.
 
<syntaxhighlight lang=Ada"ada">package body Generic_Puzzle is
Field: array(Row_Type, Col_Type) of Natural;
Line 1,735:
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.
 
<syntaxhighlight lang=Ada"ada">with Generic_Puzzle, Ada.Text_IO,
Ada.Numerics.Discrete_Random, Ada.Command_Line;
 
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. <syntaxhighlight lang=Ada"ada"> package Puzzle is new Generic_Puzzle(Rows => 3, Cols => 3, Name => Image);</syntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
<syntaxhighlight lang=APL"apl">fpg←{⎕IO←0
⍺←4 4
(s∨.<0)∨2≠⍴s←⍺:'invalid shape:'s
Line 1,925:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 2,566:
 
=={{header|Astro}}==
<syntaxhighlight lang="python">type Puzzle(var items: {}, var position: -1)
 
fun mainframe(puz):
Line 2,683:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">Size := 20
Grid := [], Deltas := ["-1,0","1,0","0,-1","0,1"], Width := Size * 2.5
Gui, font, S%Size%
Line 2,764:
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="basic">10 REM 15-PUZZLE GAME
20 REM COMMODORE BASIC 2.0
30 REM ********************************
Line 2,882:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}{{works with|ARM BBC BASIC}}{{works with|Brandy BASIC|Matrix Brandy}}
<syntaxhighlight 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,930:
=={{header|BQN}}==
{{trans|APL}}
<syntaxhighlight lang="bqn">_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
FPG←{
𝕊𝕩: 4‿4𝕊𝕩;
Line 2,972:
@
}</syntaxhighlight>
<syntaxhighlight lang="bqn"> )ex 15_puzzle.bqn
FPG 10
┌─
Line 3,007:
===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.
<syntaxhighlight lang=C"c">/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, § 22 */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
Line 3,031:
 
===C89, short version, TTY mode===
<syntaxhighlight lang=C"c">/*
* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC
*/
Line 3,186:
 
===C89, long version, TTY/Winapi/ncurses modes===
<syntaxhighlight lang=C"c">/**
* RosettaCode: Fifteen puzle game, C89, MS Windows Console API, MVC
*
Line 3,502:
{{libheader|System.Drawing}}
{{works with|C sharp|6}}
<syntaxhighlight lang="csharp">using System;
using System.Drawing;
using System.Linq;
Line 3,664:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
#include <time.h>
#include <stdlib.h>
Line 3,777:
Tested with GnuCOBOL
 
<syntaxhighlight lang="cobol"> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
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</syntaxhighlight>.
 
<syntaxhighlight lang="lisp">(defpackage :15
(:use :common-lisp))
(in-package :15)
Line 4,052:
[https://easylang.online/apps/15-puzzle.html Run it]
 
<syntaxhighlight lang="text">background 432
textsize 13
len f[] 16
Line 4,136:
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight 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,186:
</pre>
=={{header|Factor}}==
<syntaxhighlight 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,297:
See [[15_puzzle_solver#Forth]] for a solver based on the same code.
 
<syntaxhighlight lang="forth">#! /usr/bin/gforth
 
cell 8 <> [if] s" 64-bit system required" exception throw [then]
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 <syntaxhighlight lang=Fortran"fortran">LOCZ = MINLOC(BOARD) !Find the zero. 0 = BOARD(LOCZ(1),LOCZ(2)) == BOARD(ZC,ZR)</syntaxhighlight> 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. <syntaxhighlight lang=Fortran"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,529:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">sub drawboard( B() as ubyte )
dim as string outstr = ""
for i as ubyte = 0 to 15
Line 4,605:
 
=={{header|Gambas}}==
<syntaxhighlight 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,908:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 5,064:
 
=={{header|Harbour}}==
<syntaxhighlight lang=Harbour"harbour">
 
#include "inkey.ch"
Line 5,252:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.Array
import System.Random
 
Line 5,354:
Implementation:
 
<syntaxhighlight lang=J"j">require'general/misc/prompt'
 
genboard=:3 :0
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:
 
<syntaxhighlight lang=J"j"> game''
15 puzzle
h for help, q to quit
Line 5,465:
=={{header|Java}}==
{{works with|Java|8}}
<syntaxhighlight lang="java">package fifteenpuzzle;
 
import java.awt.*;
Line 5,682:
=={{header|Javascript}}==
Play it [http://paulo-jorente.de/webgames/15p/ here]
<syntaxhighlight lang="javascript">
var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
Line 5,820:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
using Random
 
Line 5,948:
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.1.3
 
import java.awt.BorderLayout
Line 6,101:
{{trans|Commodore BASIC}}
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
' 15-PUZZLE GAME
' ********************************
Line 6,238:
 
=={{header|LiveCode}}==
<syntaxhighlight lang=liveCode"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,305:
 
=={{header|Lua}}==
<syntaxhighlight 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,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)
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Puzzle15 {
Line 6,550:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">grid = MapThread[{#1,#2} &, {Range @ 16, Range @ 16}]
 
Move[x_] := (empty = Select[grid, #[[1]]==16 &][[1,2]];
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:
<syntaxhighlight lang=Mercury"mercury">:- module fifteen.
:- interface.
:- use_module random, io.
Line 6,673:
As used:
 
<syntaxhighlight lang=Mercury"mercury">:- module play_fifteen.
:- interface.
:- import_module io.
Line 6,802:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import random, terminal
 
type
Line 6,958:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">module Puzzle =
struct
type t = int array
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.
<syntaxhighlight lang=Pascal"pascal">
program fifteen;
{$mode objfpc}
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]
<syntaxhighlight lang="perl">
 
use strict;
Line 7,600:
===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.
<syntaxhighlight lang="perl">
use strict;
use warnings;
Line 7,637:
=== console only ===
Kept simple. Obviously, increase the 5 random moves for more of a challenge.
<!--<syntaxhighlight lang=Phix"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,703:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/15game.htm here].
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\15_puzzle_game.exw
Line 7,832:
=={{header|PHP}}==
OOP and MVC design pattern has been used to facilitate any improvements, e.g. tiles with graphics instead of just numbers.
<syntaxhighlight lang=PHP"php"><?php
// Puzzle 15 Game - Rosseta Code - PHP 7 as the server-side script language.
 
Line 8,060:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">
import util.
 
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.
<syntaxhighlight lang=Powershell"powershell">
#15 Puzzle Game
$Script:Neighbours = @{
Line 8,395:
 
=={{header|Processing}}==
<syntaxhighlight 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,515:
==={{header|Processing Python mode}}===
{{trans|Processing}}
<syntaxhighlight lang=Python"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,631:
Numbers are displayed in Hexadecimal (ie 1 to F)
Default controls are u,d,l,r
<syntaxhighlight lang=PureBasic"purebasic">
#difficulty=10 ;higher is harder
#up="u"
Line 8,715:
{{works with|Python|3.X}}
'''unoptimized'''
<syntaxhighlight lang="python">
''' Structural Game for 15 - Puzzle with different difficulty levels'''
from random import randint
Line 8,874:
 
===Python: using tkinter===
<syntaxhighlight lang="python">
''' Python 3.6.5 code using Tkinter graphical user interface.'''
 
Line 9,127:
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
_TITLE "GUI Sliding Blocks Game "
RANDOMIZE TIMER
Line 9,215:
=={{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.
<syntaxhighlight lang=Quackery"quackery">
( moves: 0 - up, 1 - down, 2 - left, 3 - right )
 
Line 9,309:
=={{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"r">
puz15<-function(scramble.length=100){
m=matrix(c(1:15,0),byrow=T,ncol=4)
Line 9,445:
It uses the <code>2htdp/universe</code> package.
 
<syntaxhighlight lang="racket">#lang racket/base
(require 2htdp/universe 2htdp/image racket/list racket/match)
 
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.
<syntaxhighlight lang=perl6"raku" line>use Term::termios;
 
constant $saved = Term::termios.new(fd => 1).getattr;
Line 9,632:
 
=={{header|Rebol}}==
<syntaxhighlight lang=Rebol"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
Line 9,640:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">
Red [Needs: 'view]
system/view/screens/1/pane/-1/visible?: false ;; suppress console window
Line 9,715:
 
Over half of the REXX program has to do with input validation and presentation of the puzzle (grid).
<syntaxhighlight 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,824:
=={{header|Ring}}==
 
<syntaxhighlight lang="ring">
# Project : CalmoSoft Fifteen Puzzle Game
# Date : 2018/12/01
Line 10,598:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'io/console'
 
class Board
Line 10,707:
{{libheader|JRubyArt}}
Gui Version:-
<syntaxhighlight 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,813:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">call SetCSS
' ---- fill 15 squares with 1 to 15
dim sq(16)
Line 10,887:
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang="rust">extern crate rand;
use std::collections::HashMap;
Line 11,094:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">import java.util.Random
 
import jline.console._
Line 11,174:
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">
(import (scheme base)
(scheme read)
Line 11,294:
=={{header|Scilab}}==
 
<syntaxhighlight lang="text">tiles=[1:15,0];
solution=[tiles(1:4);...
tiles(5:8);...
Line 11,448:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">
BEGIN
CLASS FIFTEENPUZZLE(NUMTILES, SIDE, WIDTH, SEED);
Line 11,703:
{{works with|SML/NJ}}
{{works with|Moscow ML}}
<syntaxhighlight lang="sml">
(* Load required Modules for Moscow ML *)
load "Int";
Line 11,971:
The window-title is used to show messages.
 
<syntaxhighlight lang="tcl"> # 15puzzle_21.tcl - HaJo Gurt - 2016-02-16
# http://wiki.tcl.tk/14403
 
Line 12,114:
This plays the game in an ANSI-compliant terminal using vi/nethack movement keys to slide the tiles.
 
<syntaxhighlight lang="bash">#!/usr/bin/env bash
main() {
local puzzle=({1..15} " ") blank moves_kv i key count total last
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">
Public iSide As Integer
Public iSize As Integer
Line 12,424:
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Public Class Board
Inherits System.Windows.Forms.Form
 
Line 12,526:
[https://youtu.be/rWy3AX5HjXM 15 Puzzle in Visual Prolog - video]
 
<syntaxhighlight lang=Visual"visual Prologprolog">
/* ------------------------------------------------------------------------------------------------------
 
Line 13,464:
 
=={{header|VBScript}}==
<syntaxhighlight lang=VB"vb">
'----------------15 game-------------------------------------
'WARNING: this script uses ANSI escape codes to position items on console so
Line 13,579:
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/dynamic" for Enum
import "/ioutil" for Input
Line 13,761:
 
=={{header|x86-64 Assembly}}==
<syntaxhighlight 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,847:
{{trans|Liberty BASIC}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "fifteenpuzzlegame"
VERSION "0.0001"
Line 14,006:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">int Box, Hole, I;
[Box:= [^ ,^F,^E,^D, \starting configuration
^C,^B,^A,^9, \slide digits into ascending order
Line 14,047:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">dx = 4 : dy = 4 : dxy = dx * dy
dim grid(dx, dy)
 
Line 14,127:
 
Adaptation from Phix solution
<syntaxhighlight lang=Yabasic"yabasic">board$ = "123456789ABCDEF0"
solve$ = board$
pos = 16
10,339

edits