Snake: Difference between revisions

m
syntax highlighting fixup automation
(J: add animated movement)
m (syntax highlighting fixup automation)
Line 15:
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
<lang Ada>
-- This code is a basic implementation of snake in Ada using the command prompt
-- feel free to improve it!
Line 304:
Snake.run;
end;
</syntaxhighlight>
</lang>
 
{{out}}
Line 325:
=={{header|Amazing Hopper}}==
{{trans|C}}
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* Snake */
/* Implementing this task in Hopper-FLOW-MATIC++ */
Line 628:
PRNL("\OFF")
RET
</syntaxhighlight>
</lang>
{{out}}
Init game:
Line 728:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">gosub Init
Gui, +AlwaysOnTop
Gui, font, s12, consolas
Line 848:
return [oGrid, row, col]
}
;-----------------------------------------</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">
REM Snake
 
Line 969:
End
'--------------------------
</syntaxhighlight>
</lang>
 
==={{header|Locomotive Basic}}===
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).
<langsyntaxhighlight 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
30 f$=chr$(228):w$=chr$(127):b$=chr$(231)
Line 1,005:
280 if a$<>" " then 260
290 print f$;
300 return</langsyntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
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.
<langsyntaxhighlight lang="zxbasic"> 10 FOR i=0 TO 7
20 READ bits
30 POKE USR "L"+i,bits
Line 1,101:
870 DATA BIN 11111100
880 DATA BIN 01111111
890 DATA BIN 00110110</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="c">// Snake
 
// The problem with implementing this task in C is, the language standard
Line 1,247:
close_screen();
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Simple Windows console implementation.
[[File:SnakeCpp.png|200px|thumb|right]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <ctime>
Line 1,365:
snake s; s.play(); return 0;
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
Line 1,376:
{{libheader| Vcl.ExtCtrls}}
{{Trans|JavaScript}}
<syntaxhighlight lang="delphi">
<lang Delphi>
unit SnakeGame;
 
Line 1,732:
FrameTimer.Enabled := True;
end;
end.</langsyntaxhighlight>
Form resources:
<syntaxhighlight lang="delphi">
<lang Delphi>
object SnakeApp: TSnakeApp
OnCreate = FormCreate
end
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
Line 1,746:
FreeBSD, OpenBSD, NetBSD, DragonFly BSD, Linux, MS Windows, and MacOS
(tested on FreeBSD and MS Windows).
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,980:
snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}
food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}
)</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">{-# LANGUAGE TemplateHaskell #-}
import Control.Monad.Random (getRandomRs)
import Graphics.Gloss.Interface.Pure.Game
Line 2,082:
main = do world <- createWorld
play inW white 7 world renderWorld handleEvents updateWorld
where inW = InWindow "The Snake" (400, 400) (10, 10)</langsyntaxhighlight>
 
'''Extra credit'''
Line 2,088:
It is easy to make snake to seek food automatically. Just change the first line of the <code>updateWorld</code> definition:
 
<langsyntaxhighlight lang="haskell">updateWorld _ = id >>> snakeSeeksFood >>> (snakeEats <|> snakeMoves) </langsyntaxhighlight>
 
and add local definition:
 
<langsyntaxhighlight lang="haskell"> snakeSeeksFood w = w & snake .& turns optimalDirection
where
optimalDirection = minimumBy (comparing distanceToFood) safeTurns
Line 2,104:
distanceToFood d = let (a,b) = w^.snake & turns d & moves & (^.body) & head
(x,y) = w^.food & head
in (a-x)^2 + (b-y)^2</langsyntaxhighlight>
 
=={{header|J}}==
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.
 
<langsyntaxhighlight Jlang="j">require'ide/qt/gl2'
coinsert 'jgl2'
 
Line 2,185:
end.
snake=: ,:_ _
}}</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,193:
=={{header|JavaScript}}==
You need the P5 Library to run this code!
<langsyntaxhighlight lang="javascript">
const L = 1, R = 2, D = 4, U = 8;
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake;
Line 2,301:
if( !snake.alive ) text( "THE END", 630, 250 );
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Makie version in 99 lines.
<langsyntaxhighlight lang="julia">using Makie
 
mutable struct SnakeGame
Line 2,405:
 
play()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|C++}}
{{works with|Windows 10}}
<langsyntaxhighlight lang="scala">// Kotlin Native v0.5
 
import kotlinx.cinterop.*
Line 2,591:
srand(time(null).toInt())
Snake().play()
}</langsyntaxhighlight>
 
{{output}}
Line 2,601:
[[File:snake-lua.png]]
{{works with|LÖVE}}
<langsyntaxhighlight Lualang="lua">UP, RIGHT, DOWN, LEFT = 1, 2, 3, 4
UpdateTime=0.200
Timer = 0
Line 2,768:
Head.nextDirection = iDirection
end
end</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 2,774:
{{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”.
<langsyntaxhighlight Nimlang="nim">import macros, os, random
import ncurses
 
Line 2,883:
 
sleep(1000)
closeScreen()</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,889:
{{libheader|OCamlSDL2}}
 
<langsyntaxhighlight lang="ocaml">(* A simple Snake Game *)
open Sdl
 
Line 3,042:
main_loop state
in
main_loop initial_state</langsyntaxhighlight>
 
=={{header|Perl}}==
[[File:Snake_game_perl.png|200px|thumb|right]]
<langsyntaxhighlight lang="perl">use utf8;
use Time::HiRes qw(sleep);
use Term::ANSIColor qw(colored);
Line 3,216:
elsif ($key eq "\e[C" and $dir ne LEFT ) { $dir = RIGHT }
elsif ($key eq "\e[D" and $dir ne RIGHT) { $dir = LEFT }
}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{trans|C++}}
<langsyntaxhighlight Phixlang="phix">constant W = 60, H = 30, MAX_LEN = 600
enum NORTH, EAST, SOUTH, WEST
 
Line 3,300:
end while
end procedure
play()</langsyntaxhighlight>
 
=={{header|Python}}==
Using Pygame. Works with Python >= 3.7.
<langsyntaxhighlight lang="python">from __future__ import annotations
 
import itertools
Line 3,565:
score = game.main()
print(score)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
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].
 
<syntaxhighlight lang="raku" perl6line>use SDL2::Raw;
use Cairo;
 
Line 3,746:
}
 
SDL_Quit();</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 3,756:
 
[http://github.com/rust-rosetta/rust-rosetta/blob/master/tasks/snake/SnkRust.png snake game screenshot]
<langsyntaxhighlight lang="fsharp">/* add to file Cargo.toml:
[dependencies]
winsafe = "0.0.8"
Line 3,926:
.unwrap();
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class SnakeGame(w, h) {
const readkey = frequire('Term::ReadKey')
const ansi = frequire('Term::ANSIColor')
Line 4,065:
var h = `tput lines`.to_i
 
SnakeGame(w || 80, h || 24).play</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 4,072:
{{libheader|Wren-dynamic}}
An embedded program so we can ask the C host to call ncurses and another library function for us.
<langsyntaxhighlight lang="ecmascript">/* snake.wren */
 
import "random" for Random
Line 4,207:
}
C.usleep(999 * 1000)
Ncurses.endwin()</langsyntaxhighlight>
<br>
Now embed this script in the following C program, compile and run it.
<langsyntaxhighlight lang="c">/* gcc snake.c -o snake -lncurses -lwren -lm */
 
#include <stdio.h>
Line 4,372:
free(script);
return 0;
}</langsyntaxhighlight>
 
=={{header|XPL0}}==
Line 4,386:
speed is currently set at nine steps per second.
 
<langsyntaxhighlight XPL0lang="xpl0">def Width=40, Height=25-1, \playing area including border
StartLength = 10, \starting length of snake including head
Morsels = 10; \number of food items constantly offered
Line 4,494:
Sound(0, 36, 1); \pause 2 seconds to see result
OpenI(1); \flush any pending keystrokes
]</langsyntaxhighlight>
10,343

edits