Terminal control/Positional read: Difference between revisions

m
(added Perl programming solution)
m (→‎{{header|Wren}}: Minor tidy)
 
(10 intermediate revisions by 8 users not shown)
Line 1:
{{task|Terminal control}}[[Terminal Control::task| ]]
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language.
 
=={{header|Action!}}==
Method 1: terminal reading
<syntaxhighlight lang="action!">proc Main()
byte CHARS, cursorinh=$2F0
 
graphics(0) cursorinh=1
 
position(2,2) printe("Action!")
 
CHARS=Locate(2,2) position(2,2) put(CHARS)
 
cursorinh=0
position(2,4) printf("Character at column 2 row 2 was %C",CHARS)
 
return</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<p>AutoHotkey is not built for the command line, so we need call the WinAPI directly.</p><p>For fun, this writes random characters to the command window so that it has something to retrieve. </p>
<langsyntaxhighlight AHKlang="ahk">DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
Loop 10
Line 41 ⟶ 57:
return out
return 0
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 10 DEF FN C(H) = SCRN( H - 1,(V - 1) * 2) + SCRN( H - 1,(V - 1) * 2 + 1) * 16
20 LET V = 6:C$ = CHR$ ( FN C(3))</langsyntaxhighlight>
 
==={{header|LocomotiveBBC BasicBASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> PRINT TAB(2,5) "Here"
char$ = GET$(2,5)
PRINT ''"Character at column 3 row 6 was " char$</syntaxhighlight>
{{works with|all BBC BASICs}} that support calling OSBYTE
<syntaxhighlight lang="bbcbasic"> PRINT TAB(2,5) "Here"
PRINT TAB(2,5); : REM Position cursor over character to read
A%=&87:char%=((USR&FFF4)AND&FF00)DIV256 : REM Ask operating system to read character
PRINT ''"Character at column 3 row 6 was CHR$(";char%;")"</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<lang locobasic>10 LOCATE 3,6
The top Left corner Is at position 0,0
20 a$=COPYCHR$(#0)</lang>
<syntaxhighlight lang="freebasic">'Works on Windows. On Linux, the value returned can differ from the character shown on the console.
'For example, unprintable control codes - such as the LF character (10) that implicitly occurs
'after the end of Printed text - may be picked up instead of the untouched character in its place.
 
Print "T@4;4G,XIJ"
Print ">C+PE0)RM;"
Print "JEV6B/8E?H"
Print "FSC>41UIGR"
Print "V>41JMXMOW"
Print "IY0*KH6M;B"' Character at column 3, row 6 = 0
Print "-6<UL*>DU7"
Print "MZ))<5D:B8"
Print ".@UB/P6UQ)"
Print "<9HYH)<ZJF"
 
Dim As Integer char_ascii_value = Screen(6,3)
Locate 6, 14 : Print "Character at column 3, row 6 = "; Chr(char_ascii_value)
Sleep</syntaxhighlight>
 
 
==={{header|Locomotive Basic}}===
<syntaxhighlight lang="locobasic">10 LOCATE 3,6
20 a$=COPYCHR$(#0)</syntaxhighlight>
 
Amstrad CPC screen memory only stores pixels but no character information (as opposed to e.g. the C64), so the firmware routine (TXT_UNWRITE) called by BASIC works by trying to find a match between screen pixels and the shape of a currently defined character. If the character table or screen pixels in the area of the character are changed between writing and reading, COPYCHR$ will therefore fail.
 
===[[QuickBASIC#QBasic|QBasic]]===
 
The top left corner is (1, 1).
 
<langsyntaxhighlight lang="qbasic">c$ = CHR$(SCREEN(6, 3))</langsyntaxhighlight>
 
=== {{header|ZX Spectrum Basic}} ===
<langsyntaxhighlight lang="basic"> 10 REM The top left corner is at position 0,0
20 REM So we subtract one from the coordinates
30 LET c$ = SCREEN$(5,2)</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> PRINT TAB(2,5) "Here"
char$ = GET$(2,5)
PRINT ''"Character at column 3 row 6 was " char$</lang>
{{works with|all BBC BASICs}} that support calling OSBYTE
<lang bbcbasic> PRINT TAB(2,5) "Here"
PRINT TAB(2,5); : REM Position cursor over character to read
A%=&87:char%=((USR&FFF4)AND&FF00)DIV256 : REM Ask operating system to read character
PRINT ''"Character at column 3 row 6 was CHR$(";char%;")"</lang>
 
=={{header|C}}==
Line 82 ⟶ 118:
 
{{libheader|Win32}}
<langsyntaxhighlight lang="c">#include <windows.h>
#include <wchar.h>
 
Line 114 ⟶ 150:
wprintf(L"Character at (3, 6) had been '%lc'\n", c);
return 0;
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<langsyntaxhighlight lang="lisp">(defun positional-read ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
;; print random characters in a 10x20 grid
Line 136 ⟶ 172:
(format scr "extracted char: ~A" char))
(refresh scr)
(get-char scr)))</langsyntaxhighlight>
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
/*
Line 167 ⟶ 203:
}
fmt.Printf("The character at column 3, row 6 is '%c'\n", c)
}</langsyntaxhighlight>
 
{{out}}
Line 176 ⟶ 212:
=={{header|Julia}}==
{{trans|Raku}}
<langsyntaxhighlight lang="julia">using LibNCurses
 
randtxt(n) = foldl(*, rand(split("1234567890abcdefghijklmnopqrstuvwxyz", ""), n))
Line 190 ⟶ 226:
ch = LibNCurses.winch(row, col)
LibNCurses.mvwaddstr(col, 52, "The character at ($row, $col) is $ch.") )
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
This is based on the C entry and works on Windows 10:
<langsyntaxhighlight lang="scala">// Kotlin Native version 0.3
 
import kotlinx.cinterop.*
Line 218 ⟶ 254:
else println("Something went wrong!")
}
}</langsyntaxhighlight>
 
{{out}}
Line 224 ⟶ 260:
The character at column 3, row 6 is 'A'
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Determine the character displayed on the screen at column 3, row 6 and
# store that character in a variable.
#
# Use a group of functions "shellcurses"
 
# # Variables:
#
FPATH="/usr/local/functions/shellcurses/"
 
rst="�[0m"
red="�[31m"
whi="�[37m"
 
integer row=${1:-6} col=${2:-3} # Allow command line row col input
 
# # 10x10 grid of random digits
#
typeset -A grid
for ((i=0; i<10; i++)); do
for ((j=0; j<10; j++)); do
(( grid[${i}][${j}] = (RANDOM % 9) + 1 ))
done
done
 
# # Functions:
#
 
 
######
# main #
######
# # Initialize the curses screen
#
initscr ; export MAX_LINES MAX_COLS
 
# # Display the random number grid with target in red
#
clear
for ((i=1; i<=10; i++)); do
for ((j=1; j<=10; j++)); do
colr=${whi}
(( i == row )) && (( j == col )) && colr=${red}
mvaddstr ${i} ${j} "${colr}${grid[$((i-1))][$((j-1))]}${rst}"
done
done
 
str=$(rtnch ${row} ${col}) # return char at (row, col) location
 
mvaddstr 12 1 "Digit at (${row},${col}) = ${str}" # Display result
move 14 1
refresh
endwin</syntaxhighlight>
 
{{out}}<pre>
2466511215
6743931696
7546513188
7233775996
4748942123
8893655153
8341639139
8772676987
3772947552
8454526539
 
Digit at (6,3) = 9</pre>
 
=={{header|Nim}}==
{{trans|Raku}}
{{trans|Julia}}
{{libheader|nim-ncurses}}
This Nim version is inspired by Raku and Julia versions.
<syntaxhighlight lang="nim">import random, sequtils, strutils
import ncurses
 
randomize()
 
let win = initscr()
assert not win.isNil, "Unable to initialize."
 
for y in 0..9:
mvaddstr(y.cint, 0, newSeqWith(10, sample({'0'..'9', 'a'..'z'})).join())
 
let row = rand(9).cint
let col = rand(9).cint
let ch = win.mvwinch(row, col)
 
mvaddstr(row, col + 11, "The character at ($1, $2) is $3.".format(row, col, chr(ch)))
mvaddstr(11, 0, "Press any key to quit.")
refresh()
discard getch()
 
endwin()</syntaxhighlight>
 
{{out}}
<pre>tw5bl8mhvl
37t0nvwjhr
055co0b3hm
409stl3jgv The character at (3, 8) is g.
a9j5354rci
o5ymlrtgt2
9yjag11u7n
2nv32g6s7x
3l1zujlpl2
opkl6us0mf
 
Press any key to quit.</pre>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight Perllang="perl"># 20200917 added Perl programming solution
 
use strict;
Line 253 ⟶ 401:
$win->getch;
 
endwin;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Positional_read.exw
-- demo\rosetta\Positional_read.exw
-- ================================
-- ================================
--
--</span>
position(6,1) -- line 6 column 1 (1-based)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (position, get_screen_char)</span>
puts(1,"abcdef")
<span style="color: #7060A8;">position</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- line 6 column 1 (1-based)</span>
integer {ch,attr} = get_screen_char(6,3)
<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;">"abcdef"</span><span style="color: #0000FF;">)</span>
printf(1,"\n\n=>%c",ch)
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">attr</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">get_screen_char</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
{} = wait_key()</lang>
<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;">"\n\n=&gt;%c"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 279 ⟶ 430:
=={{header|PowerShell}}==
This gets the character at position (3, 6) of the ''buffer'', not necessarily of the screen.
<langsyntaxhighlight lang="powershell">
$coord = [System.Management.Automation.Host.Coordinates]::new(3, 6)
$rect = [System.Management.Automation.Host.Rectangle]::new($coord, $coord)
$char = $Host.UI.RawUI.GetBufferContents($rect).Character
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import curses
from random import randint
 
Line 307 ⟶ 458:
 
curses.endwin()
</syntaxhighlight>
</lang>
 
{{out}}
Line 324 ⟶ 475:
=={{header|Racket}}==
Works in a CMD box on Windows:
<langsyntaxhighlight lang="racket">
#lang racket
(require ffi/unsafe ffi/unsafe/define)
Line 335 ⟶ 486:
(and (ReadConsoleOutputCharacterA (GetStdHandle -11) b 1 #x50002)
(printf "The character at 3x6 is <~a>\n" b))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Python}}
<syntaxhighlight lang="raku" perl6line>use NCurses;
 
# Reference:
Line 375 ⟶ 526:
delwin($win) if $win;
endwin;
}</langsyntaxhighlight>
 
{{out}}
Line 408 ⟶ 559:
{{works with|PC/REXX}}
{{works with|Personal REXX}}
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates reading a charcharacter from (at) at specific screen location. */
row = 6 row = 6 /*point to row six. /*point to a particular row on screen*/
col = 3 /*point to column" three. " " " column " " */
howMany = 1 /*read one character. /*read this many characters from screen*/
 
stuff = scrRead(row, col, howMany) /*this'll do it. */
 
other = scrRead(40, 63, 1) /*same thing, but for row forty. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight><br><br>
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txrlisp">;;; Type definitions and constants
 
(typedef BOOL (enum BOOL FALSE TRUE))
Line 490 ⟶ 641:
(unless (plusp [nread 0])
(error "ReadConsoleOutputCharacter read zero characters"))
(format t "character is ~s\n" [chars 0])))</langsyntaxhighlight>
 
Notes:
* An <code>ptr-out</code> to an <code>array</code> of 1 <code>DWORD</code> is used for the number of characters out parameter. The FFI type <code>(ptr-out DWORD)</code> cannot work as a function argument, because integer objects are not mutable, and there isn't any concept of taking the address of a variable. A vector of 1 integer is mutable, and by making such a vector correspond with the FFI type <code>(array 1 DWORD)</code>, the necessary semantics is achieved.
* The quasiquote expression <code>^#S(COORD X ,(+ 2 cinfo.srWindow.Left) Y ,(+ 5 cinfo.srWindow.Top))</code> is equivalent to <code>(new COORD X (+ 2 cinfo.srWindow.Left) Y (+ 5 cinfo.srWindow.Top))</code>. It is done this way to demonstrate support for structure quasiquoting.
 
=={{header|Wren}}==
{{trans|Raku}}
{{libheader|ncurses}}
An embedded program so we can ask the C host to communicate with ncurses for us.
<syntaxhighlight lang="wren">/* Terminal_control_Positional_read.wren */
 
import "random" for Random
 
foreign class Window {
construct initscr() {}
 
foreign addstr(str)
 
foreign inch(y, x)
 
foreign move(y, x)
 
foreign refresh()
 
foreign getch()
 
foreign delwin()
}
 
class Ncurses {
foreign static endwin()
}
 
// initialize curses window
var win = Window.initscr()
if (win == 0) {
System.print("Failed to initialize ncurses.")
return
}
 
// print random text in a 10x10 grid
var rand = Random.new()
for (row in 0..9) {
var line = (0..9).map{ |d| String.fromByte(rand.int(41, 91)) }.join()
win.addstr(line + "\n")
}
 
// read
var col = 3 - 1
var row = 6 - 1
var ch = win.inch(row, col)
 
// show result
win.move(row, col + 10)
win.addstr("Character at column 3, row 6 = %(ch)")
win.move(11, 0)
win.addstr("Press any key to exit...")
 
// refresh
win.refresh()
 
// wait for a keypress
win.getch()
 
// clean-up
win.delwin()
Ncurses.endwin()</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Terminal_control_Positional_read.c -o Terminal_control_Positional_read -lncurses -lwren -lm */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ncurses.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
void C_windowAllocate(WrenVM* vm) {
WINDOW** pwin = (WINDOW**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(WINDOW*));
*pwin = initscr();
}
 
void C_addstr(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
const char *str = wrenGetSlotString(vm, 1);
waddstr(win, str);
}
 
void C_inch(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
int y = (int)wrenGetSlotDouble(vm, 1);
int x = (int)wrenGetSlotDouble(vm, 2);
char c = (char)mvwinch(win, y, x);
char s[2] = "\0";
sprintf(s, "%c", c);
wrenSetSlotString(vm, 0, s);
}
 
void C_move(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
int y = (int)wrenGetSlotDouble(vm, 1);
int x = (int)wrenGetSlotDouble(vm, 2);
wmove(win, y, x);
}
 
void C_refresh(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
wrefresh(win);
}
 
void C_getch(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
wgetch(win);
}
 
void C_delwin(WrenVM* vm) {
WINDOW* win = *(WINDOW**)wrenGetSlotForeign(vm, 0);
delwin(win);
}
 
void C_endwin(WrenVM* vm) {
endwin();
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Window") == 0) {
methods.allocate = C_windowAllocate;
}
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Window") == 0) {
if (!isStatic && strcmp(signature, "addstr(_)") == 0) return C_addstr;
if (!isStatic && strcmp(signature, "inch(_,_)") == 0) return C_inch;
if (!isStatic && strcmp(signature, "move(_,_)") == 0) return C_move;
if (!isStatic && strcmp(signature, "refresh()") == 0) return C_refresh;
if (!isStatic && strcmp(signature, "getch()") == 0) return C_getch;
if (!isStatic && strcmp(signature, "delwin()") == 0) return C_delwin;
} else if (strcmp(className, "Ncurses") == 0) {
if ( isStatic && strcmp(signature, "endwin()") == 0) return C_endwin;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Terminal_control_Positional_read.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{out}}
Sample output:
<pre>
86.Z=B>)0I
R/X,HX=6RE
>*12?I-G0+
D*8S-2A.)3
9)+=89UNXW
YQN4L8NC4W Character at column 3, row 6 = N
6EQC@=))B/
XWOSZ4/CR@
LU->=2@RW1
ZKFRC9EOT0
 
Press any key to exit...
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
int C;
[Cursor(3, 6); \move cursor to column 3, row 6 (top left = 0,0)
\Call BIOS interrupt routine to read character (& attribute) at cursor position
C:= CallInt($10, $0800, 0) & $00FF; \mask off attribute, leaving the character
]</langsyntaxhighlight>
 
{{omit from|ACL2}}
9,476

edits