Joystick position: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(32 intermediate revisions by 18 users not shown)
Line 20:
For the purpose of this task, we assume that the joystick is calibrated and that the first joystick is being used. <br>
The task implementer could at their option provide a solution that includes a joystick selection facility, enabling the user to choose which joystick is to be used for this task.
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE lastStick=[255]
BYTE lastTrig=[255]
 
PROC DrawCross(BYTE s)
BYTE size=[5]
CARD x
BYTE y
 
IF s>=9 AND s<=11 THEN
x=size
ELSEIF s>=5 AND s<=7 THEN
x=159-size
ELSE
x=79
FI
 
IF s=6 OR s=10 OR s=14 THEN
y=size
ELSEIF s=5 OR s=9 OR s=13 THEN
y=79-size
ELSE
y=39
FI
Plot(x-size,y)
DrawTo(x+size,y)
Plot(x,y-size)
DrawTo(x,y+size)
RETURN
 
PROC UpdateStatus(BYTE currStick,currTrig)
IF currStick#lastStick THEN
Color=0 DrawCross(lastStick)
Color=1 DrawCross(currStick)
lastStick=currStick
FI
 
IF currTrig#lastTrig THEN
Print("Button pressed: ")
IF currTrig THEN
PrintE("no ")
ELSE
PrintE("yes")
FI
Put(28) ;move cursor up
lastTrig=currTrig
FI
RETURN
 
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6,
CRSINH=$02F0 ;Controls visibility of cursor
BYTE currStick,currTrig
 
Graphics(7)
Color=1
COLOR1=$0C
COLOR2=$02
CRSINH=1 ;hide cursor
 
DO
currStick=Stick(0)
currTrig=STrig(0)
UpdateStatus(currStick,currTrig)
UNTIL CH#$FF
OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Joystick_position.png Screenshot from Atari 8-bit computer]
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 GOSUB 400
110 P2 = PDL(2) : IF P2 <> O2 THEN O2 = P2 : VTAB 23 : HTAB 33 : PRINT P2; TAB(37);
120 B2 = FNB(2) : IF B2 <> N2 THEN N2 = B2 : VTAB 24 : HTAB 15 : PRINT P$(B2);
Line 59 ⟶ 131:
550 ROT = 0 : SCALE = 7 : XDRAW 1 AT X1, Y1
560 O0 = -1 : O1 = O0 : O2 = O0 : O3 = O0
570 RETURN</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 67 ⟶ 139:
 
[http://i.imgur.com/KsbrpK4.png Image link]
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Uncomment if Gdip.ahk is not in your standard library
; #Include, Gdip.ahk
 
Line 285 ⟶ 357:
Exit:
Gdip_Shutdown(pToken)
ExitApp</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> VDU 23,22,512;512;8,16,16,0
VDU 5
Line 311 ⟶ 383:
VDU 10,13
NEXT
ENDPROC</langsyntaxhighlight>
 
 
 
=={{header|C}}==
<syntaxhighlight lang="cpp">#include <stdio.h>
#include <stdlib.h>
 
void clear() {
for(int n = 0;n < 10; n++) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
}
}
 
#define UP "00^00\r\n00|00\r\n00000\r\n"
#define DOWN "00000\r\n00|00\r\n00v00\r\n"
#define LEFT "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\n"
#define HOME "00000\r\n00+00\r\n00000\r\n"
 
int main() {
clear();
system("stty raw");
 
printf(HOME);
printf("space to exit; wasd to move\r\n");
char c = 1;
 
while(c) {
c = getc(stdin);
clear();
 
switch (c)
{
case 'a':
printf(LEFT);
break;
case 'd':
printf(RIGHT);
break;
case 'w':
printf(UP);
break;
case 's':
printf(DOWN);
break;
case ' ':
c = 0;
break;
default:
printf(HOME);
};
 
printf("space to exit; wasd key to move\r\n");
}
 
system("stty cooked");
system("clear");
return 1;
}</syntaxhighlight>
 
{{out}}
<pre>
 
</pre>
 
=={{header|Commodore BASIC}}==
 
===Commodore VIC-20===
 
The VIC-20 has only one control port. Even still, to be able to read ''all'' the possible inputs, we have to poll two different registers. VIA #1 handles most of the joystick inputs, VIA #2 handles the "right direction" input line. For proper operation, we must set the data direction on VIA#2 to input on bit 7 of the Port B register, and then return it to output when the program is completed in order to re-enable full function of the keyboard.
 
This program maps the values from both registers to bits 0 through 4 of a single byte so that logic is evaluated identical to the C-64 example below.
 
<syntaxhighlight lang="commodorebasicv2">5 rem joystick - commodore vic-20 (expanded)
6 rem for rosetta code
10 print chr$(147);:poke 37154,peek(37154) and 127
15 j1=37137:j2=37152:sc=4118:co=37910:x=11:y=11
20 poke sc+x+y*22,43:poke co+x+y*22,0
25 j=(not peek(j1) and28)/4
30 j=j+(not peek(j1) and32)/2
35 j=j+(not peek(j2) and128)/16
40 print chr$(19);"joy: ";
45 get k$:if k$="q" then print chr$(147):poke 37154,peek(37154)or128:end
50 ox=x:oy=y
60 if(j and 1) then y=1:ud$="u"
61 if(j and 2) then y=21:ud$="d"
62 if(j and 3)=0 then y=11:ud$=" "
63 if(j and 4) then x=0:lr$="l"
64 if(j and 8) then x=21:lr$="r"
65 if(j and 12)=0 then x=11:lr$=" "
66 if(j and 16) then f$="fire!":c=24
67 if(j and 16)=0 then f$=" ":c=43
70 print tab(5);ud$;tab(7);lr$;tab(9);f$;
75 poke sc+x+y*22,c:poke co+x+y*22,0
80 if (ox=x) and (oy=y) then goto 100
85 poke sc+ox+oy*22,32
100 goto 25</syntaxhighlight>
 
===Commodore 64===
 
On the Commodore 64, both joystick ports can be read from registers on the CIA#1 6526 chip. This will report binary input from the joystick control ports in bits 0 through 4 (four directions plus a single fire or action button.) Control Port 1 is read from location 56321 and Control Port 2 is read from location 56320.
 
<syntaxhighlight lang="commodorebasicv2">5 rem joystick - commodore 64
6 rem for rosetta code
8 rem black bkg, white text, dk. grey border
9 poke 53280,11:poke 53281,0:poke 646,1
10 print chr$(147);"joystick port 1 or 2";:input jp
11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10
12 jp=(jp=2)+56321:print chr$(147);
15 sc=1024:x=20:y=12:poke sc+x+y*40,43
20 j=not peek(jp) and 31
25 print chr$(19);"{CRSR DOWN 24}joy status: ";
26 get k$:if k$="q" then print chr$(147):end
35 ox=x:oy=y
40 if(j and 1) then y=0:ud$="up "
45 if(j and 2) then y=23:ud$="down"
46 if(j and 3)=0 then y=12:ud$=" "
50 if(j and 4) then x=0:lr$="left "
55 if(j and 8) then x=39:lr$="right"
56 if(j and 12)=0 then x=20:lr$=" "
60 if(j and 16) then f$="fire!":c=24
61 if(j and 16)=0 then f$=" ":c=43
65 print tab(12);ud$;tab(17);lr$;tab(23);f$;
85 poke sc+x+y*40,c:if (ox=x) and (oy=y) then goto 100
90 poke sc+ox+oy*40,32
100 goto 20</syntaxhighlight>
 
===Commodore Plus/4===
 
The Commodore Plus/4 has the JOY(''n'') function available in BASIC v3.5 to read the position of a joystick plugged into control port ''n''. The return value is a number 1 through 8 corresponding to each unique direction in a clockwise order, beginning with "up" returning a value of "1". Bit 7 of the return value will report the status of the fire button.
 
<syntaxhighlight lang="gwbasic">5 rem joystick - commodore plus/4
6 rem for rosetta code
8 rem black bkg, white text, dk. grey border
9 color 0,1:color 4,2,1:color 1,2,7
10 print chr$(147);"joystick port 1 or 2";:input jp
11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10
12 print chr$(147);
15 sc=3072:x=20:y=13:poke sc+x+y*40,43
20 j=joy(jp)
25 print chr$(19);"joy status: ";
26 get k$:if k$="q" then print chr$(147):end
35 ox=x:oy=y
40 if(j and 15)=1 then d$="up ":x=20:y=1:goto 48
41 if(j and 15)=2 then d$="up right":x=39:y=1:goto 48
42 if(j and 15)=3 then d$=" right":x=39:y=13:goto 48
43 if(j and 15)=4 then d$="down right":x=39:y=24:goto 48
44 if(j and 15)=5 then d$="down ":x=20:y=24:goto 48
45 if(j and 15)=6 then d$="down left ":x=0:y=24:goto 48
46 if(j and 15)=7 then d$=" left ":x=0:y=13:goto 48
47 if(j and 15)=8 then d$="up left ":x=0:y=1
48 if(j and 128) then f$="fire!":c=24
49 if(j and 128)=0 then f$=" ":c=43
50 if(j=0) then d$=" ":x=20:y=13
65 print tab(12);d$;tab(23);f$;
85 poke sc+x+y*40,c:if (ox=x) and (oy=y) then goto 100
90 poke sc+ox+oy*40,32
100 goto 20</syntaxhighlight>
 
===Commodore 128===
 
BASIC 7.0 retains the same functionality of BASIC 3.5 on the Plus/4 for reading the joystick port(s). The C128 can take advantage of dual screen output.
 
<syntaxhighlight lang="gwbasic">5 rem joystick - commodore 128
6 rem for rosetta code
8 rem black bkg, white text, dk. grey border
9 color 0,1:color 4,12:color 1,2:graphic 0:scnclr 0:graphic 5
10 print chr$(147);"joystick port 1 or 2";:input jp
11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10
12 print chr$(147);
15 sc=1024:x=20:y=12:poke sc+x+y*40,43
20 j=joy(jp)
25 print chr$(19);"joy status: ";
26 get k$:if k$="q" then print chr$(147):end
35 ox=x:oy=y
40 if(j and 15)=1 then d$="up ":x=20:y=0:goto 48
41 if(j and 15)=2 then d$="up right":x=39:y=0:goto 48
42 if(j and 15)=3 then d$=" right":x=39:y=12:goto 48
43 if(j and 15)=4 then d$="down right":x=39:y=24:goto 48
44 if(j and 15)=5 then d$="down ":x=20:y=24:goto 48
45 if(j and 15)=6 then d$="down left ":x=0:y=24:goto 48
46 if(j and 15)=7 then d$=" left ":x=0:y=12:goto 48
47 if(j and 15)=8 then d$="up left ":x=0:y=0
48 if(j and 128) then f$="fire!":c=24
49 if(j and 128)=0 then f$=" ":c=43
50 if(j=0) then d$=" ":x=20:y=12
65 print tab(12);d$;tab(23);f$;
85 poke sc+x+y*40,c:if (ox=x) and (oy=y)then goto 100
90 poke sc+ox+oy*40,32
100 goto 20</syntaxhighlight>
=={{header|Delphi}}==
{{libheader|mmSystem}}
Form application version.
<syntaxhighlight lang="delphi">
unit uMain;
 
interface
 
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms,
Vcl.ExtCtrls, Vcl.StdCtrls;
 
type
TForm1 = class(TForm)
tmr1: TTimer;
lblPosition: TLabel;
procedure tmr1Timer(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure DrawCrosshair(X, Y: Integer);
end;
 
var
Form1: TForm1;
X: Integer = 0;
Y: Integer = 0;
 
implementation
 
uses
mmSystem, Vcl.Graphics;
 
{$R *.dfm}
 
procedure TForm1.DrawCrosshair(X, Y: Integer);
const
RADIUS = 10;
CROSS = 3;
begin
Canvas.Brush.Color := clblack;
Canvas.FillRect(ClientRect);
with Canvas do
begin
Pen.Color := clWhite;
pen.Width := 1;
Ellipse(X - RADIUS, Y - RADIUS, X + RADIUS, Y + RADIUS);
pen.Width := 2;
MoveTo(X - CROSS * RADIUS, Y);
LineTo(X + CROSS * RADIUS, Y);
MoveTo(X, Y - CROSS * RADIUS);
LineTo(X, Y + CROSS * RADIUS);
end;
end;
 
procedure TForm1.FormPaint(Sender: TObject);
begin
DrawCrosshair(X, Y);
end;
 
procedure TForm1.tmr1Timer(Sender: TObject);
var
info: TJoyInfo;
begin
if (joyGetPos(0, @info) = 0) then
begin
X := Round(ClientWidth * info.wXpos / MAXWORD);
Y := Round(ClientHeight * info.wYpos / MAXWORD);
lblPosition.Caption := Format('(%3d,%3d)', [X, Y]);
Invalidate;
end;
end;
 
end.
</syntaxhighlight>
Form resource:
<syntaxhighlight lang="delphi">
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 600
ClientWidth = 600
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnPaint = FormPaint
PixelsPerInch = 96
TextHeight = 13
object lblPosition: TLabel
Left = 500
Top = 0
Width = 100
Height = 21
Alignment = taCenter
AutoSize = False
Caption = '(0,0)'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -20
Font.Name = 'Tahoma'
Font.Style = []
ParentFont = False
end
object tmr1: TTimer
Interval = 500
OnTimer = tmr1Timer
end
end
</syntaxhighlight>
{{out}}
Result preview [https://ibb.co/tc0xH3q]
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Screen 12
 
Dim As Single x, y
Dim As Integer buttons, result
 
Const JoystickID = 0
 
'This line checks to see if the joystick is ok.
If Getjoystick(JoystickID, buttons, x, y) Then
Print "Joystick doesn't exist or joystick error."
Print !"\nPress any key to continue."
Sleep
End
End If
 
Do
result = Getjoystick(JoystickID, buttons, x, y)
Locate 1,1
Print ; "result:"; result; " x:"; x; " y:"; y; " Buttons:"; buttons, "", "", ""
'This tests to see which buttons from 1 to 27 are pressed.
For a As Integer = 0 To 26
If (buttons And (1 Shl a)) Then
Print "Button "; a; " pressed. "
Else
Print "Button "; a; " not pressed."
End If
Next a
Loop</syntaxhighlight>
 
 
=={{header|Go}}==
{{libheader|termbox-go}}
{{libheader|joystick(go)}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"github.com/nsf/termbox-go"
"github.com/simulatedsimian/joystick"
"log"
"os"
"strconv"
"time"
)
 
func printAt(x, y int, s string) {
for _, r := range s {
termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)
x++
}
}
 
func readJoystick(js joystick.Joystick, hidden bool) {
jinfo, err := js.Read()
check(err)
 
w, h := termbox.Size()
tbcd := termbox.ColorDefault
termbox.Clear(tbcd, tbcd)
printAt(1, h-1, "q - quit")
if hidden {
printAt(11, h-1, "s - show buttons:")
} else {
bs := ""
printAt(11, h-1, "h - hide buttons:")
for button := 0; button < js.ButtonCount(); button++ {
if jinfo.Buttons&(1<<uint32(button)) != 0 {
// Buttons assumed to be numbered from 1, not 0.
bs += fmt.Sprintf(" %X", button+1)
}
}
printAt(28, h-1, bs)
}
 
// Map axis values in range -32767 to +32768 to termbox co-ordinates.
x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)
y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)
printAt(x, y, "+") // display crosshair
termbox.Flush()
}
 
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
 
func main() {
// Under Linux the id is used to construct the joystick device name.
// For example: id 0 will open device: "/dev/input/js0"
// Under Windows the id is the actual numeric id of the joystick.
jsid := 0
// Optionally pass joystick id to be used as a command line argument.
if len(os.Args) > 1 {
i, err := strconv.Atoi(os.Args[1])
check(err)
jsid = i
}
 
js, jserr := joystick.Open(jsid)
check(jserr)
err := termbox.Init()
check(err)
defer termbox.Close()
 
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
 
ticker := time.NewTicker(time.Millisecond * 40)
hidden := false // Controls whether button display hidden or not.
 
for doQuit := false; !doQuit; {
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'q' {
doQuit = true
} else if ev.Ch == 'h' {
hidden = true
} else if ev.Ch == 's' {
hidden = false
}
}
if ev.Type == termbox.EventResize {
termbox.Flush()
}
case <-ticker.C:
readJoystick(js, hidden)
}
}
}</syntaxhighlight>
 
=={{header|GUISS}}==
Graphical User Interface Support Script only makes use of installed applications. So for this task, we use the joystick calibration routine, which shows a joystick position indicator:
 
<langsyntaxhighlight lang="guiss">Start,Control Panel, Game Controllers, List:installed controllers,Click:Joystick,
Button:Properties,Button:Test</langsyntaxhighlight>
 
=={{header|Haskell}}==
Half-solution of the problem, exhibits X and Y coordinates of the joystick; works on Windows (Haskell Platform):
 
<syntaxhighlight lang="haskell">import qualified Graphics.UI.GLFW as GLFW -- cabal install GLFW-b
import Graphics.Win32.Key
import Control.Monad.RWS.Strict (liftIO)
 
main = do
liftIO $ do
_ <- GLFW.init
GLFW.pollEvents
(jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1
putStrLn $ (show jxrot) ++ " " ++ (show jyrot)
w <- getAsyncKeyState 27 -- ESC pressed?
if (w<1) then main else do
GLFW.terminate
return ()
getJoystickDirections :: GLFW.Joystick -> IO (Double, Double)
 
getJoystickDirections js = do
maxes <- GLFW.getJoystickAxes js
return $ case maxes of
(Just (x:y:_)) -> (-y, x)
_ -> ( 0, 0)
</syntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 CLEAR SCREEN
110 DO
120 LET J=JOY(0) OR JOY(1) OR JOY(2)
130 PRINT AT 1,1:" ";:PRINT AT 1,1:"";
140 IF J BAND 1 THEN PRINT "right ";
150 IF J BAND 2 THEN PRINT "left ";
160 IF J BAND 4 THEN PRINT "down ";
170 IF J BAND 8 THEN PRINT "up ";
180 IF J BAND 16 THEN PRINT "fire ";
190 LOOP</syntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using CSFML.LibCSFML, Gtk.ShortNames, Colors, Graphics, Cairo
 
#------------ input code ----------------------#
 
mutable struct Joystick
devnum::Int
isconnected::Bool
hasXaxis::Bool
nbuttons::Int
pressed::Vector{Bool}
ypos::Int
xpos::Int
name::String
Joystick(n, b=2, c=false, x=true) = new(n, c, x, b, fill(false, b), 0, 0)
end
 
const devnum = 0
const buttons = 2
const jstick = Joystick(devnum, buttons)
 
function polljoystick(jstick, sleepinterval=0.05)
while !sfJoystick_isConnected(jstick.devnum)
sleep(0.25) # wait till connected
sfJoystick_update()
end
jstick.name = sfJoystick_getIdentification(jstick.devnum).name
jstick.isconnected = true
jstick.hasXaxis = sfJoystick_hasAxis(jstick.devnum, 0)
jstick.nbuttons = sfJoystick_getButtonCount(jstick.devnum)
while true
sfJoystick_update()
for i in 1:jstick.nbuttons
jstick.pressed[i] = sfJoystick_isButtonPressed(jstick.devnum, i - 1)
end
jstick.ypos = sfJoystick_getAxisPosition(jstick.devnum, 1)
jstick.xpos = sfJoystick_getAxisPosition(joystick.devnum, 0)
yield()
sleep(sleepinterval)
end
end
 
#------------ output code -------------------#
 
makelabel() = "Button 1: " * (jstick.pressed[1] ? "DOWN" : "UP") *
" Button 2: " * (jstick.pressed[2] ? "DOWN" : "UP")
 
const fontpointsize = 80
const wid = 500
const hei = 500
win = Window("Cursor Task", wid, hei) |> (Frame() |> (vbox = Box(:v)))
set_gtk_property!(vbox, :expand, true)
can = Canvas(wid, hei)
label = Label(makelabel())
push!(vbox, can, label)
 
joytoxpos() = div((jstick.xpos + 100) * width(can), 200)
joytoypos() = div((jstick.ypos + 100) * height(can), 200)
Gtk.showall(win)
 
@guarded draw(can) do widget
ctx = getgc(can)
select_font_face(ctx, "Courier", Cairo.FONT_SLANT_NORMAL, Cairo.FONT_WEIGHT_BOLD)
set_font_size(ctx, fontpointsize)
set_source(ctx, colorant"red")
move_to(ctx, joytoxpos(), joytoypos())
show_text(ctx, "+")
set_gtk_property!(label, :label, makelabel())
end
 
@async polljoystick(jstick)
 
while true
draw(can)
sleep(0.2)
yield()
end
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> 'disable text window
nomainwin
 
Line 391 ⟶ 1,030:
close #m
unloadbmp "plus"
end</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
<langsyntaxhighlight lang="locobasic">10 MODE 1:BORDER 14:x=320:y=200:d=1
20 a=JOY(0) ' read state of first joystick
30 IF d THEN q$="*" ELSE q$=" "
Line 406 ⟶ 1,045:
110 IF a<16 THEN LOCATE 1,1:PRINT " ":PRINT " "
120 MOVE x-8,y+8:TAG:PRINT "X";:TAGOFF
130 GOTO 20</langsyntaxhighlight>
 
Output (this version supports drawing with the cursor):
Line 412 ⟶ 1,051:
[[File:CPC drawing with joystick.png]]
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Slider2D[Dynamic[ControllerState[{"X", "Y"}]], ImageSize -> {500, 500}]</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
{{libheader|SFML}}
{{libheader|ocaml-sfml}}
 
<syntaxhighlight lang="ocaml">let remove x = List.filter (fun y -> y <> x)
Using the SFML with its OCaml bindings [http://ocaml-sfml.forge.ocamlcore.org/ ocaml-sfml]:
 
<lang ocaml>let remove x = List.filter (fun y -> y <> x)
let buttons_string b =
String.concat " " (List.map string_of_int b)
 
let position app x y =
let view = SFRenderWindow.getView app in
Line 432 ⟶ 1,070:
(hw +. ((x /. 100.0) *. hw),
hh +. ((y /. 100.0) *. hh))
 
let cross =
[| 1.0, 1.0; 10.0, 1.0; 10.0, -1.0; 1.0, -1.0;
1.0, -10.0; -1.0, -10.0; -1.0, -1.0; -10.0, -1.0;
-10.0, 1.0; -1.0, 1.0; -1.0, 10.0; 1.0, 10.0; |]
 
let () =
let app = SFRenderWindow.make (800, 600) "Joystick Position" in
Line 448 ⟶ 1,086:
SFText.setString text (buttons_string b);
let x, y = position app x y in
SFShape.setPosition shape (x, y);
SFRenderWindow.clear app SFColor.black;
SFRenderWindow.drawText app text ();
Line 457 ⟶ 1,095:
| SFEvent.JoystickButtonPressed (0, button) -> ((x, y), button::b)
| SFEvent.JoystickButtonReleased (0, button) -> ((x, y), remove button b)
| SFEvent.JoystickMoved (0, SFEventSFJoystick.JoystickXX, av) -> ((av, y), b)
| SFEvent.JoystickMoved (0, SFEventSFJoystick.JoystickYY, av) -> ((x, av), b)
| _ -> joyd
in
Line 474 ⟶ 1,112:
proc_event joyd
in
loop ((0.0, 0.0), [])</langsyntaxhighlight>
 
Run with the command:
$ ocaml -I /tmp/ocaml-sfml/src sfml_system.cma sfml_window.cma sfml_graphics.cma joy.ml
 
=={{header|Phix}}==
Windows only, taken from the [http://phix.x10.mx/pmwiki/pmwiki.php?n=Main.JoystickPadLibrary JoystickPadLibrary on PCAN]
 
First, joy.e:
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #000080;font-style:italic;">-- Joystick library for Euphoria (Windows)
-- /Mic, 2002
--
-- integer joy_init()
-- returns the number of joysticks attached to the computer
--
-- sequence joy_get_state(integer joy_num)
-- returns the current state of joystick #joy_num (can be either 1 or 2).
-- the format of the return sequence is:
-- {X_direction, Y_direction, Z_direction, buttons}
-- the X,Y and Z directions have 3 possible values; 0 (negative), 32768 (neutral) or 65535 (positive)
-- the buttons' status are represented by a single bit (button up, button down). e.g. to get the status
-- of button #3 on joystick #1 you'd use:
-- sequence state
-- state = joy_get_state(1)
-- if and_bits(state[4],4) then ... end if
--</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">dll</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">machine</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">joyinfo</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">allocate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">32</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">winmm</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">joyGetNumDevs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joyGetPos</span>
<span style="color: #000000;">winmm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">open_dll</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"winmm.dll"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">winmm</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Unable to open winmm.dll"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">joyGetNumDevs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">define_c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">winmm</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"joyGetNumDevs"</span><span style="color: #0000FF;">,{},</span><span style="color: #000000;">C_UINT</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">joyGetPos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">define_c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">winmm</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"joyGetPos"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">C_INT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">C_POINTER</span><span style="color: #0000FF;">},</span><span style="color: #000000;">C_INT</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetNumDevs</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetPos</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Unable to link functions"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">joy_init</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">joy1Attached</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joy2Attached</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">numDevs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetNumDevs</span><span style="color: #0000FF;">,{})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">numDevs</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">joy1Attached</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetPos</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joyinfo</span><span style="color: #0000FF;">})</span> <span style="color: #0000FF;">!=</span> <span style="color: #000000;">167</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">joy2Attached</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">numDevs</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetPos</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joyinfo</span><span style="color: #0000FF;">})</span> <span style="color: #0000FF;">!=</span> <span style="color: #000000;">167</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">joy1Attached</span> <span style="color: #0000FF;">+</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">joy2Attached</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">joy_get_state</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">joy_num</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">joy_num</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">joy_num</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">joy_num</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">joyGetPos</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">joy_num</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joyinfo</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">joy_num</span><span style="color: #0000FF;">*</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)})</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- ERROR</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">peek4u</span><span style="color: #0000FF;">({</span><span style="color: #000000;">joyinfo</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">joy_num</span><span style="color: #0000FF;">*</span><span style="color: #000000;">16</span><span style="color: #0000FF;">),</span><span style="color: #000000;">4</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
And a test program:
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">joy</span><span style="color: #0000FF;">.</span><span style="color: #000000;">ew</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">joy_init</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"No joystick(s) attached!"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">joy_info</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000000;">s</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">button_mask</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Joystick test\nEntering input loop. Press a key to exit..\n\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">()=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000080;font-style:italic;">-- Get the state of joystick #1</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">joy_get_state</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Do not print info unless the state has changed</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">joy_info</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">joy_info</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"X = %d, Y= %d "</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">32767</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">32768</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">32767</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">32768</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">button_mask</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span><span style="color: #000000;">button_mask</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"BTN%d "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">button_mask</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
Line 480 ⟶ 1,228:
{{libheader|GLUT}}
Note: The code is not yet tested with a real joystick (I don't have one), it was just simulated with dummy functions. Can somebody having a joystick please test it, and remove this message?
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/openGl.l")
 
(setq *JoyX 0.0 *JoyY 0.0)
Line 519 ⟶ 1,267:
# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop)</langsyntaxhighlight>
 
=={{header|PureBasic}}==
This is limited to only digital joysticks.
<langsyntaxhighlight PureBasiclang="purebasic">If InitJoystick() = 0
MessageRequester("Error!", "Need to connect a joystick", #PB_MessageRequester_Ok)
End
Line 594 ⟶ 1,342:
Delay(10)
Until event = #PB_Event_CloseWindow
EndIf</langsyntaxhighlight>
[[File:JoystickPosition-PureBasic.png]]
 
=={{header|Python}}==
{{libheader|Pygame}}
<langsyntaxhighlight Pythonlang="python">import sys
import pygame
 
Line 671 ⟶ 1,419:
# Write the display
pygame.display.flip()
clk.tick(40) # Limit to <=40 FPS</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2020.011}}
Linux only terminal based joystick testing utility. Reads events from the joystick asynchronously, allows a main processing loop if desired. This uses the main loop to check for and compensate for a resized terminal but not really anything else. Hit control-c to exit; needs one extra event from the the joystick to exit completely. Only shows the first 3 axes, no matter how many are available. Tested with an Logitech extreme joystick and an Xbox controller.
 
<syntaxhighlight lang="raku" line>use experimental :pack;
 
# Joysticks generally show up in the /dev/input/ directory as js(n) where n is
# the number assigned by the OS. E.G. /dev/input/js1 . In my particular case:
 
my $device = '/dev/input/js0';
 
my $exit = 0;
 
my $event-stream = $device.IO.open(:bin);
my $js = $event-stream.Supply(:8size);
 
my %config; # joystick configuration: number of axes and buttons
my %event; # global "joystick event"
 
%config<button>.push: 0;
 
my $callback = sub { update };
 
sub get-js-event ( $ev, &callback ) {
exit if $exit;
# 32 bit timestamp milliseconds. Allows easy checking for "double-click" button presses
%event<timestamp> = $ev.subbuf(0, 4).reverse.unpack('N');
 
# 16 bit (signed int16) value of current control
%event<value> = (my $v = $ev.subbuf(4, 2).unpack('S')) > 32767 ?? -65536 + $v !! $v;
 
# Two 8 bit integers, current event: control type, and control ID
(%event<type>, %event<number>) = $ev.subbuf(6).unpack('CC');
 
# Process the event
if %event<type> +& 128 { # initialing
given %event<type> +& 3 { # enumeration of control inputs
when 1 { %config<button>.push: %event<number> }
when 2 { %config<axis>.push: %event<number> }
}
} else {
# Optional callback subroutine to run every time a js event is received
callback
}
}
 
# read events from the joystick driver asynchronously
start react whenever $js { $js.act: { get-js-event($_, $callback) } }
 
# allow a short delay while driver initializes
sleep .5;
 
# clean up on exit
signal(SIGINT).tap: {
print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25hWaiting for one more joystick event...\n";
$exit = 1;
exit(0);
}
 
use Terminal::ANSIColor;
 
my ($rows, $cols) = qx/stty size/.words; # get the terminal size
 
my $xhair = '╺╋╸';
my $axis = '█';
my @btext = %config<button>.map: { sprintf( "%2d", $_) };
my @button = @btext.map: {color('bold white on_blue ') ~ $_ ~ color('reset')};
my ($x, $y, $z) = ($rows/2).floor, ($cols/2).floor, 0;
 
sub update {
given %event<type> {
when 1 { # button event
given %event<value> {
when 0 { @button[%event<number>] = color('bold white on_blue ') ~ @btext[%event<number>] ~ color('reset') }
when 1 { @button[%event<number>] = color('bold white on_green') ~ @btext[%event<number>] ~ color('reset') }
}
}
when 2 { # axis events
given %event<number> {
when 0 { $y = ($cols / 2 + %event<value> / 32767 * $cols / 2).Int max 1 }
when 1 { $x = ($rows / 2 + %event<value> / 32767 * $rows / 2).Int max 2 }
when 2 { $z = (%event<value> / 32767 * 100).Int }
default { } # only using the first 3 axes, ignore ant others
}
$x min= $rows - 1;
$y min= $cols - 1;
}
}
print "\e[H\e[J\e[1;1H";
print " ", join " ", flat @button, "Axis 0: $x", "Axis 1: $y" , "Axis 2: $z%\n";
my $bar = ($z / 100 * $cols / 2).floor;
if $bar < 0 {
print ' ' x ($bar + $cols / 2).floor, color('bold green') ~ $axis x -$bar ~ color('reset');
} else {
print ' ' x $cols / 2, color('bold green') ~ $axis x $bar ~ color('reset');
}
print "\e[{$x};{$y}H", color('bold yellow') ~ $xhair ~ color('reset');
}
 
print "\e[?25l"; # hide the cursor
update; # initial update
 
# Main loop, operates independently of the joystick event loop
loop {
once say " Joystick has {%config<axis>.elems} axes and {%config<button>.elems} buttons";
sleep 1;
($rows, $cols) = qx/stty size/.words;
}
</syntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
{{libheader|mkLibsdl}} <!-- from http://mkextensions.sourceforge.net/ -->
<langsyntaxhighlight lang="tcl">package require Tk 8.6
package require mkLibsdl
 
Line 718 ⟶ 1,577:
.c create line {120 115 120 125} -tags xhairV
.c create line {115 120 125 120} -tags xhairH
joystick event eval {display [joystick event peek]}</langsyntaxhighlight>
<!-- I think it can also be done with Tcl3d as that has SDL Joystick bindings, but damned if I can figure out the API in a reasonable amount of effort. It's definitely not Tclish (but what would you expect with something mashed together with SWIG? Once a stinky C API, always a stinky C API…) -->
 
=={{header|Wren}}==
{{libheader|DOME}}
I'm not sure whether DOME can detect digital joysticks as I don't have one to test. However, it can certainly detect gamepads which nowadays usually include two analog sticks (a form of joystick) so we use the left of these to detect movement and then move the cross-hair (a '+' symbol) accordingly.
 
We also allow movement of the cross-hair using the keyboard direction keys for those who don't have a suitable device.
<syntaxhighlight lang="wren">import "input" for Keyboard, GamePad
import "graphics" for Canvas, Color
import "dome" for Window
 
var Buttons = [
"left", "right", "up", "down", "A", "B", "X", "Y",
"back", "start", "guide", "leftshoulder", "rightshoulder"
]
 
var Symbols = ["L", "R", "U", "D", "A", "B", "X", "Y", "BK", "S", "G", "LS", "RS"]
 
class Main {
construct new(width, height) {
Window.resize(width, height)
Canvas.resize(width, height)
Window.title = "Joystick position"
_w = width
_h = height
_dx = (width/100).floor
_dy = (height/100).floor
_gpd = GamePad.next
}
 
init() {
// start in center
_x = _w / 2
_y = _h / 2
Canvas.cls(Color.yellow)
showButtonStatus()
Canvas.print("+", _x, _y, Color.red)
}
 
update() {
var dx = 0
var dy = 0
if (Keyboard.isKeyDown("left") || _gpd.getAnalogStick("left").x < -0.25) {
dx = -_dx
} else if (Keyboard.isKeyDown("right") || _gpd.getAnalogStick("left").x > 0.25) {
dx = _dx
} else if (Keyboard.isKeyDown("up") || _gpd.getAnalogStick("left").y < -0.25) {
dy = -_dy
} else if (Keyboard.isKeyDown("down") || _gpd.getAnalogStick("left").y > 0.25) {
dy = _dy
}
moveCrossHair(dx, dy)
}
 
moveCrossHair(dx, dy) {
_x = _x + dx
_y = _y + dy
if (_x < 0) _x = 0
if (_x > _w - 5) _x = _w - 5
if (_y < 0) _y = 0
if (_y > _h * 0.96 - 5) _y = _h * 0.96 - 5
}
 
// show whether other gamepad keys are pressed by printing the corresponding symbol if they are.
showButtonStatus() {
Canvas.rectfill(0, _h * 0.96, _w, _h, Color.blue)
var s = ""
for (i in 0...Buttons.count) {
var button = Buttons[i]
if (_gpd.isButtonPressed(button)) s = s + " " + Symbols[i]
}
Canvas.print(s, 0, _h * 0.98, Color.white)
}
 
draw(alpha) {
Canvas.cls(Color.yellow)
showButtonStatus()
Canvas.print("+", _x, _y, Color.red)
}
}
 
var Game = Main.new(600, 600)</syntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
Assuming a Kempston joystick interface, fairly standard at the time.
 
<syntaxhighlight lang="zxbasic">10 DIM o$(5)
20 LET xm=0: LET xx=31: REM screen limits
30 LET ym=0: LET yx=18
40 LET xo=16: LET yo=9: REM origin
50 LET xc=xo: LET yc=yo
60 PRINT AT yc,xc;" ": REM entry point for scan loop - blank cursor
70 LET xc=xo: LET yc=yo
80 LET t=IN 31
90 IF t=1 OR t=5 OR t=9 OR t=17 OR t=21 OR t=25 THEN LET xc=xx: LET o$(2)="R": REM right
100 IF t=2 OR t=6 OR t=10 OR t=18 OR t=22 OR t=26 THEN LET xc=xm: LET o$(1)="L": REM left
110 IF t=4 OR t=5 OR t=6 OR t=20 OR t=21 OR t=22 THEN LET yc=yx: LET o$(4)="D": REM down
120 IF t=8 OR t=9 OR t=10 OR t=24 OR t=25 OR t=26 THEN LET yc=ym: LET o$(3)="U": REM up
130 IF t>=16 THEN LET o$(5)="F": REM fire
140 PRINT AT 21,0;"Input:";o$
150 PRINT AT yc,xc;"+"
160 LET o$=" ": REM five spaces to blank output line again
170 GO TO 60</syntaxhighlight>
 
{{Out}}
<pre>
+
 
Input:L D
</pre>
 
{{omit from|AWK}}
{{omit from|C sharp}}
{{omit from|Lilypond}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|ML/I}}
{{omit from|Maxima}}
{{omit from|Octave}}
{{omit from|PARI/GP}}
{{omit from|R}}
{{omit from|Retro}}
{{omit from|SAS}}
{{omit from|Scilab}}
{{omit from|SQL PL|Cannot connect a joystick}}
{{omit from|Stata}}
{{omit from|TI-83 BASIC|Cannot connect a joystick.}}
{{omit from|zkl}}
9,476

edits