2048: Difference between revisions
m
syntax highlighting fixup automation
(2048 in FreeBASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 55:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program 2048_64.s */
Line 1,106:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Ada}}==
{{works with|GNAT}}
<
with System.Random_Numbers;
procedure Play_2048 is
Line 1,286:
end loop Main_Loop;
end Play_2048;
</syntaxhighlight>
{{out}}
<pre>+----+----+----+----+
Line 1,300:
=={{header|ALGOL 68}}==
<
main:(
INT side = 4;
Line 1,443:
lose: print(("you lose!", new line))
)
</syntaxhighlight>
=={{header|Amazing Hopper}}==
<pre>
VERSION 1: "Hopper" flavour.
</pre>
<
#context-free select Position of aleatory tail
#context-free show Table
Line 1,685:
println
back
</syntaxhighlight>
{{out}}
<pre>
Line 1,740:
VERSION 2: "Hopper-BASIC" flavour.
</pre>
<
// Definicion de "contextos"
Line 2,029:
Clear Mark.
Return
</syntaxhighlight>
=={{header|Applesoft BASIC}}==
<
10 REM ************
Line 2,238:
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program 2048.s */
Line 3,134:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 3,157:
=={{header|AutoHotkey}}==
<
Gui, font, s%s%
Gui, add, text, y1
Line 3,380:
Grid[StrSplit(rnd, ",").1, StrSplit(rnd, ",").2] := 2
}
;------------------------------</
=={{header|Batch File}}==
<
:: Batch File Implementation v2.0.1
Line 3,554:
echo(Press any key to exit . . .
pause>nul
exit /b 0</
{{out}}
<pre>2048 Game in Batch
Line 3,578:
Yo solo lo transcribo.
<
SCREEN 13
PALETTE 1, pColor(35, 33, 31)
Line 3,933:
PRINT "Score:" + STR$(gScore)
END SUB
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
Won% = FALSE : Lost% = FALSE
@% = 5
Line 4,007:
IF Board(z DIV SIZE,z MOD SIZE) = 0 THEN Board(z DIV SIZE,z MOD SIZE) = 2-(RND(10)=1)*2 : EXIT FOR
NEXT
ENDPROC</
{{out}}
<pre> _ _ _ _
Line 4,043:
===Version 1===
Supports limited colours through vt100 escape codes. Requires a posix machine for <tt>termios.h</tt> and <tt>unistd.h</tt> headers. Provides simplistic animations when moving and merging blocks.
<syntaxhighlight lang=c>
#include <stdio.h>
#include <stdlib.h>
Line 4,323:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,340:
<syntaxhighlight lang=c>
#include <stdio.h>
Line 4,682:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
{{trans|C++}}
<
namespace g2048_csharp
Line 5,080:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 5,100:
=={{header|C++}}==
<
#include <time.h>
#include <iostream>
Line 5,294:
return system( "pause" );
}
</syntaxhighlight>
{{out}}
<pre>
Line 5,313:
=={{header|Clojure}}==
<
(ns 2048
(:require [clojure.string :as str]))
Line 5,432:
:default (recur (handle-turn field)))))
(play-2048)</
{{out}}
Line 5,447:
=={{header|Common Lisp}}==
Depends on Windows msvcrt.dll for _getch. Depends on quicklisp. Use arrow keys to make moves and press "Q" to quit. Tested with SBCL.
<
(defpackage :2048-lisp
Line 5,647:
(format t "~% Score: ~D~%" score)
(print-board board 4)
(prompt-input board score))</
{{out}}
<pre>* (2048-lisp::prompt)
Line 5,675:
=={{header|D}}==
{{trans|C++}}
<
import core.stdc.stdlib: exit;
Line 5,866:
G2048 g;
g.gameLoop;
}</
The output is the same as the C++ version.
=={{header|Delphi}}==
Line 5,872:
{{libheader| Velthuis.Console}}Thanks for Rudy Velthuis [https://github.com/rvelthuis/Consoles].
{{Trans|C++}}
<
program Game2048;
Line 6,277:
Writeln('Press Enter to exit');
Readln;
end.</
{{out}}
<pre>
Line 6,298:
=={{header|Elixir}}==
{{works with|Elixir|1.3}}
<
@size 4
@range 0..@size-1
Line 6,412:
end
Game2048.play 512</
{{out}}
Line 6,444:
{{works with|Elm 0.18.0}}
Try online [https://ellie-app.com/3ZMMpYsbfcMa1/3]
<
import Html exposing (Html, div, p, text, button, span, h2)
Line 6,846:
viewGrid model.tiles
]
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Line 6,852:
The following code can be executed as is using F# Interactive from system command line ("fsi.exe 2048.fsx") but not from Visual Studio F# Interactive window due to the way it access keyboard (the System.Console.ReadKey() function).
<
// the board is represented with a list of 16 integers
let empty = List.init 16 (fun _ -> 0)
Line 6,912:
play()
</syntaxhighlight>
=={{header|Factor}}==
Line 6,927:
<
USE: accessors
FROM: arrays => <array> array ;
Line 7,248:
MAIN: start-2048
</syntaxhighlight>
=={{header|Forth}}==
Line 7,256:
Just like my implementation of [[15 Puzzle Game#Forth|15 Puzzle Game]], this uses Vim's h/j/k/l for movement.
<
: 2D-ARRAY ( height width )
CREATE DUP ,
Line 7,490:
INIT
MAIN-LOOP</
{{out}}
Line 7,517:
===Source===
The initial attempt at showing the board relied rather heavily on FORMAT tricks, in particular the use of the <''n''> facility whereby the value of an integer expression can be inserted into a format statement's coding on-the-fly, as in the following. <
WRITE (MSG,1) !Roll forth a top/bottom boundary. No corner characters (etc.), damnit.
1 FORMAT ("|",<NC>(<W>("-"),"|")) !Heavy reliance on runtime values in NC and W. But see FORMAT 22.
Line 7,523:
WRITE (MSG,22) ((" ",L1 = 1,W),"|",C = 1,NC) !Compare to FORMAT 2.
22 FORMAT ("|",666A1) !A constant FORMAT, a tricky WRITE.
4 FORMAT ("|",<NC - 1>(<W>("-"),"+"),<W>("-"),"|") !With internal + rather than |.</
This sort of thing is not necessarily accepted by all compilers, so instead the next stage was to convert to using complicated WRITE statements. If one regarded the various sizes (the values of NR, NC, W in the source) as truly fixed, literal constants could be used throughout. This would however mean that they would appear without explanation, and if one eventually attempted to recode with different values, mistakes would be likely. Thus below, FORMAT 3 has <code> (<NC>(A1,I<W>),A1)</code> and if the <> scheme were unavailable, you'd have to use <code>(4(A1,I6),A1)</code> instead, not too troublesome a change. Or, the text of the format sequence could be written to a CHARACTER variable, as demonstrated in [[Multiplication_tables#Traditional_approach]]. Yet another approach might be <code>(666(A1,I6))</code> which relies on the addendum <code>A1</code> happening to be the same as the start of the <code>(A1,I6)</code> pair, but there is still the appearance of the literal constant six instead of <W>, and if there were to be any change to be made, it would have to be remembered...
<
INTEGER NR,NC !Number of rows and columns.
INTEGER BOARD(NR,NC) !The board. Actual storage is transposed!
Line 7,715:
601 FORMAT ("None! Oh dear.") !Nothing more can be done.
END !That was fun.
</syntaxhighlight>
===Output===
Line 7,771:
=={{header|FreeBASIC}}==
Based On MichD's original code (https://github.com/michd/2048-qbasic)
<
'--- Declaration of global variables ---
Line 8,081:
End Select
Loop
Loop</
=={{header|Go}}==
<
import (
Line 8,355:
}
}
</syntaxhighlight>
=={{header|Haskell}}==
<
import Data.List
import Data.Maybe
Line 8,490:
setCursorPosition 1 1
putStrLn $ intercalate "\n\n\n\ESC[C" $ concatMap showTile `map` pos
</syntaxhighlight>
=={{header|J}}==
'''Solution'''
<
NB. =========================================================
NB. 2048 game engine
Line 8,599:
- start a new game:
grd=: g2048Con ''
)</
'''Usage'''
<
Score is 0
Line 8,620:
0 0 4 4
0 0 0 2
...</
=={{header|Java}}==
[[File:game_2048_java2.png|300px|thumb|right]]
{{works with|Java|8}}
<
import java.awt.event.*;
import java.util.Random;
Line 8,922:
return -1;
}
}</
=={{header|JavaScript}}==
Uses the P5.js library.
<
/* Tile object: */
Line 9,106:
game.keyHandler(keyCode);
}
</syntaxhighlight>
=={{header|Julia}}==
Uses the Gtk toolkit. Includes scoring, a choice of board size and toolbar buttons for Undo and New Game.
<
@enum Direction2048 Right Left Up Down
Line 9,281:
const boardsize = 4
app2048(boardsize)
</syntaxhighlight>
=={{header|Kotlin}}==
Stateless with focus on clarity rather than conciseness.
<
import java.io.InputStreamReader
Line 9,455:
}
println("+----+----+----+----+")
}</
Sample output:
Line 9,476:
Takes input on stdin using the words "left", "right", "up", "down".
<
use 'format import '[format].
use 'random.
Line 9,703:
$stdout putln: "Better luck next time!".
}.
</syntaxhighlight>
Sample output:
Line 9,719:
=={{header|Lua}}==
Sadly, ANSI C doesn't have low-level keyboard input, so neither does vanilla Lua, so the input is a bit cumbersome (wasd PLUS enter).
<
local unpack = unpack or table.unpack -- for 5.3 +/- compatibility
game = {
Line 9,794:
end
}
game:play()</
{{out}}
<pre>+----+----+----+----+
Line 9,808:
=={{header|M2000 Interpreter}}==
<
Module Game2048 {
\\ 10% 4 and 90% 2
Line 9,932:
}
Game2048
</syntaxhighlight>
Each move copied to clipboard
Line 9,964:
Next is the main body of code:
<
macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty);
G := module()
Line 10,184:
end module;
G:-reset();SP("Score/Lose",caption,"Click an Arrow to begin.");
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
"LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]),
"RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]),
Line 10,221:
stat=Nest[AddRandomNumber[#,RandomChoice[{2,4}]]&,ConstantArray[0,{n,n}],4];
Dynamic[PrintStat@stat]</
=={{header|MATLAB}}==
<
if nargin < 1 || isempty(field)
Line 10,357:
vector(vector==0) = [];
end</
You can start with an empty 4 x 4 board and save the last state of the playing field with:
<
Or you start from a saved playing field:
<
=={{header|Nim}}==
Line 10,369:
{{works with|Nim Compiler|0.19.4}}
<
const
Line 10,553:
for i in 1..BoardLength + 7:
eraseLine()
cursorUp()</
=={{header|OCaml}}==
<
let list_make x v =
let rec aux acc i =
Line 10,706:
loop grid
in
loop grid</
{{out}}
Line 10,746:
=={{header|Pascal}}==
<
program game2048;
uses Crt;
Line 11,109:
until end_game;
end.
</syntaxhighlight>
=={{header|Perl}}==
<
use strict; # https://rosettacode.org/wiki/2048
Line 11,198:
add2(2) for 1, 2;
$winner = '';
}</
=={{header|Phix}}==
Line 11,206:
Now I just got figure out how to win...
You can run this online [http://phix.x10.mx/p2js/2048.htm here].
<!--<
<span style="color: #000080;font-style:italic;">-- demo\rosetta\2048.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 11,473:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PHP}}==
Works from PHP5 and upwards in CLI mode.
<
<?php
Line 11,705:
}
</syntaxhighlight>
=={{header|PicoLisp}}==
<
(symbols 'simul 'pico)
Line 11,842:
(T (fish '((This) (= 512 (: N))) *G)
(println 'Maximum) ) )
(bye)</
=={{header|Pony}}==
{{works with|ponyc|0.10.0}}
<
use "term"
use "random"
Line 12,113:
input(consume notify)
</syntaxhighlight>
=={{header|Prolog}}==
Works with swi-prolog, any version.
<
Entry point, just create a blank grid and enter a 'game loop'
-------------------------------------------------------------*/
Line 12,275:
dbl(' ', ' ').
dbl(2,4). dbl(4,8). dbl(8,16). dbl(16,32). dbl(32,64). dbl(64,128). dbl(128,256). dbl(256,512). dbl(512,1028). dbl(1028,2048).
</syntaxhighlight>
{{out}}
<pre>?- play_2048.
Line 12,295:
=={{header|Python}}==
===Python: Original, with output===
<
import curses
Line 12,496:
curses.wrapper(main)
</syntaxhighlight>
===Python: using tkinter===
<
''' Python 3.6.5 code using Tkinter graphical user interface.
Line 12,793:
root.bind_all('<Key>', g.key)
root.mainloop()
</syntaxhighlight>
=={{header|QB64}}==
<
_DEFINE A-Z AS _INTEGER64
DIM SHARED Grid(0 TO 5, 0 TO 5) AS INTEGER
Line 13,084:
COLOR dc&, bg&
END SUB
</syntaxhighlight>
=={{header|R}}==
orginal R package : https://github.com/ThinkRstat/r2048
<syntaxhighlight lang=R>
GD <- function(vec) {
c(vec[vec != 0], vec[vec == 0])
Line 13,252:
}
</syntaxhighlight>
=={{header|Racket}}==
Line 13,258:
Play the RacketScript fork online here: http://rapture.twistedplane.com:8080/#example/2048-game
<
;; LICENSE: See License file LICENSE (MIT license)
;;
Line 14,063:
(start)
</syntaxhighlight>
=={{header|Raku}}==
Line 14,069:
Uses termios to set the terminal options, so only compatible with POSIX terminals. This version does not include a specific "win" or "lose" condition. (though it would be trivial to add them.) You can continue to play this even after getting a 2048 tile; and if there is no valid move you can make, you can't do anything but quit.
{{works with|Rakudo|2018.05}}
<
constant $saved = Term::termios.new(fd => 1).getattr;
Line 14,183:
move %dir{$key} if so %dir{$key};
last if $key eq 'q'; # (q)uit
}</
Sample output:
<pre>
Line 14,208:
{{works with|Red|0.6.4}}
<
random/seed now
Line 14,296:
display
view lay
</syntaxhighlight>
{{out}}
Line 14,315:
::* displays a message if a winning move was entered.
::* displays the game board as a grid (with boxes).
<
parse arg N win seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 4 /*Not specified? Then use the default.*/
Line 14,404:
do s=r to sTo by #; @.s.c= @(s + #, c) /*slide ↑ or ↓ */
end /*s*/; @.sTo.c= b /*handle the last one.*/
end /*r*/; return</
Programming note: with a little more program complexity, the '''moveLR''' and '''moveUD''' subroutines could've
<br>been combined, as well as the '''packLR''' and '''packUD''' subroutines.
Line 14,573:
=={{header|Ring}}==
<
# Project : 2048 Game
Line 15,010:
on '2048' setStylesheet(C_BUTTON2048STYLE)
off
</syntaxhighlight>
=={{header|Ruby}}==
inspired by the Raku version
<
#!/usr/bin/ruby
Line 15,213:
end
end
</syntaxhighlight>
=={{header|Rust}}==
Line 15,219:
A simple implementation in rust. The user has to input an endline since i did not find a way to read a key press
{{libheader|rand}}
<
use std::io::{self,BufRead};
extern crate rand;
Line 15,404:
}
}
</syntaxhighlight>
=={{header|Scala}}==
<
import java.awt.{BorderLayout, Color, Dimension, Font, Graphics2D, Graphics, RenderingHints}
import java.util.Random
Line 15,599:
}
}</
=={{header|Seed7}}==
Line 15,611:
STD_CONSOLE works also always the same, independent from the operating system or terminal/console.
<
include "console.s7i";
include "keybd.s7i";
Line 15,800:
until moveOkay;
until quit;
end func;</
=={{header|Tcl}}==
===Text mode===
<
# A minimal implementation of the game 2048 in Tcl.
# For a maintained version with expanded functionality see
Line 16,081:
main
</syntaxhighlight>
===Tk===
Line 16,088:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Public Sub New()
Me.Value = 0
Line 16,327:
End Sub
End Module
</syntaxhighlight>
{{out}}
<pre>
Line 16,352:
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<
import "random" for Random
import "/ioutil" for Input
Line 16,564:
}
runGame.call()</
{{out}}
Line 16,587:
=={{header|XPL0}}==
<
int Box(16), Moved;
Line 16,647:
until Moved;
];
]</
|