Snake: Difference between revisions
Content added Content deleted
(J: add animated movement) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 15: | Line 15: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<syntaxhighlight lang="ada"> |
|||
<lang Ada> |
|||
-- This code is a basic implementation of snake in Ada using the command prompt |
-- This code is a basic implementation of snake in Ada using the command prompt |
||
-- feel free to improve it! |
-- feel free to improve it! |
||
Line 304: | Line 304: | ||
Snake.run; |
Snake.run; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 325: | Line 325: | ||
=={{header|Amazing Hopper}}== |
=={{header|Amazing Hopper}}== |
||
{{trans|C}} |
{{trans|C}} |
||
<syntaxhighlight lang="amazing hopper"> |
|||
<lang Amazing Hopper> |
|||
/* Snake */ |
/* Snake */ |
||
/* Implementing this task in Hopper-FLOW-MATIC++ */ |
/* Implementing this task in Hopper-FLOW-MATIC++ */ |
||
Line 628: | Line 628: | ||
PRNL("\OFF") |
PRNL("\OFF") |
||
RET |
RET |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Init game: |
Init game: |
||
Line 728: | Line 728: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">gosub Init |
||
Gui, +AlwaysOnTop |
Gui, +AlwaysOnTop |
||
Gui, font, s12, consolas |
Gui, font, s12, consolas |
||
Line 848: | Line 848: | ||
return [oGrid, row, col] |
return [oGrid, row, col] |
||
} |
} |
||
;-----------------------------------------</ |
;-----------------------------------------</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
REM Snake |
REM Snake |
||
Line 969: | Line 969: | ||
End |
End |
||
'-------------------------- |
'-------------------------- |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Locomotive Basic}}=== |
==={{header|Locomotive Basic}}=== |
||
Line 976: | Line 976: | ||
If you are playing this in [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], first click on the CPC screen so it gets keyboard input and then enter "run" (clicking the Run button would deselect the screen again). |
If you are playing this in [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], first click on the CPC screen so it gets keyboard input and then enter "run" (clicking the Run button would deselect the screen again). |
||
< |
<syntaxhighlight lang="locobasic">10 mode 1:randomize time |
||
20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=6 |
20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=6 |
||
30 f$=chr$(228):w$=chr$(127):b$=chr$(231) |
30 f$=chr$(228):w$=chr$(127):b$=chr$(231) |
||
Line 1,005: | Line 1,005: | ||
280 if a$<>" " then 260 |
280 if a$<>" " then 260 |
||
290 print f$; |
290 print f$; |
||
300 return</ |
300 return</syntaxhighlight> |
||
==={{header|ZX Spectrum Basic}}=== |
==={{header|ZX Spectrum Basic}}=== |
||
Line 1,013: | Line 1,013: | ||
Note that lines <code>10</code> to <code>210</code> and <code>580</code> to <code>890</code>—more than half the program—define graphics characters for the snake's head (facing in different directions) and for its food. If you're happy to make do with characters from the standard character set, you can easily adapt lines <code>220</code> to <code>570</code> to work on their own. The things the snake eats are supposed to be apples, although they don't look too much like them. |
Note that lines <code>10</code> to <code>210</code> and <code>580</code> to <code>890</code>—more than half the program—define graphics characters for the snake's head (facing in different directions) and for its food. If you're happy to make do with characters from the standard character set, you can easily adapt lines <code>220</code> to <code>570</code> to work on their own. The things the snake eats are supposed to be apples, although they don't look too much like them. |
||
< |
<syntaxhighlight lang="zxbasic"> 10 FOR i=0 TO 7 |
||
20 READ bits |
20 READ bits |
||
30 POKE USR "L"+i,bits |
30 POKE USR "L"+i,bits |
||
Line 1,101: | Line 1,101: | ||
870 DATA BIN 11111100 |
870 DATA BIN 11111100 |
||
880 DATA BIN 01111111 |
880 DATA BIN 01111111 |
||
890 DATA BIN 00110110</ |
890 DATA BIN 00110110</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
As some implementation below (C++) works on Windows console, let it work on Linux. Other implementations could be added as well, reusing the api. |
As some implementation below (C++) works on Windows console, let it work on Linux. Other implementations could be added as well, reusing the api. |
||
< |
<syntaxhighlight lang="c">// Snake |
||
// The problem with implementing this task in C is, the language standard |
// The problem with implementing this task in C is, the language standard |
||
Line 1,247: | Line 1,247: | ||
close_screen(); |
close_screen(); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Simple Windows console implementation. |
Simple Windows console implementation. |
||
[[File:SnakeCpp.png|200px|thumb|right]] |
[[File:SnakeCpp.png|200px|thumb|right]] |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <windows.h> |
#include <windows.h> |
||
#include <ctime> |
#include <ctime> |
||
Line 1,365: | Line 1,365: | ||
snake s; s.play(); return 0; |
snake s; s.play(); return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| Winapi.Windows}} |
{{libheader| Winapi.Windows}} |
||
Line 1,376: | Line 1,376: | ||
{{libheader| Vcl.ExtCtrls}} |
{{libheader| Vcl.ExtCtrls}} |
||
{{Trans|JavaScript}} |
{{Trans|JavaScript}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
unit SnakeGame; |
unit SnakeGame; |
||
Line 1,732: | Line 1,732: | ||
FrameTimer.Enabled := True; |
FrameTimer.Enabled := True; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
Form resources: |
Form resources: |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
object SnakeApp: TSnakeApp |
object SnakeApp: TSnakeApp |
||
OnCreate = FormCreate |
OnCreate = FormCreate |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
Line 1,746: | Line 1,746: | ||
FreeBSD, OpenBSD, NetBSD, DragonFly BSD, Linux, MS Windows, and MacOS |
FreeBSD, OpenBSD, NetBSD, DragonFly BSD, Linux, MS Windows, and MacOS |
||
(tested on FreeBSD and MS Windows). |
(tested on FreeBSD and MS Windows). |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,980: | Line 1,980: | ||
snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold} |
snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold} |
||
food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed} |
food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed} |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">{-# LANGUAGE TemplateHaskell #-} |
||
import Control.Monad.Random (getRandomRs) |
import Control.Monad.Random (getRandomRs) |
||
import Graphics.Gloss.Interface.Pure.Game |
import Graphics.Gloss.Interface.Pure.Game |
||
Line 2,082: | Line 2,082: | ||
main = do world <- createWorld |
main = do world <- createWorld |
||
play inW white 7 world renderWorld handleEvents updateWorld |
play inW white 7 world renderWorld handleEvents updateWorld |
||
where inW = InWindow "The Snake" (400, 400) (10, 10)</ |
where inW = InWindow "The Snake" (400, 400) (10, 10)</syntaxhighlight> |
||
'''Extra credit''' |
'''Extra credit''' |
||
Line 2,088: | Line 2,088: | ||
It is easy to make snake to seek food automatically. Just change the first line of the <code>updateWorld</code> definition: |
It is easy to make snake to seek food automatically. Just change the first line of the <code>updateWorld</code> definition: |
||
< |
<syntaxhighlight lang="haskell">updateWorld _ = id >>> snakeSeeksFood >>> (snakeEats <|> snakeMoves) </syntaxhighlight> |
||
and add local definition: |
and add local definition: |
||
< |
<syntaxhighlight lang="haskell"> snakeSeeksFood w = w & snake .& turns optimalDirection |
||
where |
where |
||
optimalDirection = minimumBy (comparing distanceToFood) safeTurns |
optimalDirection = minimumBy (comparing distanceToFood) safeTurns |
||
Line 2,104: | Line 2,104: | ||
distanceToFood d = let (a,b) = w^.snake & turns d & moves & (^.body) & head |
distanceToFood d = let (a,b) = w^.snake & turns d & moves & (^.body) & head |
||
(x,y) = w^.food & head |
(x,y) = w^.food & head |
||
in (a-x)^2 + (b-y)^2</ |
in (a-x)^2 + (b-y)^2</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 2,116: | Line 2,116: | ||
In this implementation, speed is fixed (and final score is by the update rate). Another approach might be to start slow and gradually speed based on the length of the snake. Those sorts of changes are left as an exercise for the reader. |
In this implementation, speed is fixed (and final score is by the update rate). Another approach might be to start slow and gradually speed based on the length of the snake. Those sorts of changes are left as an exercise for the reader. |
||
< |
<syntaxhighlight lang="j">require'ide/qt/gl2' |
||
coinsert 'jgl2' |
coinsert 'jgl2' |
||
Line 2,185: | Line 2,185: | ||
end. |
end. |
||
snake=: ,:_ _ |
snake=: ,:_ _ |
||
}}</ |
}}</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 2,193: | Line 2,193: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
You need the P5 Library to run this code! |
You need the P5 Library to run this code! |
||
< |
<syntaxhighlight lang="javascript"> |
||
const L = 1, R = 2, D = 4, U = 8; |
const L = 1, R = 2, D = 4, U = 8; |
||
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake; |
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake; |
||
Line 2,301: | Line 2,301: | ||
if( !snake.alive ) text( "THE END", 630, 250 ); |
if( !snake.alive ) text( "THE END", 630, 250 ); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Makie version in 99 lines. |
Makie version in 99 lines. |
||
< |
<syntaxhighlight lang="julia">using Makie |
||
mutable struct SnakeGame |
mutable struct SnakeGame |
||
Line 2,405: | Line 2,405: | ||
play() |
play() |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|C++}} |
{{trans|C++}} |
||
{{works with|Windows 10}} |
{{works with|Windows 10}} |
||
< |
<syntaxhighlight lang="scala">// Kotlin Native v0.5 |
||
import kotlinx.cinterop.* |
import kotlinx.cinterop.* |
||
Line 2,591: | Line 2,591: | ||
srand(time(null).toInt()) |
srand(time(null).toInt()) |
||
Snake().play() |
Snake().play() |
||
}</ |
}</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 2,601: | Line 2,601: | ||
[[File:snake-lua.png]] |
[[File:snake-lua.png]] |
||
{{works with|LÖVE}} |
{{works with|LÖVE}} |
||
< |
<syntaxhighlight lang="lua">UP, RIGHT, DOWN, LEFT = 1, 2, 3, 4 |
||
UpdateTime=0.200 |
UpdateTime=0.200 |
||
Timer = 0 |
Timer = 0 |
||
Line 2,768: | Line 2,768: | ||
Head.nextDirection = iDirection |
Head.nextDirection = iDirection |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Line 2,774: | Line 2,774: | ||
{{libheader|nim-ncurses}} |
{{libheader|nim-ncurses}} |
||
As in the C version, the code is provided for Linux. We use the tiny API defined in the C version, only adjusted to work with Nim and the library “nim-ncurses”. |
As in the C version, the code is provided for Linux. We use the tiny API defined in the C version, only adjusted to work with Nim and the library “nim-ncurses”. |
||
< |
<syntaxhighlight lang="nim">import macros, os, random |
||
import ncurses |
import ncurses |
||
Line 2,883: | Line 2,883: | ||
sleep(1000) |
sleep(1000) |
||
closeScreen()</ |
closeScreen()</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 2,889: | Line 2,889: | ||
{{libheader|OCamlSDL2}} |
{{libheader|OCamlSDL2}} |
||
< |
<syntaxhighlight lang="ocaml">(* A simple Snake Game *) |
||
open Sdl |
open Sdl |
||
Line 3,042: | Line 3,042: | ||
main_loop state |
main_loop state |
||
in |
in |
||
main_loop initial_state</ |
main_loop initial_state</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
[[File:Snake_game_perl.png|200px|thumb|right]] |
[[File:Snake_game_perl.png|200px|thumb|right]] |
||
< |
<syntaxhighlight lang="perl">use utf8; |
||
use Time::HiRes qw(sleep); |
use Time::HiRes qw(sleep); |
||
use Term::ANSIColor qw(colored); |
use Term::ANSIColor qw(colored); |
||
Line 3,216: | Line 3,216: | ||
elsif ($key eq "\e[C" and $dir ne LEFT ) { $dir = RIGHT } |
elsif ($key eq "\e[C" and $dir ne LEFT ) { $dir = RIGHT } |
||
elsif ($key eq "\e[D" and $dir ne RIGHT) { $dir = LEFT } |
elsif ($key eq "\e[D" and $dir ne RIGHT) { $dir = LEFT } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{trans|C++}} |
{{trans|C++}} |
||
< |
<syntaxhighlight lang="phix">constant W = 60, H = 30, MAX_LEN = 600 |
||
enum NORTH, EAST, SOUTH, WEST |
enum NORTH, EAST, SOUTH, WEST |
||
Line 3,300: | Line 3,300: | ||
end while |
end while |
||
end procedure |
end procedure |
||
play()</ |
play()</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Using Pygame. Works with Python >= 3.7. |
Using Pygame. Works with Python >= 3.7. |
||
< |
<syntaxhighlight lang="python">from __future__ import annotations |
||
import itertools |
import itertools |
||
Line 3,565: | Line 3,565: | ||
score = game.main() |
score = game.main() |
||
print(score) |
print(score) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 3,572: | Line 3,572: | ||
This is a variation of a demo script included in the examples folder for the Raku [https://modules.raku.org/search/?q=SDL2%3A%3ARaw SDL2::Raw library bindings]. |
This is a variation of a demo script included in the examples folder for the Raku [https://modules.raku.org/search/?q=SDL2%3A%3ARaw SDL2::Raw library bindings]. |
||
<lang |
<syntaxhighlight lang="raku" line>use SDL2::Raw; |
||
use Cairo; |
use Cairo; |
||
Line 3,746: | Line 3,746: | ||
} |
} |
||
SDL_Quit();</ |
SDL_Quit();</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Line 3,756: | Line 3,756: | ||
[http://github.com/rust-rosetta/rust-rosetta/blob/master/tasks/snake/SnkRust.png snake game screenshot] |
[http://github.com/rust-rosetta/rust-rosetta/blob/master/tasks/snake/SnkRust.png snake game screenshot] |
||
< |
<syntaxhighlight lang="fsharp">/* add to file Cargo.toml: |
||
[dependencies] |
[dependencies] |
||
winsafe = "0.0.8" |
winsafe = "0.0.8" |
||
Line 3,926: | Line 3,926: | ||
.unwrap(); |
.unwrap(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">class SnakeGame(w, h) { |
||
const readkey = frequire('Term::ReadKey') |
const readkey = frequire('Term::ReadKey') |
||
const ansi = frequire('Term::ANSIColor') |
const ansi = frequire('Term::ANSIColor') |
||
Line 4,065: | Line 4,065: | ||
var h = `tput lines`.to_i |
var h = `tput lines`.to_i |
||
SnakeGame(w || 80, h || 24).play</ |
SnakeGame(w || 80, h || 24).play</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Line 4,072: | Line 4,072: | ||
{{libheader|Wren-dynamic}} |
{{libheader|Wren-dynamic}} |
||
An embedded program so we can ask the C host to call ncurses and another library function for us. |
An embedded program so we can ask the C host to call ncurses and another library function for us. |
||
< |
<syntaxhighlight lang="ecmascript">/* snake.wren */ |
||
import "random" for Random |
import "random" for Random |
||
Line 4,207: | Line 4,207: | ||
} |
} |
||
C.usleep(999 * 1000) |
C.usleep(999 * 1000) |
||
Ncurses.endwin()</ |
Ncurses.endwin()</syntaxhighlight> |
||
<br> |
<br> |
||
Now embed this script in the following C program, compile and run it. |
Now embed this script in the following C program, compile and run it. |
||
< |
<syntaxhighlight lang="c">/* gcc snake.c -o snake -lncurses -lwren -lm */ |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 4,372: | Line 4,372: | ||
free(script); |
free(script); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
Line 4,386: | Line 4,386: | ||
speed is currently set at nine steps per second. |
speed is currently set at nine steps per second. |
||
< |
<syntaxhighlight lang="xpl0">def Width=40, Height=25-1, \playing area including border |
||
StartLength = 10, \starting length of snake including head |
StartLength = 10, \starting length of snake including head |
||
Morsels = 10; \number of food items constantly offered |
Morsels = 10; \number of food items constantly offered |
||
Line 4,494: | Line 4,494: | ||
Sound(0, 36, 1); \pause 2 seconds to see result |
Sound(0, 36, 1); \pause 2 seconds to see result |
||
OpenI(1); \flush any pending keystrokes |
OpenI(1); \flush any pending keystrokes |
||
]</ |
]</syntaxhighlight> |