#include<conio.h>
#include<dos.h>

char *strings[] = {"The cursor will move one position to the left",
  		   "The cursor will move one position to the right",
 		   "The cursor will move vetically up one line",
 		   "The cursor will move vertically down one line",
 		   "The cursor will move to the beginning of the line",
 		   "The cursor will move to the end of the line",
 		   "The cursor will move to the top left corner of the screen",
 		   "The cursor will move to the bottom right corner of the screen"};

int main()
{
	int i,j,MAXROW,MAXCOL;
	struct text_info tInfo;
	gettextinfo(&tInfo);
	MAXROW = tInfo.screenheight;
	MAXCOL = tInfo.screenwidth;

	clrscr();
	cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
	getch();

	for(i=0;i<8;i++)
	{
		clrscr();
		gotoxy(5,MAXROW/2);

		cprintf("%s",strings[i]);
		getch();

		switch(i){
			case 0:gotoxy(wherex()-1,wherey());
			break;
			case 1:gotoxy(wherex()+1,wherey());
			break;
			case 2:gotoxy(wherex(),wherey()-1);
			break;
			case 3:gotoxy(wherex(),wherey()+1);
			break;
			case 4:for(j=0;j<strlen(strings[i]);j++){
				   gotoxy(wherex()-1,wherey());
				   delay(100);
			       }
			break;
			case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
			       for(j=0;j<strlen(strings[i]);j++){
				   gotoxy(wherex()+1,wherey());
				   delay(100);
			       }
			break;
			case 6:while(wherex()!=1)
			       {
				     gotoxy(wherex()-1,wherey());
				     delay(100);
		               }
			       while(wherey()!=1)
			       {
			             gotoxy(wherex(),wherey()-1);
			             delay(100);
			       }
			break;
			case 7:while(wherex()!=MAXCOL)
			       {
				     gotoxy(wherex()+1,wherey());
				     delay(100);
			       }
			       while(wherey()!=MAXROW)
			       {
				     gotoxy(wherex(),wherey()+1);
				     delay(100);
			       }
			break;
			};
			getch();
	}

	clrscr();
	cprintf("End of demonstration.");
	getch();
	return 0;
}


curses start; # needed before any screen clearing, positioning etc. #
curses clear  # clear the screen #


/* ARM assembly Raspberry PI  */
/*  program clearScreen.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall

.equ BUFFERSIZE,          100

/* Initialized data */
.data
szMessStartPgm:            .asciz "Program start \n"
szMessEndPgm:              .asciz "Program normal end.\n"
szClear:                   .asciz "\33[2J"     @ console clear (id language C)
szClear1:                  .byte 0x1B
                           .byte 'c'           @ other console clear
                           .byte 0
szCarriageReturn:          .asciz "\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:

    ldr r0,iAdrszMessStartPgm                   @ display start message
    bl affichageMess
    //ldr r0,iAdrszClear                        @ clear screen
    ldr r0,iAdrszClear1                         @ change for other clear screen
    bl affichageMess
    ldr r0,iAdrszMessEndPgm                     @ display end message
    bl affichageMess

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call
iAdrszMessStartPgm:       .int szMessStartPgm
iAdrszMessEndPgm:         .int szMessEndPgm
iAdrszClear:              .int szClear
iAdrszClear1:             .int szClear1
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return


(defun cursor-movement ()
  (with-screen (scr :input-blocking t :input-echoing nil :cursor-visible t)
    ;; display the screen and wait for a keypress
    (refresh scr) (get-char scr)

    (move-direction scr :right) (refresh scr) (get-char scr)
    (move-direction scr :left) (refresh scr) (get-char scr)
    (move-direction scr :down) (refresh scr) (get-char scr)
    (move-direction scr :up) (refresh scr) (get-char scr)
    ;; end of line
    (move scr (car (cursor-position scr)) (1- (width scr))) (refresh scr) (get-char scr)
    ;; beginning of line
    (move scr (car (cursor-position scr)) 0) (refresh scr) (get-char scr)
    ;; bottom right corner
    (move scr (1- (height scr)) (1- (width scr))) (refresh scr) (get-char scr)
    ;; top left corner
    (move scr 0 0) (refresh scr) (get-char scr)))


static void Main(string[] args)
{
    //There will be a 3 second pause between each cursor movement.
    Console.Write("\n\n\n\n     Cursor is here -->   ");
    System.Threading.Thread.Sleep(3000);
    Console.CursorLeft = Console.CursorLeft - 1; //Console.CursorLeft += -1 is an alternative.
    System.Threading.Thread.Sleep(3000);
    Console.CursorLeft = Console.CursorLeft + 1;
    System.Threading.Thread.Sleep(3000);
    Console.CursorTop = Console.CursorTop - 1;
    System.Threading.Thread.Sleep(3000);
    Console.CursorTop = Console.CursorTop + 1;
    System.Threading.Thread.Sleep(3000);
    Console.CursorLeft = 0; //Move the cursor far left.
    System.Threading.Thread.Sleep(3000);
    Console.CursorLeft = Console.BufferWidth - 1;
    /* BufferWidth represents the number of characters wide the console area is.
        * The exact value may vary on different systems.
        * As the cursor position is a 0 based index we must subtract 1 from buffer width or we move the cursor out of bounds.
        * In some cases WindowWidth may be preferable (however in this demonstration window and buffer should be the same).
        */
    System.Threading.Thread.Sleep(3000);
    Console.SetCursorPosition(0,0); //I have used an alternative method for moving the cursor here which I feel is cleaner for the task at hand.
    System.Threading.Thread.Sleep(3000);
    Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); //Buffer height is usually longer than the window so window has been used instead.
    System.Threading.Thread.Sleep(3000);
}


( ANSI terminal control lexicon )
DECIMAL

( support routines)
 27 CONSTANT ESC
: <##>    ( n -- ) ( sends n, radix 10, no spaces)
          BASE @ >R DECIMAL  0 <# #S #> TYPE   R> BASE ! ;

: ESC[   ( -- )   ESC EMIT ." [" ;

( ANSI terminal commands as Forth words)
: <CUU>  ( row --) ESC[ <##> ." A" ;
: <CUD>  ( row --) ESC[ <##> ." B" ;
: <CUF>  ( col --) ESC[ <##> ." C" ;
: <CUB>  ( col --) ESC[ <##> ." D" ;
: <CPL>  ( -- )    ESC[ <##> ." F" ;
: <CHA>  ( n --)   ESC[ <##> ." G" ;
: <EL>   ( -- )    ESC[ ." K" ;
: <ED>   ( -- )    ESC[ ." 2J" ;
: <CUP>  ( row col -- ) SWAP ESC[ <##> ." ;" <##> ." H"  ;

( Define ANSI Forth names for these functions using our markup words)
: AT-XY ( col row  -- ) SWAP <CUP> ;
: PAGE  ( -- ) <ED>  1 1 <CUP> ;


package main

import (
    "fmt"
    "time"
    "os"
    "os/exec"
    "strconv"
)

func main() {
    tput("clear") // clear screen
    tput("cup", "6", "3") // an initial position
    time.Sleep(1 * time.Second)
    tput("cub1") // left
    time.Sleep(1 * time.Second)
    tput("cuf1") // right
    time.Sleep(1 * time.Second)
    tput("cuu1") // up
    time.Sleep(1 * time.Second)
    // cud1 seems broken for me.  cud 1 works fine though.
    tput("cud", "1") // down
    time.Sleep(1 * time.Second)
    tput("cr") // begining of line
    time.Sleep(1 * time.Second)
    // get screen size here
    var h, w int
    cmd := exec.Command("stty", "size")
    cmd.Stdin = os.Stdin
    d, _ := cmd.Output()
    fmt.Sscan(string(d), &h, &w)
    // end of line
    tput("hpa", strconv.Itoa(w-1))
    time.Sleep(2 * time.Second)
    // top left
    tput("home")
    time.Sleep(2 * time.Second)
    // bottom right
    tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1))
    time.Sleep(3 * time.Second)
}

func tput(args ...string) error {
    cmd := exec.Command("tput", args...)
    cmd.Stdout = os.Stdout
    return cmd.Run()
}


const ESC = "\u001B" # escape code
const moves = Dict( "left" => "[1D", "right" => "[1C", "up" => "[1A", "down" => "[1B",
                    "linestart" => "[9D", "topleft" => "[H", "bottomright" => "[24;79H")

print("$ESC[2J")     # clear terminal first
print("$ESC[10;10H") # move cursor to (10, 10) say
const count = [0]
for d in ["left", "right", "up", "down", "linestart", "bottomright"]
    sleep(3) # three second pause for display between cursor movements
    print("$ESC$(moves[d])")
    print(count[1] += 1)
end
println()
println()


// version 1.1.2

const val ESC = "\u001B"  // escape code

fun main(args: Array<String>) {
    print("$ESC[2J")     // clear terminal first
    print("$ESC[10;10H") // move cursor to (10, 10) say
    val aecs = arrayOf(
        "[1D",    // left
        "[1C",    // right
        "[1A",    // up
        "[1B",    // down
        "[9D",    // line start
        "[H",     // top left
        "[24;79H" // bottom right - assuming 80 x 24 terminal
    )
    for (aec in aecs) {
        Thread.sleep(3000) // three second display between cursor movements
        print("$ESC$aec")
    }
    Thread.sleep(3000)
    println()
}


global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;

1 const stdout

: write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;
: print ( buf len -- ) stdout write ;

: clear-screen ( -- ) s" \033[2J\033[H" print ;

: _start ( -- noret ) clear-screen bye ;


void cls(void) {
    printf("\33[2J");
}


       PROGRAM-ID. blank-terminal.

       DATA DIVISION.
       SCREEN SECTION.
       01  blank-screen BLANK SCREEN.

       PROCEDURE DIVISION.
           DISPLAY blank-screen

           GOBACK
           .


#!/usr/bin/lasso9

local(esc		= decode_base64('Gw=='))

stdoutnl('Demonstrate how to move the cursor one position to the left
Demonstrate how to move the cursor one position to the right
Demonstrate how to move the cursor up one line (without affecting its horizontal position)
Demonstrate how to move the cursor down one line (without affecting its horizontal position)
Demonstrate how to move the cursor to the beginning of the line
Demonstrate how to move the cursor to the end of the line
Demonstrate how to move the cursor to the top left corner of the screen
Demonstrate how to move the cursor to the bottom right corner of the screen
')

// place cursor in a suitable place before exercise
stdout(#esc + '[5;10H')
sleep(2000)

// move the cursor one position to the left
stdout(#esc + '[1D')
sleep(2000)

// move the cursor one position to the right
stdout(#esc + '[1C')
sleep(2000)

// move the cursor up one line
stdout(#esc + '[1A')
sleep(2000)

// move the cursor down one line
stdout(#esc + '[1B')
sleep(2000)

// move the cursor to the beginning of the line
stdout(#esc + '[100D')
sleep(2000)

// move the cursor to the top left corner of the screen
stdout(#esc + '[H')
sleep(2000)

// move the cursor to the bottom right corner of the screen
stdout(#esc + '[500;500H')
sleep(2000)


Run["tput cub1"]                  (* one position to the left *)
Run["tput cuf1" ]                 (* one position to the right *)
Run["tput cuu1" ]                 (* up one line *)
Run["tput cud1"]                  (* down one line *)
Run["tput cr"]                    (* beginning of line *)
Run["tput home"]                  (* top left corner *)

WIDTH=RunThrough["tput cols", ""];
HEIGHT=RunThrough["tput lines", ""];

Run["tput hpa "<>WIDTH]            (* end of line *)
Run["tput cup "<>HEIGHT<>"  "<> WIDTH]    (* bottom right corner *)


import terminal

echo "Press the return key to go to next step."
echo "Starting in the middle of last line."

template waitUser() =
  while getch() != '\r': discard

let (width, height) = terminalSize()
# Start by positionning the cursor in the middle of the line.
setCursorXPos(width div 2)
waitUser()
# Move one character backward.
cursorBackward(1)
waitUser()
# Move one character forward.
cursorForward(1)
waitUser()
# Move one character up.
cursorUp(1)
waitUser()
# Move one character down.
cursorDown(1)
waitUser()
# Move at beginning of line.
setCursorXPos(0)
waitUser()
# Move at end of line.
setCursorXPos(width - 1)
waitUser()
# Move cursor to the top left corner.
setCursorPos(0, 0)
waitUser()
# Move cursor to the bottom right corner.
setCursorPos(width - 1, height - 1)
waitUser()


system "tput cub1"; sleep 1;  # one position to the left
system "tput cuf1"; sleep 1;  # one position to the right
system "tput cuu1"; sleep 1;  # up one line
system "tput cud1"; sleep 1;  # down one line
system "tput cr";   sleep 1;  # beginning of line
system "tput home"; sleep 1;  # top left corner

$_ = qx[stty -a </dev/tty 2>&1];
my($rows,$cols) = /(\d+) rows; (\d+) col/;
$rows--; $cols--;

system "tput cup $rows $cols"; # bottom right corner
sleep 1;


--
-- demo\rosetta\Cursor_movement.exw
-- ================================
--
-- These may vary by platform/hardware... (this program is ideal for sorting such things out)
--
constant HOME  = 327,
         END   = 335,
         UP    = 328,
         DOWN  = 336,
         LEFT  = 331,
         RIGHT = 333,
         PGUP  = 329,   -- (goto top left)
         PGDN  = 337    -- (goto bottom right)

constant {maxl,maxc} = video_config()[VC_SCRNLINES..VC_SCRNCOLS]

procedure move_cursor(integer dy, integer dx)
    integer {l,c} = sq_add(get_position(),{dy,dx})
    if l>=1 and l<=maxl
    and c>=1 and c<=maxc then
        position(l,c)
    end if
end procedure

procedure move_to(integer ny=-1, integer nx=-1)
    integer {l,c} = get_position()
    if ny!=-1 then l = ny end if
    if nx!=-1 then c = nx end if
    position(l,c)
end procedure

procedure showkey(integer key)
    integer {l,c} = get_position()
    position(2,maxc-5)
    ?key
    position(l,c)
end procedure

while 1 do
    integer key = wait_key()
    if key=#1B then exit end if -- escape quits
    showkey(key)
    if    key=HOME  then move_to(nx:=1)     -- home
    elsif key=END   then move_to(nx:=maxc)  -- end
    elsif key=UP    then move_cursor(-1, 0) -- up
    elsif key=DOWN  then move_cursor(+1, 0) -- down
    elsif key=LEFT  then move_cursor( 0,-1) -- left
    elsif key=RIGHT then move_cursor( 0,+1) -- right
    elsif key=PGUP  then move_to(1,1)       -- page_up
    elsif key=PGDN  then move_to(maxl,maxc) -- page_down
    end if
end while


extern (C) nothrow {
    void disp_open();
    void disp_move(int, int);
    void disp_eeop();
    void disp_close();
}

void main() {
    disp_open();
    disp_move(0, 0);
    disp_eeop();
    disp_close();
}


uses
  System.SysUtils,
  Winapi.Windows;

procedure ClearScreen;
var
  stdout: THandle;
  csbi: TConsoleScreenBufferInfo;
  ConsoleSize: DWORD;
  NumWritten: DWORD;
  Origin: TCoord;
begin
  stdout := GetStdHandle(STD_OUTPUT_HANDLE);
  Win32Check(stdout<>INVALID_HANDLE_VALUE);
  Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));
  ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;
  Origin.X := 0;
  Origin.Y := 0;
  Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin,
    NumWritten));
  Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin,
    NumWritten));
  Win32Check(SetConsoleCursorPosition(stdout, Origin));
end;


(call 'tput "cub1")                                # one position to the left
(call 'tput "cuf1")                                # one position to the right
(call 'tput "cuu1")                                # up one line
(call 'tput "cud1")                                # down one line
(call 'tput "cr")                                  # beginning of the line
(call 'tput "hpa" (sys "COLUMNS"))                 # end of the line
(call 'tput "home")                                # top left corner
(call 'tput "cup" (sys "LINES") (sys "COLUMNS"))   # bottom right corner


import curses

scr = curses.initscr()
#     Demonstrate how to move the cursor one position to the left
def move_left():
	y,x = curses.getyx()
	curses.move(y,x-1)

#    Demonstrate how to move the cursor one position to the right
def move_right():
	y,x = curses.getyx()
	curses.move(y,x+1)

#    Demonstrate how to move the cursor up one line (without affecting its horizontal position)
def move_up():
	y,x = curses.getyx()
	curses.move(y-1,x)

#    Demonstrate how to move the cursor down one line (without affecting its horizontal position)
def move_down():
	y,x = curses.getyx()
	curses.move(y+1,x)

#    Demonstrate how to move the cursor to the beginning of the line
def move_line_home()
	y,x = curses.getyx()
	curses.move(y,0)

#    Demonstrate how to move the cursor to the end of the line
def move_line_end()
	y,x = curses.getyx()
	maxy,maxx = scr.getmaxyx()
	curses.move(y,maxx)

#    Demonstrate how to move the cursor to the top left corner of the screen
def move_page_home():
	curses.move(0,0)

#    Demonstrate how to move the cursor to the bottom right corner of the screen
def move_page_end():
	y,x = scr.getmaxyx()
	curses.move(y,x)


#lang racket
(require (planet neil/charterm:3:0))
(define x 0)
(define y 0)

(define (on-key k)
  (match k
    ['down   (move  0 -1)]
    ['up     (move  0 +1)]
    ['right  (move +1  0)]
    ['left   (move -1  0)]
    [else    #f]))

(define (move dx dy)
  (set! x (+ x dx))
  (set! y (+ y dy))
  (charterm-cursor x y))

(with-charterm
 (charterm-clear-screen)
 (charterm-cursor 0 0)
 (let loop ([continue? #t])
   (when continue?
     (loop (on-key (charterm-read-key))))))


shell "tput cub1";                  # one position to the left
shell "tput cuf1";                  # one position to the right
shell "tput cuu1";                  # up one line
shell "tput cud1";                  # down one line
shell "tput cr";                    # beginning of line
shell "tput home";                  # top left corner

$_ = qx[stty -a </dev/tty 2>&1];
my $rows = +m/'rows '    <(\d+)>/;
my $cols = +m/'columns ' <(\d+)>/;

shell "tput hpa $cols";             # end of line
shell "tput cup $rows $cols";       # bottom right corner


program clear
    character(len=:), allocatable :: clear_command
    clear_command = "clear" !"cls" on Windows, "clear" on Linux and alike
    call execute_command_line(clear_command)
end program


' FB 1.05.0 Win64

' FreeBASIC has a built in Cls command which clears the console on Windows
' but it may still be possible to scroll the console to view its
' previous contents. The following command prevents this.

Shell("Cls")
Sleep


/*REXX pgm demonstrates how to achieve movement of the terminal cursor. */

parse value scrsize() with sd sw       /*find the display screen size.  */
parse value cursor() with row col      /*find where the cursor is now.  */

colL=col-1;  if colL==0 then colL=sw   /*prepare to move cursor to left.*/
call cursor row,colL                   /*move cursor to the left (wrap).*/

colR=col+1;  if colR>sw then colL=1    /*prepare to move cursor to right*/
call cursor row,colR                   /*move cursor to the right (wrap)*/

rowU=row-1;  if rowU==0 then rowU=sd   /*prepare to move cursor up.     */
call cursor rowU,col                   /*move cursor  up  (with wrap).  */

rowD=row+1;  if rowD>sd then rowD=1    /*prepare to move cursor down.   */
call cursor rowD,col                   /*move cursor down (with wrap).  */

call cursor row,1                      /*move cursor to beginning of row*/
call cursor row,sw                     /*move cursor to    end    of row*/
call cursor 1,1                        /*move cursor to top left corner.*/
call cursor sd,sw                      /*move cursor to bot right corner*/

                                       /*stick a fork in it, we're done.*/


object CursorMovement extends App {
  val ESC = "\u001B" // escape code

  print(s"$ESC[2J$ESC[10;10H") // clear terminal first, move cursor to (10, 10) say
  val aecs = Seq(
    "[1D", // left
    "[1C", // right
    "[1A", // up
    "[1B", // down
    "[9D", // line start
    "[H", // top left
    "[24;79H" // bottom right - assuming 80 x 24 terminal
  )
  for (aec <- aecs) {
    Thread.sleep(3000) // three second display between cursor movements
    print(s"$ESC$aec")
  }

}


# Simplification wrapper for when we're actually affecting the terminal
proc tput args {
    exec tput {*}$args >@stdout <@stdin
}

tput cub1;                 # one position to the left
tput cuf1;                 # one position to the right
tput cuu1;                 # up one line
tput cud1;                 # down one line
tput cr;                   # beginning of line
tput home;                 # top left corner

# For line ends and bottom, we need to determine size of terminal
set width [exec tput cols]
set height [exec tput lines]

tput hpa $width;	   # end of line
tput cpu $height $width;   # bottom right corner


tput cub1                  # one position to the left
tput cuf1                  # one position to the right
tput cuu1                  # up one line
tput cud1                  # down one line
tput cr                    # beginning of line
tput home                  # top left corner

# For line ends and bottom, we need to determine size
# of terminal
WIDTH=`tput cols`
HEIGHT=`tput lines`

tput hpa $WIDTH            # end of line
tput cup $HEIGHT $WIDTH    # bottom right corner


import "timer" for Timer
import "io" for Stdout

System.write("\e[2J")     // clear terminal
System.write("\e[12;40H") // move to (12, 40)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[D")      // move left
Stdout.flush()
Timer.sleep(2000)
System.write("\e[C")      // move right
Stdout.flush()
Timer.sleep(2000)
System.write("\e[A")      // move up
Stdout.flush()
Timer.sleep(2000)
System.write("\e[B")      // move down
Stdout.flush()
Timer.sleep(2000)
System.write("\e[G")      // move to beginning of line
Stdout.flush()
Timer.sleep(2000)
System.write("\e[79C")    // move to end of line (assuming 80 column terminal)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[1;1H")   // move to top left corner
Stdout.flush()
Timer.sleep(2000)
System.write("\e[24;80H") // move to bottom right corner (assuming 80 x 24 terminal)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[1;1H")   // home cursor again before quitting


package main

import (
    "os"
    "os/exec"
)

func main() {
    c := exec.Command("clear")
    c.Stdout = os.Stdout
    c.Run()
}


import System.Console.ANSI

main = clearScreen


procedure main ()
  if &features == "MS Windows" then system("cls")  # Windows
  else if &features == "UNIX" then system("clear") # Unix
end


public class Clear
{
    public static void main (String[] args)
    {
        System.out.print("\033[2J");
    }
}


include c:\cxpl\codes;  \intrinsic 'code' declarations
int I, X, Y, W, H;
[Cursor(10, 13);        \set cursor to arbitrary location on screen
I:= ChIn(1);            \wait for keystroke (no echo to display)
ChOut(0, $08\BS\);      \backspace moves one position right
I:= ChIn(1);
X:= Peek($40, $50);     \get cursor location from BIOS data
Y:= Peek($40, $51);
Cursor(X+1, Y);         \move one position right
I:= ChIn(1);
Cursor(X+1, Y-1);       \move up one line
I:= ChIn(1);
ChOut(0, $0A\LF\);      \line feed moves down one line
I:= ChIn(1);
ChOut(0, $0D\CR\);      \carriage return moves to beginning of current line
I:= ChIn(1);
W:= Peek($40, $4A);     \get width of display (standard = 80; mine = 94)
Cursor(W-1, Y);         \move to end of current line
I:= ChIn(1);
Cursor(0, 0);           \move to top left corner
I:= ChIn(1);
H:= Peek($40, $84) + 1; \get height of display (standard = 25; mine = 50)
Cursor(W-1, H-1);       \move to bottom right corner
I:= ChIn(1);
]


print("\e[2J\e[6;3H");	// clear screen, move to an initial position
   Atomic.sleep(1);	// pause to let cursor blink
print("\e[D");		// left
   Atomic.sleep(1);
print("\e[C");		// right
   Atomic.sleep(1);
print("\e[A");		// up
   Atomic.sleep(1);
print("\e[B");		// down
   Atomic.sleep(1);
print("\e[;H");		// top left
   Atomic.sleep(1);


10 PRINT CHR$(8);:REM cursor one position left
20 PRINT CHR$(9);:REM cursor one position right
30 GO SUB 500: REM get cursor position
40 IF cr>0 THEN LET cr=cr-1: GO SUB 550: REM cursor up one line
50 IF cr<22 THEN LET cr=cr+1: GO SUB 550: REM cursor down one line
60 POKE 23688,33: REM cursor to beginning of the line
70 POKE 23688,0: REM cursor to end of line
80 POKE 23688,33:POKE 23689,24: REM cursor to top left
90 REM bottom two rows are reserved for input and errors
100 REM so we reserve those lines here
110 POKE 23688,0: POKE 23689,2: REM bottom right

499 STOP: REM do not overrun into subroutines

500 REM get cursor position
510 LET cc=33-PEEK 23688:REM current column
520 LET cr=24-PEEK 23689:REM current row
530 RETURN

550 REM set cursor position
560 PRINT AT cr,cc;
570 RETURN

600 REM alternative set cursor position
610 POKE 23688,33-cc
620 POKE 23689,24-cr
630 RETURN


/* Terminal Control, clear the screen, in Jsish */
function cls() { printf('\u001b[2J'); }

;cls();

/*
=!EXPECTSTART!=
cls() ==> ^[[2Jundefined
=!EXPECTEND!=
*/


// version 1.1.2

fun main(args: Array<String>) {
    println("\u001Bc")  // Esc + c
}


local(
	esc = decode_base64('Gw==')
)

stdout(#esc + '[2J')


Module Checkit {
      Pen 14 ' yellow
      \\ using form we set characters by rows
      \\ this clear the screen
      Form 80, 40
      \\ magenta for background, all form for vertical scrolling
      Cls 5, 0
      Print "wait... half second"
      Wait 500
      \\ clear using background color
      Cls
      \\ set the background (using html number for color), and set 4th line as top
      \\ for scrolling
      Cls #11bb22, 3
      Print "This is in 4th line"
      Wait  1000
      \\ now we center the form, using 12000 twips by 8000twips as border
      \\ form inside maybe smaller
      \\ font size is 16pt of current font
      Font "Courier New"
      Window 16, 12000, 8000;
      Print "This is first line"
      Wait 1000
      Font "Arial"
      \\ set the console form to screen 0, maximized
      Window 16, 0
      Cls 5   ' magenta
      Back {
            Cls 15 ' white border
      }
}
checkit


import terminal

eraseScreen() #puts cursor at down
setCursorPos(0, 0)


#load "unix.cma"
#directory "+ANSITerminal"
#load "ANSITerminal.cma"
open ANSITerminal

let () =
  erase Screen


int main() {
	Process.system("clear");
	return 0;
}


[ $ &print("\33[2J",end='')& python ] is clearscreen


#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
 (void (charterm-clear-screen)))


/*REXX boilerplate determines how to clear screen (under various REXXes)*/
trace off;      parse arg !            /*turn off tracing; get C.L. args*/
if !all(arg())  then exit              /*Doc request?   Show, then exit.*/
if !cms then address ''                /*Is this CMS?  Use this address.*/

!cls                                   /*clear the (terminal) screen.   */            /* ◄═══   this is where  "it"  happens.*/

exit                                   /*stick a fork in it, we're done.*/
/*═════════════════════════════general 1-line subs══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
!all:  !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal:  if symbol('!CALL')\=="VAR" then !call=; return !call
!env:  !env='ENVIRONMENT'; if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM'; if !os2 then !env='OS2'!env; !ebcdic=1=='f0'x; if !crx then !env='DOS'; return
!fid:  parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _=lastpos('\',!fn); !fm=left(!fn,_); !fn=substr(!fn,_+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm,1+('0'arg(1)))
!rex:  parse upper version !ver !vernum !verdate .; !brexx='BY'==!vernum; !kexx='KEXX'==!ver; !pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver; !r4='REXX-R4'==!ver; !regina='REXX-REGINA'==left(!ver,11); !roo='REXX-ROO'==!ver; call !env; return
!sys:  !cms=!sys=='CMS'; !os2=!sys=='OS2'; !tso=!sys=='TSO'|!sys=='MVS'; !vse=!sys=='VSE'; !dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD'; !crx=left(!sys,6)=='DOSCRX'; call !rex; return
!var:  call !fid; if !kexx then return space(dosenv(arg(1))); return space(value(arg(1),,!env))


object Cls extends App {print("\033[2J")}


$ include "seed7_05.s7i";
  include "console.s7i";

const proc: main is func
  local
    var text: console is STD_NULL;
  begin
    console := open(CONSOLE);
    clear(console);
    # Terminal windows often restore the previous
    # content, when a program is terminated. Therefore
    # the program waits until Return/Enter is pressed.
    readln;
  end func;


func clear { print(static x = `clear`) };
clear();


fun clearScreen () =
  let
    val strm = TextIO.openOut (Posix.ProcEnv.ctermid ())
  in
    TextIO.output (strm, "\^[[H\^[[2J");
    TextIO.closeOut strm
  end


clear

# Alternative method using tput
tput clear


System.cmd(System.isWindows and "cls" or "clear");
// or, for ANSI terminals: print("\e[2J")


       .model small
       .stack 1024
       .data
       .code
start:

	mov ax,@data
	mov ds,ax

	mov ax,@code
	mov es,ax

	cld					;String functions are set to auto-increment

	mov ax,13h                              ;select 320x200 VGA
	int 10h

	mov ah,0Eh
	mov al,'A'                              ;select char to print
	mov bx,11                               ;select color to print it in
	int 10h

ExitDOS:
	mov ax,4C00h		                 ;return to dos
	int 21h
end start


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program colorterminal64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessStartPgm:            .asciz "Program start \n"
szMessEndPgm:              .asciz "Program normal end.\n"
szMessColorRed:            .asciz "Color red.\n"
szCodeInit:                .asciz "\033[0m"                    //color reinit
szCodeRed:                 .asciz "\033[31m"                   //color red
szMessBlue:                .asciz "\033[34mColor Blue\n"       //color blue
szMessTwoColor:            .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest:                .asciz "\033[33m\033[1mMessage yellow bold\n"

szCarriageReturn:          .asciz "\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:

    ldr x0,qAdrszMessStartPgm                   //display start message
    bl affichageMess
    ldr x0,qAdrszCodeRed                        //color red
    bl affichageMess
    ldr x0,qAdrszMessColorRed
    bl affichageMess
    ldr x0,qAdrszMessBlue                       //message color blue
    bl affichageMess
    ldr x0,qAdrszMessTwoColor                   //message two colors
    bl affichageMess
    ldr x0,qAdrszMessTest
    bl affichageMess
    ldr x0,qAdrszCodeInit                       //color reinitialize
    bl affichageMess
    ldr x0,qAdrszMessEndPgm                     //display end message
    bl affichageMess

100:                                            //standard end of the program
    mov x0,0                                    //return code
    mov x8,EXIT                                 //request to exit program
    svc 0                                       //perform system call
qAdrszMessStartPgm:        .quad szMessStartPgm
qAdrszMessEndPgm:          .quad szMessEndPgm
qAdrszCodeInit:            .quad szCodeInit
qAdrszCodeRed:             .quad szCodeRed
qAdrszMessBlue:            .quad szMessBlue
qAdrszMessColorRed:        .quad szMessColorRed
qAdrszMessTwoColor:        .quad szMessTwoColor
qAdrszMessTest:            .quad szMessTest
qAdrszCarriageReturn:      .quad szCarriageReturn
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


with Ada.Text_Io;

with Ansi;

procedure Coloured  is
   use Ada.Text_Io;
   subtype Ansi_Colors is Ansi.Colors
     range Ansi.Black .. Ansi.Colors'Last;  -- Avoid default
begin
   for Fg_Color in Ansi_Colors loop
      Put ("Rosetta ");
      Put (Ansi.Foreground (Fg_Color));
      for Bg_Color in Ansi_Colors loop
         Put (Ansi.Background (Bg_Color));
         Put ("Code");
      end loop;
      Put (Ansi.Reset);
      New_Line;
   end loop;
end Coloured;


/* ARM assembly Raspberry PI  */
/*  program colorText.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall

.equ BUFFERSIZE,          100

/* Initialized data */
.data
szMessStartPgm:            .asciz "Program start \n"
szMessEndPgm:              .asciz "Program normal end.\n"
szMessColorRed:            .asciz "Color red.\n"
szCodeInit:                .asciz "\033[0m"                    @ color reinit
szCodeRed:                 .asciz "\033[31m"                   @ color red
szMessBlue:                .asciz "\033[34mColor Blue\n"       @ color blue
szMessTwoColor:            .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest:                .asciz "\033[33m\033[1mMessage yellow bold\n"

szCarriageReturn:          .asciz "\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:

    ldr r0,iAdrszMessStartPgm                   @ display start message
    bl affichageMess
    ldr r0,iAdrszCodeRed                        @ color red
    bl affichageMess
    ldr r0,iAdrszMessColorRed
    bl affichageMess
    ldr r0,iAdrszMessBlue                       @ message color blue
    bl affichageMess
    ldr r0,iAdrszMessTwoColor                   @ message two colors
    bl affichageMess
    ldr r0,iAdrszMessTest
    bl affichageMess
    ldr r0,iAdrszCodeInit                       @ color reinitialize
    bl affichageMess
    ldr r0,iAdrszMessEndPgm                     @ display end message
    bl affichageMess

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call
iAdrszMessStartPgm:        .int szMessStartPgm
iAdrszMessEndPgm:          .int szMessEndPgm
iAdrszCodeInit:            .int szCodeInit
iAdrszCodeRed:             .int szCodeRed
iAdrszMessBlue:            .int szMessBlue
iAdrszMessColorRed:        .int szMessColorRed
iAdrszMessTwoColor:        .int szMessTwoColor
iAdrszMessTest:            .int szMessTest
iAdrszCarriageReturn:      .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return


str: "Hello World"

print color #red str
print color #green str
print color #blue str
print color #magenta str
print color #yellow str
print color #cyan str
print color #black str
print color #white str


DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
Loop 15
	 SetConsoleTextAttribute(hConsole, A_Index)
	,WriteConsole(hConsole, "AutoHotkey`n")

MsgBox

SetConsoleTextAttribute(hConsole, Attributes){
	return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes)
}
WriteConsole(hConsole, text){
	VarSetCapacity(out, 16)
	If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text)
				  , UPtrP, out, uint, 0 )
		return out
	return 0
}


' ANSI terminal coloured text
COLOR FG TO BLACK
PRINT "a word"

COLOR FG TO RED
PRINT "a word"

COLOR FG TO GREEN
PRINT "a word"

' Other colours include YELLOW, BLUE, MAGENTA, CYAN, WHITE
' Second keyword can be BG for background colour control
' The COLOR command also accepts keywords of NORMAL, INTENSE, INVERSE, RESET


FOR n = 1 TO 15
    COLOR n
    PRINT "Rosetta Code"
NEXT


      FOR col% = 0 TO 14
        COLOUR col% : REM foreground
        COLOUR 128+(15-col%) : REM background
        PRINT "Rosetta Code"
      NEXT


#include <stdio.h>

void table(const char *title, const char *mode)
{
	int f, b;
	printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
	for (b = 40; b <= 107; b++) {
		if (b == 48) b = 100;
		printf("%3d\t\033[%s%dm", b, mode, b);
		for (f = 30; f <= 97; f++) {
			if (f == 38) f = 90;
			printf("\033[%dm%3d ", f, f);
		}
		puts("\033[m");
	}
}

int main(void)
{
	int fg, bg, blink, inverse;

	table("normal ( ESC[22m or ESC[m )", "22;");
	table("bold ( ESC[1m )", "1;");
	table("faint ( ESC[2m ), not well supported", "2;");
	table("italic ( ESC[3m ), not well supported", "3;");
	table("underline ( ESC[4m ), support varies", "4;");
	table("blink ( ESC[5m )", "5;");
	table("inverted ( ESC[7m )", "7;");
	return 0;
}


static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.BackgroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Red on Yellow");
    Console.ForegroundColor = ConsoleColor.White;
    Console.BackgroundColor = ConsoleColor.Black;
    Console.WriteLine("White on black");
    Console.ResetColor();
    Console.WriteLine("Back to normal");
    Console.ReadKey();
}


*> Apologies for the repetitiveness.
       IDENTIFICATION  DIVISION.
       PROGRAM-ID. coloured-text.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       78  example-str VALUE "COBOL".

       01  fore-colour PIC 9.
       01  back-colour PIC 9.

       01  line-num    PIC 99 VALUE 1.
       01  col-num     PIC 99 VALUE 1.

       01  pause       PIC X.

       PROCEDURE DIVISION.
           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
               PERFORM VARYING back-colour FROM 0 BY 1
                       UNTIL back-colour > 7
                   DISPLAY example-str AT LINE line-num, COLUMN col-num
                       WITH FOREGROUND-COLOR fore-colour,
                       BACKGROUND-COLOR back-colour

                   ADD 6 TO col-num
               END-PERFORM

               ADD 1 TO line-num
               MOVE 1 TO col-num
           END-PERFORM

           DISPLAY "With HIGHLIGHT:" AT LINE line-num, COLUMN 1
           ADD 1 TO line-num

           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
               PERFORM VARYING back-colour FROM 0 BY 1
                       UNTIL back-colour > 7
                   DISPLAY example-str AT LINE line-num, COLUMN col-num
                       WITH FOREGROUND-COLOR fore-colour,
                       BACKGROUND-COLOR back-colour HIGHLIGHT

                   ADD 6 TO col-num
               END-PERFORM

               ADD 1 TO line-num
               MOVE 1 TO col-num
           END-PERFORM

           DISPLAY "With LOWLIGHT: (has no effect on many terminals)"
               AT LINE line-num, COLUMN 1
           ADD 1 TO line-num

           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
               PERFORM VARYING back-colour FROM 0 BY 1
                       UNTIL back-colour > 7
                   DISPLAY example-str AT LINE line-num, COLUMN col-num
                       WITH FOREGROUND-COLOR fore-colour,
                       BACKGROUND-COLOR back-colour LOWLIGHT

                   ADD 6 TO col-num
               END-PERFORM

               ADD 1 TO line-num
               MOVE 1 TO col-num
           END-PERFORM

           DISPLAY "With BLINK:" AT LINE line-num, COLUMN 1
           ADD 1 TO line-num

           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
               PERFORM VARYING back-colour FROM 0 BY 1
                       UNTIL back-colour > 7
                   DISPLAY example-str AT LINE line-num, COLUMN col-num
                       WITH FOREGROUND-COLOR fore-colour,
                       BACKGROUND-COLOR back-colour BLINK

                   ADD 6 TO col-num
               END-PERFORM

               ADD 1 TO line-num
               MOVE 1 TO col-num
           END-PERFORM

           DISPLAY "Press enter to continue."
               AT LINE line-num, COLUMN 1
           ACCEPT pause AT LINE line-num, COLUMN 40

           GOBACK
           .


UInt32 seed = 0
F nonrandom_choice(lst)
   :seed = 1664525 * :seed + 1013904223
   R lst[:seed % UInt32(lst.len)]

V board = Array(‘123456789’)
V wins = ([0, 1, 2], [3, 4, 5], [6, 7, 8],
          [0, 3, 6], [1, 4, 7], [2, 5, 8],
          [0, 4, 8], [2, 4, 6])

F printboard()
   print([0, 3, 6].map(x -> (:board[x .+ 3]).join(‘ ’)).join("\n"))

F score(board = board) -> (Char, [Int])?
   L(w) :wins
      V b = board[w[0]]
      I b C ‘XO’ & all(w.map(i -> @board[i] == @b))
         R (b, w.map(i -> i + 1))
   R N

F finished()
   R all(:board.map(b -> b C ‘XO’))

F space(board = board)
   R board.filter(b -> b !C ‘XO’)

F my_turn(xo, &board)
   V options = space()
   V choice = nonrandom_choice(options)
   board[Int(choice) - 1] = xo
   R choice

F my_better_turn(xo, &board)
   ‘Will return a next winning move or block your winning move if possible’
   V ox = I xo == ‘X’ {Char(‘O’)} E Char(‘X’)
   Int? oneblock
   V options = space(board).map(s -> Int(s) - 1)
   Int choice
   L(chc) options
      V brd = copy(board)
      brd[chc] = xo
      I score(brd) != N
         choice = chc
         L.break
      I oneblock == N
         brd[chc] = ox
         I score(brd) != N
            oneblock = chc
   L.was_no_break
      choice = oneblock ? nonrandom_choice(options)
   board[choice] = xo
   R choice + 1

F your_turn(xo, &board)
   V options = space()
   L
      V choice = input("\nPut your #. in any of these positions: #. ".format(xo, options.join(‘’))).trim((‘ ’, "\t", "\r", "\n"))
      I choice C options
         board[Int(choice) - 1] = xo
         R choice
      print(‘Whoops I don't understand the input’)

F me(xo = Char(‘X’))
   printboard()
   print("\nI go at "my_better_turn(xo, &:board))
   R score()

F you(xo = Char(‘O’))
   printboard()
   print("\nYou went at "my_turn(xo, &:board))
   R score()

L !finished()
   (Char, [Int])? s = me(Char(‘X’))
   I s != N
      printboard()
      print("\n#. wins along #.".format(s[0], s[1]))
      L.break
   I !finished()
      s = you(Char(‘O’))
      I s != N
         printboard()
         print("\n#. wins along #.".format(s[0], s[1]))
         L.break
L.was_no_break
   print("\nA draw")


(defun coloured-text ()
  (with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
    (dolist (i '(:red :green :yellow :blue :magenta :cyan :white))
      (add-string scr (format nil "~A~%" i) :fgcolor i))
      (refresh scr)
      ;; wait for keypress
      (get-char scr)))


import
    std.conv,
    std.stdio;

enum Color {
    fgBlack = 30,
    fgRed,
    fgGreen,
    fgYellow,
    fgBlue,
    fgMagenta,
    fgCyan,
    fgWhite,

    bgBlack = 40,
    bgRed,
    bgGreen,
    bgYellow,
    bgBlue,
    bgMagenta,
    bgCyan,
    bgWhite
}

string color(string text, Color ink) {
    return "\033["
        ~ ink.to!int.to!string
        ~ "m"
        ~ text
        ~ "\033[0m";
}

void main() {
    auto colors = [
        Color.fgBlack,
        Color.fgRed,
        Color.fgGreen,
        Color.fgYellow,
        Color.fgBlue,
        Color.fgMagenta,
        Color.fgCyan,
        Color.fgWhite
    ];

    foreach (c; colors) {
        // Print the color name, in white.
        c.to!string.color(Color.fgWhite).writeln;

        // Print some text in the color.
        "Hello, world!".color(c).writeln;
    }
}


with Ada.Text_IO, Ada.Numerics.Discrete_Random;
  -- can play human-human, human-computer, computer-human or computer-computer
  -- the computer isn't very clever: it just chooses a legal random move

procedure Tic_Tac_Toe is

   type The_Range is range 1 .. 3;
   type Board_Type is array (The_Range, The_Range) of Character;

   package Rand is new Ada.Numerics.Discrete_Random(The_Range);
   Gen: Rand.Generator; -- required for the random moves

   procedure Show_Board(Board: Board_Type) is
      use Ada.Text_IO;
   begin
      for Row in The_Range loop
         for Column in The_Range loop
            Put(Board(Row, Column));
         end loop;
         Put_Line("");
      end loop;
      Put_Line("");
   end Show_Board;

   function Find_Winner(Board: Board_Type) return Character is
      -- if 'x' or 'o' wins, it returns that, else it returns ' '

      function Three_Equal(A,B,C: Character) return Boolean is
      begin
         return (A=B) and (A=C);
      end Three_Equal;

   begin -- Find_Winner
      for I in The_Range loop
         if    Three_Equal(Board(I,1), Board(I,2), Board(I,3)) then
            return Board(I,1);
         elsif  Three_Equal(Board(1,I), Board(2,I), Board(3,I)) then
            return Board(1,I);
         end if;
      end loop;
      if Three_Equal(Board(1,1), Board(2,2), Board (3,3)) or
         Three_Equal(Board(3,1), Board(2,2), Board (1,3)) then
         return Board(2,2);
      end if;
      return ' ';
   end Find_Winner;

   procedure Do_Move(Board: in out Board_Type;
                     New_Char: Character; Computer_Move: Boolean) is
      Done: Boolean := False;
      C: Character;
      use Ada.Text_IO;

      procedure Do_C_Move(Board: in out Board_Type; New_Char: Character) is
         Found: Boolean := False;
         X,Y: The_Range;
      begin
         while not Found loop
            X := Rand.Random(Gen);
            Y := Rand.Random(Gen);
            if (Board(X,Y) /= 'x') and  (Board(X,Y) /= 'o') then
               Found := True;
               Board(X,Y) := New_Char;
            end if;
         end loop;
      end Do_C_Move;

   begin
      if Computer_Move then
         Do_C_Move(Board, New_Char);
      else -- read move;
         Put_Line("Choose your move, " & New_Char);
         while not Done loop
            Get(C);
            for Row in The_Range loop
               for Col in The_Range loop
                  if Board(Row, Col) = C then
                     Board(Row, Col) := New_Char;
                     Done := True;
                  end if;
               end loop;
            end loop;
         end loop;
      end if;
   end Do_Move;

   The_Board : Board_Type := (('1','2','3'), ('4','5','6'), ('7','8','9'));
   Cnt_Moves: Natural := 0;
   Players: array(0 .. 1) of Character := ('x', 'o'); -- 'x' begins
   C_Player: array(0 .. 1) of Boolean := (False, False);
   Reply: Character;

begin -- Tic_Tac_Toe

   -- firstly, ask whether the computer shall take over either player
   for I in Players'Range loop
      Ada.Text_IO.Put_Line("Shall " & Players(I) &
                             " be run by the computer? (y=yes)");
      Ada.Text_IO.Get(Reply);
      if Reply='y' or Reply='Y' then
         C_Player(I) := True;
         Ada.Text_IO.Put_Line("Yes!");
      else
         Ada.Text_IO.Put_Line("No!");
      end if;
   end loop;
   Rand.Reset(Gen); -- to initalize the random generator

   -- now run the game
   while (Find_Winner(The_Board) = ' ') and (Cnt_Moves < 9) loop
      Show_Board(The_Board);
      Do_Move(The_Board, Players(Cnt_Moves mod 2), C_Player(Cnt_Moves mod 2));
      Cnt_Moves := Cnt_Moves + 1;
   end loop;
   Ada.Text_IO.Put_Line("This is the end!");

   -- finally, output the outcome
   Show_Board (The_Board);
   if Find_Winner(The_Board) = ' ' then
      Ada.Text_IO.Put_Line("Draw");
   else
      Ada.Text_IO.Put_Line("The winner is: " & Find_Winner(The_Board));
   end if;
end Tic_Tac_Toe;


## after PARI/GP

#     C: for( initcode ; condcode ; incrcode ) {body}
# .[q]           [1]        [2]        [3]       [4]
# #           [initcode] [condcode] [incrcode] [body] (for)
[ [q]S. 4:.3:.2:.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x
    Os.L.o
]sF                                             # F = for

[
    27P         ## ESC
    91P         ## Bra ... together: CSI
    n           ## colour 1 (fg)
    [;]P        ## ";"
    n           ## colour 2 (bg)
    [;1m]P      ## ";1m"
]sS
[
    27P         ## ESC
    91P         ## Bra ... together: CSI
    [0m]P       ## "0m"
]sR

[0q]s0 [<0 1]sL ## L: isle

## for b=40 b<=47 ++b
## for f=30 f<=37 ++f
[40sb] [lb 47 lLx] [lb 1+ sb] [
    [30sf] [lf 37 lLx] [lf 1+ sf] [
        lb lf lSx [colour-blind]P lRx [ ]P
    ] lFx       ## for b
    AP
] lFx   ## for f


open System

Console.ForegroundColor <- ConsoleColor.Red
Console.BackgroundColor <- ConsoleColor.Yellow
Console.WriteLine("Red on Yellow")

Console.ForegroundColor <- ConsoleColor.White
Console.BackgroundColor <- ConsoleColor.Black
Console.WriteLine("White on Black")

Console.ForegroundColor <- ConsoleColor.Green
Console.BackgroundColor <- ConsoleColor.Blue
Console.WriteLine("Green on Blue")

Console.ResetColor()
Console.WriteLine("Back to normal")
Console.ReadKey()


( ANSI terminal control lexicon Colored Text)
DECIMAL
( support routines)
 27 CONSTANT ESC
: <##>    ( n -- ) ( sends n, radix 10, no spaces)
          BASE @ >R   0 <# #S #> TYPE   R> BASE ! ;

: ESC[   ( -- )   ESC EMIT ." [" ;
( Attributes )
1 CONSTANT BOLD    2 CONSTANT DIM    3 CONSTANT ITALIC
5 CONSTANT BLINK   7 CONSTANT REV    8 CONSTANT BLANK

( Colors )
0 CONSTANT BLACK   1 CONSTANT RED    2 CONSTANT GREEN
3 CONSTANT YELLOW  4 CONSTANT BLUE   5 CONSTANT MAGENTA
6 CONSTANT CYAN    7 CONSTANT WHITE

: ATTR   ( attribute ) ESC[ <##> ." m" ;  ( use:  BOLD ATTR       )
: TEXT       ( color ) 30 + ATTR ;        ( use:  YELLOW TEXT     )
: BACKGROUND ( color ) 40 + ATTR ;        ( use:  BLUE BACKGROUND )


! Standard Fortran, should work with any modern compiler (tested gfortran 9)
! and ANSI supporting terminal (tested Linux, various terminals).
program coloured_terminal_text
  use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
  implicit none

  ! Some parameters for our ANSI escape codes
  character(*), parameter :: esc = achar(27) ! Escape character.
  character(*), parameter :: reset = esc // '[0m' ! Terminates an ANSI code.
  ! Foreground(font) Colours
  character(*), parameter :: red     = esc // '[31m'
  character(*), parameter :: green   = esc // '[32m'
  character(*), parameter :: yellow  = esc // '[33m'
  character(*), parameter :: blue    = esc // '[34m'
  character(*), parameter :: magenta = esc // '[35m'
  character(*), parameter :: cyan    = esc // '[36m'
  character(*), parameter :: grey    = esc // '[90m' !Bright-Black
  ! One background colour
  character(*), parameter :: background_green = esc // '[42m'
  ! Some other formatting
  character(*), parameter :: bold = esc // '[1m'
  character(*), parameter :: bold_blink = esc // '[1;5m'

  ! Write to terminal (stderr, use OUTPUT_UNIT for stdout)
  write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
  write(ERROR_UNIT, '(4x, a)')       &
      red     // 'Red'     // reset, &
      green   // 'Green'   // reset, &
      yellow  // 'Yellow'  // reset, &
      blue    // 'Blue'    // reset, &
      magenta // 'Magenta' // reset, &
      cyan    // 'Cyan'    // reset, &
      grey    // 'Grey'    // reset
  write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset

  write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text


begin

    string(10) board;

    % initialise the board                                                   %
    procedure initBoard ; board := " 123456789";

    % display the board                                                      %
    procedure showBoard ;
        begin
            s_w := 0;
            write( board(1//1), "|", board(2//1), "|", board(3//1) );
            write( "-+-+-" );
            write( board(4//1), "|", board(5//1), "|", board(6//1) );
            write( "-+-+-" );
            write( board(7//1), "|", board(8//1), "|", board(9//1) )
        end showBoard ;

    % returns true if board pos is free, false otherwise                     %
    logical procedure freeSpace( integer value pos ) ;
        ( board(pos//1) >= "1" and board(pos//1) <= "9" );

    % check for game over                                                    %
    logical procedure gameOver ;
        begin
            logical noMoves;
            noMoves := true;
            for i := 1 until 9 do if noMoves then noMoves := not freeSpace( i );
            noMoves
        end gameOver ;

    % makes the specified winning move or blocks it, if it will win          %
    logical procedure winOrBlock( integer   value pos1, pos2, pos3
                                ; string(1) value searchCharacter
                                ; string(1) value playerCharacter
                                ) ;
        if      board(pos1//1) = searchCharacter
            and board(pos2//1) = searchCharacter
            and freeSpace( pos3 )
        then begin
            board(pos3//1) := playerCharacter;
            true
            end
        else if board(pos1//1) = searchCharacter
            and freeSpace( pos2 )
            and board(pos3//1) = searchCharacter
        then begin
            board(pos2//1) := playerCharacter;
            true
            end
        else if freeSpace( pos1 )
            and board(pos2//1) = searchCharacter
            and board(pos3//1) = searchCharacter
        then begin
            board(pos1//1) := playerCharacter;
            true
            end
        else begin
            false
        end winOrBlock ;

    % makes a winning move or blocks a winning move, if there is one         %
    logical procedure makeOrBlockWinningMove( string(1) value searchCharacter
                                            ; string(1) value playerCharacter
                                            ) ;
        (  winOrBlock( 1, 2, 3, searchCharacter, playerCharacter )
        or winOrBlock( 4, 5, 6, searchCharacter, playerCharacter )
        or winOrBlock( 7, 8, 9, searchCharacter, playerCharacter )
        or winOrBlock( 1, 4, 7, searchCharacter, playerCharacter )
        or winOrBlock( 2, 5, 8, searchCharacter, playerCharacter )
        or winOrBlock( 3, 6, 9, searchCharacter, playerCharacter )
        or winOrBlock( 1, 5, 9, searchCharacter, playerCharacter )
        or winOrBlock( 3, 5, 7, searchCharacter, playerCharacter )
        ) ;

    % makes a move when there isn't an obvious winning/blocking move         %
    procedure move ( string(1) value playerCharacter ) ;
        begin
            logical moved;
            moved := false;
            % try for the centre, a corner or the midle of a line            %
            for pos := 5, 1, 3, 7, 9, 2, 4, 6, 8 do begin
                if not moved and freeSpace( pos ) then begin
                    moved := true;
                    board(pos//1) := playerCharacter
                end
            end
        end move ;

    % gets a move from the user                                              %
    procedure userMove( string(1) value playerCharacter ) ;
        begin
            integer move;
            while
                begin
                    write( "Please enter the move for ", playerCharacter, " " );
                    read( move );
                    ( move < 1 or move > 9 or not freeSpace( move ) )
                end
            do  begin
                write( "Invalid move" )
            end;
            board(move//1) := playerCharacter
        end userMove ;

    % returns true if the three board positions have the player character,   %
    %         false otherwise                                                %
    logical procedure same( integer   value pos1, pos2, pos3
                          ; string(1) value playerCharacter
                          ) ;
        (   board(pos1//1) = playerCharacter
        and board(pos2//1) = playerCharacter
        and board(pos3//1) = playerCharacter
        );

    % returns true if the player has made a winning move, false otherwise    %
    logical procedure playerHasWon( string(1) value playerCharacter ) ;
        (  same( 1, 2, 3, playerCharacter )
        or same( 4, 5, 6, playerCharacter )
        or same( 7, 8, 9, playerCharacter )
        or same( 1, 4, 7, playerCharacter )
        or same( 2, 5, 8, playerCharacter )
        or same( 3, 6, 9, playerCharacter )
        or same( 1, 5, 9, playerCharacter )
        or same( 3, 5, 7, playerCharacter )
        ) ;

    % takes a players turn - either automated or user input                  %
    procedure turn ( string(1) value playerCharacter, otherCharacter
                   ; logical   value playerIsUser
                   ) ;
        begin
            if playerIsUser then userMove( playerCharacter )
            else begin
                write( playerCharacter, " moves..." );
                if  not makeOrBlockWinningMove( playerCharacter, playerCharacter )
                and not makeOrBlockWinningMove( otherCharacter,  playerCharacter )
                then move( playerCharacter )
            end;
            showBoard
        end turn ;

    % asks a question and returns true if the user inputs y/Y,               %
    % false otherwise                                                        %
    logical procedure yes( string(32) value question ) ;
        begin
            string(1) answer;
            write( question );
            read( answer );
            answer = "y" or answer = "Y"
        end yes ;

    % play the game                                                          %
    while
        begin
            string(1)  again;
            string(32) gameResult;
            logical    oIsUser, xIsUser;

            oIsUser := yes( "Do you want to play O? " );
            xIsUser := yes( "Do you want to play X? " );

            gameResult := "it's a draw";
            initBoard;
            showBoard;
            while not gameOver and not playerHasWon( "O" ) and not playerHasWon( "X" ) do begin
                turn( "O", "X", oIsUser );
                if playerHasWon( "O" ) then gameResult := "O wins"
                else if not gameOver then begin
                    turn( "X", "O", xIsUser );
                    if playerHasWon( "X" ) then gameResult := "X wins"
                end
            end ;
            write( gameResult );

            yes( "Play again? " )
        end
    do  begin end

end.


for i as uinteger = 0 to 15
    color i, 15-i
    print "Colour "+str(i),
    if i mod 4 = 3 then color 0,0: print
next i


import console.*

bold()
blink()

if $os.toLowerCase().startsWith( 'win' )
  println( 'not supported' )
else
  println( 'good to go' )

reset()

println( RED + 'Red', GREEN + 'Green', BLUE + 'Blue', MAGENTA + 'Magenta', CYAN + 'Cyan', YELLOW + 'Yellow' + RESET )


package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    color(red)
    fmt.Println("Red")
    color(green)
    fmt.Println("Green")
    color(blue)
    fmt.Println("Blue")
}

const (
    blue  = "1"
    green = "2"
    red   = "4"
)

func color(c string) {
    cmd := exec.Command("tput", "setf", c)
    cmd.Stdout = os.Stdout
    cmd.Run()
}


#!/usr/bin/env golosh
----
This module demonstrates terminal colours.
----
module Terminalcontrolcoloredtext

import gololang.AnsiCodes

function main = |args| {

  # these are lists of pointers to the ansi functions in the golo library.
  # {} doesn't do anything so it's got no effect on the text.

  let foregrounds = vector[
    ^fg_red, ^fg_blue, ^fg_magenta, ^fg_white, ^fg_black, ^fg_cyan, ^fg_green, ^fg_yellow
  ]
  let backgrounds = vector[
    ^bg_red, ^bg_blue, ^bg_magenta, ^bg_white, ^bg_black, ^bg_cyan, ^bg_green, ^bg_yellow
  ]
  let effects = vector[
    {}, ^bold, ^blink, ^underscore, ^concealed, ^reverse_video
  ]

  println("Terminal supports ansi code: " + likelySupported())

  foreach fg in foregrounds {
    foreach bg in backgrounds {
      foreach effect in effects {
        fg()
        bg()
        effect()
        print("Rosetta Code")
        reset()
      }
    }
  }
  println("")
}


property OMask : missing value
property XMask : missing value
property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448}
property difficulty : missing value

repeat
   set OMask to 0
   set XMask to 0

   if button returned of (display dialog "Who should start?" buttons {"I shoud", "CPU"}) = "CPU" then set OMask to npcGet()
   set difficulty to button returned of (display dialog "Please choose your difficulty" buttons {"Hard", "Normal"})

   repeat
       set XMask to XMask + 2 ^ (nGet() - 1)
       if winnerForMask(XMask) or OMask + XMask = 511 then exit repeat
       set OMask to npcGet()
       if winnerForMask(OMask) or OMask + XMask = 511 then exit repeat
   end repeat

   if winnerForMask(OMask) then
       set msg to "CPU Wins!"
   else if winnerForMask(XMask) then
       set msg to "You WON!!!"
   else
       set msg to "It's a draw"
   end if

   display dialog msg & return & return & drawGrid() & return & return & "Do you want to play again?"
end repeat

on nGet()
   set theMessage to "It's your turn Player 1, please fill in the number for X" & return & return & drawGrid()
   repeat
       set value to text returned of (display dialog theMessage default answer "")
       if (offset of value in "123456789") is not 0 then
           if not positionIsUsed(value as integer) then exit repeat
       end if
   end repeat
   return value as integer
end nGet

on npcGet()
   --first get the free positions
   set freeSpots to {}
   repeat with s from 1 to 9
       if not positionIsUsed(s) then set end of freeSpots to 2 ^ (s - 1)
   end repeat
   --second check if 1 move can make the CPU win
   repeat with spot in freeSpots
       if winnerForMask(OMask + spot) then return OMask + spot
   end repeat

   if difficulty is "Hard" and OMask is 0 then
       if XMask = 1 or XMask = 4 then return 2
       if XMask = 64 or XMask = 256 then return 128
   end if
   --third check if a user can make make it win (defensive) place it on position
   repeat with spot in freeSpots
       if winnerForMask(XMask + spot) then return OMask + spot
   end repeat

   --fourth check if CPU can win in two moves
   repeat with spot1 in freeSpots
       repeat with spot2 in freeSpots
           if winnerForMask(OMask + spot1 + spot2) then return OMask + spot2
       end repeat
   end repeat
   --fifth check if player can win in two moves
   repeat with spot1 in freeSpots
       repeat with spot2 in reverse of freeSpots
           if winnerForMask(XMask + spot1 + spot2) then return OMask + spot1
       end repeat
   end repeat
   --at last pick a random spot
   if XMask + OMask = 0 and difficulty = "Hard" then return 1

   return OMask + (some item of freeSpots)
end npcGet

on winnerForMask(mask)
   repeat with winLine in winningNumbers
       if BWAND(winLine, mask) = contents of winLine then return true
   end repeat
   return false
end winnerForMask

on drawGrid()
   set grid to ""
   repeat with o from 0 to 8
       if BWAND(OMask, 2 ^ o) = 2 ^ o then
           set grid to grid & "O"
       else if BWAND(XMask, 2 ^ o) = 2 ^ o then
           set grid to grid & "X"
       else
           set grid to grid & o + 1
       end if
       if o is in {2, 5} then set grid to grid & return
   end repeat
   return grid
end drawGrid

on positionIsUsed(pos)
   return BWAND(OMask + XMask, 2 ^ (pos - 1)) = 2 ^ (pos - 1)
end positionIsUsed

on BWAND(n1, n2)
   set theResult to 0
   repeat with o from 0 to 8
       if (n1 mod 2) = 1 and (n2 mod 2) = 1 then set theResult to theResult + 2 ^ o
       set {n1, n2} to {n1 div 2, n2 div 2}
   end repeat
   return theResult as integer
end BWAND


10 FOR I = 0 TO 31
20 COLOR I, 7 - (I MOD 8)
30 PRINT I;
40 IF I MOD 4 = 3 THEN COLOR 7, 0 : PRINT
50 NEXT I


#!/usr/bin/runhaskell

import System.Console.ANSI

colorStrLn :: ColorIntensity -> Color -> ColorIntensity -> Color -> String -> IO ()
colorStrLn fgi fg bgi bg str = do
  setSGR [SetColor Foreground fgi fg, SetColor Background bgi bg]
  putStr str
  setSGR []
  putStrLn ""

main = do
  colorStrLn Vivid White Vivid Red "This is red on white."
  colorStrLn Vivid White Dull Blue "This is white on blue."
  colorStrLn Vivid Green Dull Black "This is green on black."
  colorStrLn Vivid Yellow Dull Black "This is yellow on black."
  colorStrLn Dull Black Vivid Blue "This is black on light blue."


NB. relies on an vt100 terminal

CSI=: 27 91 { a.
'BLACK BLUE CYAN WHITE'=: 0 4 6 7
'OFF REVERSEVIDEO'=: 0 7

HIDECURSOR=: CSI,'?25l'
SHOWCURSOR=: CSI,'?25h'

csi=: (,~ (CSI , (' '&=)`(,:&';')}@:":))~
clear=: csi&'J'
attributes=: csi&'m'
color=: BLACK&$: : ([email protected]:(40 30 + ,)) NB. BACKGROUND color FOREGROUND
move=: csi&'H'

upward=: csi&'A'
downward=: csi&'B'
foreward=: csi&'C'
backward=: csi&'D'

DB=: (downward , backward) ''

NB. J is character vector to simulate the J icon.
J=: (BLUE color WHITE[CYAN)
J=: J , (backward 1),' T ',(backward 1),DB,,3#,:'|',DB
J=: J , (backward 5),'*    |',DB
J=: J , (backward 5),'\____/'
smoutput(color BLACK),(clear 2),(move 8 22),J,(WHITE color BLACK),(downward 2)


Gui, Add, Button, x12 y12 w30 h30 vB1 gButtonHandler,
Gui, Add, Button, x52 y12 w30 h30 vB2 gButtonHandler,
Gui, Add, Button, x92 y12 w30 h30 vB3 gButtonHandler,
Gui, Add, Button, x12 y52 w30 h30 vB4 gButtonHandler,
Gui, Add, Button, x52 y52 w30 h30 vB5 gButtonHandler,
Gui, Add, Button, x92 y52 w30 h30 vB6 gButtonHandler,
Gui, Add, Button, x12 y92 w30 h30 vB7 gButtonHandler,
Gui, Add, Button, x52 y92 w30 h30 vB8 gButtonHandler,
Gui, Add, Button, x92 y92 w30 h30 vB9 gButtonHandler,
; Generated using SmartGUI Creator 4.0
Gui, Show, x127 y87 h150 w141, Tic-Tac-Toe
Winning_Moves := "123,456,789,147,258,369,159,357"
Return

ButtonHandler:
    ; Fired whenever the user clicks on an enabled button
    Go(A_GuiControl,"X")
    GoSub MyMove
Return

MyMove: ; Loops through winning moves. First attempts to win, then to block, then a random move
    Went=0
    Loop, parse, Winning_Moves,`,
    {
        Current_Set := A_LoopField
        X:=O:=0
        Loop, parse, Current_Set
        {
            GuiControlGet, Char,,Button%A_LoopField%
            If ( Char = "O" )
                O++
            If ( Char = "X" )
                X++
        }
        If ( O = 2 and X = 0 ) or ( X = 2 and O = 0 ){
            Finish_Line(Current_Set)
            Went = 1
            Break ; out of the Winning_Moves Loop to ensure the computer goes only once
        }
    }
    If (!Went)
        GoSub RandomMove
Return

Go(Control,chr){
    GuiControl,,%Control%, %chr%
    GuiControl,Disable,%Control%
    GoSub, CheckWin
}

CheckWin:
    Loop, parse, Winning_Moves,`,
    {
        Current_Set := A_LoopField
        X:=O:=0
        Loop, parse, Current_Set
        {
            GuiControlGet, Char,,Button%A_LoopField%
            If ( Char = "O" )
                O++
            If ( Char = "X" )
                X++
        }
        If ( O = 3 ){
            Msgbox O Wins!
            GoSub DisableAll
            Break
        }
        If ( X = 3 ){
            MsgBox X Wins!
            GoSub DisableAll
            Break
        }
    }
return

DisableAll:
    Loop, 9
        GuiControl, Disable, Button%A_Index%
return

Finish_Line(Set){ ;   Finish_Line is called when a line exists with 2 of the same character. It goes in the remaining spot, thereby blocking or winning.
    Loop, parse, set
    {
        GuiControlGet, IsEnabled, Enabled, Button%A_LoopField%
        Control=Button%A_LoopField%
        If IsEnabled
            Go(Control,"O")
    }
}

RandomMove:
    Loop{
        Random, rnd, 1, 9
        GuiControlGet, IsEnabled, Enabled, Button%rnd%
        If IsEnabled
        {
            Control=Button%rnd%
            Go(Control,"O")
            Break
        }
    }
return

GuiClose:
ExitApp


using AnsiColor

function showbasecolors()
    for color in keys(Base.text_colors)
        print_with_color(color, " ", string(color), " ")
    end
    println()
end

function showansicolors()
    for fore in keys(AnsiColor.COLORS)
        print(@sprintf("%15s ", fore))
        for back in keys(AnsiColor.COLORS)
            print(" ", colorize(fore, "RC", background=back), " ")
        end
        println()
    end
    println()
    for eff in keys(AnsiColor.MODES)
        print(@sprintf(" %s ", eff), colorize("default", "RC", mode=eff))
    end
    println()
end

if Base.have_color
    println()
    println("Base Colors")
    showbasecolors()
    println("\nusing AnsiColor")
    showansicolors()
    println()
else
    println("This terminal appears not to support color.")
end


// version 1.1.2

const val ESC = "\u001B"
const val NORMAL = ESC + "[0"
const val BOLD   = ESC + "[1"
const val BLINK  = ESC + "[5"      // not working on my machine
const val BLACK  = ESC + "[0;40m"  // black background
const val WHITE  = ESC + "[0;37m"  // normal white foreground

fun main(args: Array<String>) {
    print("${ESC}c") // clear terminal first
    print(BLACK)     // set background color to black
    val foreColors = listOf(
        ";31m" to "red",
        ";32m" to "green",
        ";33m" to "yellow",
        ";34m" to "blue",
        ";35m" to "magenta",
        ";36m" to "cyan",
        ";37m" to "white"
    )
    for (attr in listOf(NORMAL, BOLD, BLINK)) {
        for (color in foreColors) println("$attr${color.first}${color.second}")
    }
    println(WHITE)  // set foreground color to normal white
}


#!/usr/bin/lasso9

define ec(code::string) => {

	local(esc		= decode_base64('Gw=='))
	local(codes		= map('esc' = #esc,
		'normal'	= #esc + '[0m',
		'blink'		= #esc + '[5;31;49m',
		'red'		= #esc + '[31;49m',
		'blue'		= #esc + '[34;49m',
		'green'		= #esc + '[32;49m',
		'magenta'	= #esc + '[35;49m',
		'yellowred'	= #esc + '[33;41m'
	))

	return #codes -> find(#code)
}

stdout( ec('red'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('blue'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('green'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('magenta'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('yellowred'))
stdout('So this is the Rosetta Code!')
stdoutnl( ec('blink'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('normal'))


10 mode 1:defint a-z
20 print "Mode 1 (4 colors):"
30 for y=0 to 3
40 for x=0 to 3
50 pen x:paper y:print "Test";
60 next
70 print
80 next
90 pen 1:paper 0
100 locate 1,25:print "<Press any key>";:call &bb06
110 ink 1,8,26
120 ink 2,21,17
130 locate 1,25:print "Flashing inks --- <Press any key>";:call &bb06
140 speed ink 8,3
150 locate 1,25:print "Different flashing --- <Press any key>";:call &bb06
160 ink 1,24:ink 2,20  ' back to defaults -- see chapter 1, page 50 in CPC manual
170 pen 1:paper 0:mode 0:speed ink 50,50
180 print "Mode 0 (16 colors):"
190 for i=0 to 15
200 pen i
210 if i=0 then paper 1 else paper 0
220 print using "##";i;
230 for j=1 to 18
240 print chr$(143);
250 next
260 next
270 pen 1:paper 0
280 print "Paper/pen 14 and 15"
290 print "are set to";
300 pen 14:print " flashing":pen 1
310 print "by default."
320 print
330 print "*End of color demo*"
340 locate 1,25:print "<Press any key>";:call &bb06
350 mode 1


Run["tput setaf 1"]; Print["Coloured Text"];
Run["tput setaf 2"]; Print["Coloured Text"];
Run["tput setaf 3"]; Print["Coloured Text"]


import Terminal
setForegroundColor(fgRed)
echo "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"

setBackgroundColor(bgBlue)
setForegroundColor(fgYellow)
stdout.write "This is an "
writeStyled  "important"
stdout.write " word"
resetAttributes()
stdout.write "\n"

setForegroundColor(fgYellow)
echo "RosettaCode!"

setForegroundColor(fgCyan)
echo "RosettaCode!"

setForegroundColor(fgGreen)
echo "RosettaCode!"

setForegroundColor(fgMagenta)
echo "RosettaCode!"


$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma

# open ANSITerminal ;;
# print_string [cyan; on_blue] "Hello\n" ;;
Hello
- : unit = ()


#!/bin/bash
declare -a B=( e e e  e e e  e e e )  # Board

function show(){  # show B - underline first 2 rows; highlight position; number empty positoins
  local -i p POS=${1:-9}; local UL BOLD="\e[1m" GREEN="\e[32m" DIM="\e[2m" OFF="\e[m" ULC="\e[4m"
  for p in 0 1 2 3 4 5 6 7 8; do
    [[ p%3 -eq 0 ]] && printf "  "                             # indent boards
    UL=""; [[ p/3 -lt 2 ]] && UL=$ULC                          # underline first 2 rows
    [[ p -eq POS ]]   && printf "$BOLD$GREEN"                  # bold and colour for this position
    [[ ${B[p]} = e ]] && printf "$UL$DIM%d$OFF" $p || printf "$UL%s$OFF" ${B[p]}  # num or UL
    { [[ p%3 -lt 2 ]] && printf "$UL | $OFF"; } || printf "\n" # underline vertical bars or NL
  done
};

function win(){  # win 'X' 3 return true if X wins after move in position 3
  local ME=$1; local -i p=$2
  [[ ${B[p/3*3]} = $ME && ${B[p/3*3+1]} = $ME && ${B[p/3*3+2]} = $ME ]] && return 0  # row
  [[ ${B[p]}     = $ME && ${B[(p+3)%9]} = $ME && ${B[(p+6)%9]} = $ME ]] && return 0  # col
  [[ ${B[4]} != $ME ]] && return 1                                                   # don't test diags
  [[ p%4 -eq 0 && ${B[0]} = $ME && ${B[8]} = $ME ]] && return 0                      # TL - BR diag
  [[ p%4 -eq 2 || p -eq 4 ]] && [[ ${B[2]} = $ME && ${B[6]} = $ME ]]                 # TR - BL diag
};

function bestMove(){  # return best move or 9 if none possible
  local ME=$1 OP=$2; local -i o s p
  local -ia S=( -9 -9 -9  -9 -9 -9  -9 -9 -9 )  # score board
  local -a SB                                   # save board
  [[ ${B[*]//[!e]} = "" ]] && return 9          # game over
  SB=( ${B[*]} )                                # save Board
  for p in 0 1 2 3 4 5 6 7 8; do                          # for each board position
    [[ ${B[p]} != e ]] && continue                        # skip occupied positions
    B[p]=$ME                                              # occupy position
    win $ME $p && { S[p]=2; B=( ${SB[*]} ); return $p; }  # ME wins so this is best move
    bestMove $OP $ME; o=$?                                # what will opponent do
    [[ o -le 8 ]] && { B[o]=$OP; win $OP $o; s=$?; }      # opponent can make a legal move
    S[p]=${s:-1}                                          # save result of opponent move
    B=( ${SB[*]} )                                        # restore board after each trial run
  done
  local -i best=-1; local -ia MOV=()
  for p in 0 1 2 3 4 5 6 7 8; do                     # find all best moves
    [[ S[p] -lt 0 ]] && continue                     # dont bother with occupied positions
    [[ S[p] -eq S[best] ]] && { MOV+=(p); best=p; }  # add this move to current list
    [[ S[p] -gt S[best] ]] && { MOV=(p); best=p; }   # a better move so scrap list and start again
  done
  return ${MOV[ RANDOM%${#MOV[*]} ]}  # pick one at random
};

function getMove(){  # getMove from opponent
  [[ $ME = X ]] && { bestMove $ME $OP; return $?; }     # pick X move automatically
  read -p "O move: " -n 1; printf "\n"; return $REPLY   # get opponents move
};

function turn(){  # turn starts or continues a game. It is ME's turn
  local -i p; local ME=$1 OP=$2
  getMove; p=$?; [[ p -gt 8 ]] && { printf "Draw!\n"; show; return 1; }  # no move so a draw
  B[p]=$ME; printf "%s moves %d\n" $ME $p                                # mark board
  win $ME $p && { printf "%s wins!\n" $ME; show $p; [[ $ME = X ]] && return 2; return 0; }
  [[ ${B[*]//[!e]} = "" ]] && { printf "Draw!\n"; show; return 1; }      # no move so a draw
  show $p; turn $OP $ME                                                  # opponent moves
};

printf "Bic Bash Bow\n"
show; [[ RANDOM%2 -eq 0 ]] && { turn O X; exit $?; } || turn X O


#!/usr/bin/rexx
/*.----------------------------------------------------------------------.*/
/*|bashcolours: Display a table showing all of the possible colours that |*/
/*|             can be generated using ANSI escapes in bash in an xterm  |*/
/*|             terminal session.                                        |*/
/*|                                                                      |*/
/*|Usage:                                                                |*/
/*|                                                                      |*/
/*|>>-bashcolours-.----------.-----------------------------------------><|*/
/*|               |-- -? ----|                                           |*/
/*|               |-- -h ----|                                           |*/
/*|               '- --help -'                                           |*/
/*|                                                                      |*/
/*|where                                                                 |*/
/*|  -?, -h or --help                                                    |*/
/*|         display this documentation.                                  |*/
/*|                                                                      |*/
/*|This program is based on the shell script in the Bash Prompt HowTo at |*/
/*|http://www.tldp.org/, by Giles Orr.                                   |*/
/*|                                                                      |*/
/*|This program writes the various colour codes to the terminal to       |*/
/*|demonstrate what's available.  Each line showshe colour code of one   |*/
/*|forground colour, out of 17 (default + 16 escapes), followed by a test|*/
/*|use of that colour on all nine background colours (default + 8        |*/
/*|escapes).  Additional highlighting escapes are also demonstrated.     |*/
/*|                                                                      |*/
/*|This program uses object-oriented features of Open Object Rexx.       |*/
/*|The lineout method is used instead of say for consistency with use of |*/
/*|the charout method.                                                   |*/
/*'----------------------------------------------------------------------'*/
  call usage arg(1)
  trace normal

/* See if escapes work on the kind of terminal in use. */
  if value('TERM',,'ENVIRONMENT') = 'LINUX' then
    do
      say 'The Linux console does not support ANSI escape sequences for',
          'changing text colours or highlighting.'
      exit 4
    end

/* Set up the escape sequences. */
  ! = '1B'x                                                  -- ASCII escape
  bg = .array~of('[40m','[41m','[42m','[43m','[44m','[45m','[46m','[47m')
  fg = .array~of('[0m',   '[1m',   '[0;30m','[1;30m','[0;31m','[1;31m',,
                 '[0;32m','[1;32m','[0;33m','[1;33m','[0;34m','[1;34m',,
                 '[0;35m','[1;35m','[0;36m','[1;36m','[0;37m','[1;37m')
  hi = .array~of('[4m','[5m','[7m','[8m')
  text = 'gYw'                                              -- The test text
  .OUTPUT~lineout(' ')
  .OUTPUT~lineout('Foreground  |       Background Codes')
  .OUTPUT~lineout(!'[4mCodes       '!'[0m|'||,
                  !'[4m~[40m ~[41m ~[42m ~[43m ~[44m ~[45m ~[46m ~[47m'!'[0m')

  do f = 1 to fg~size                          -- write the foreground info.
    prefix = '~'fg[f]~left(6)' '!||fg[f]~strip' 'text
    .OUTPUT~charout(prefix)

    do b = 1 to bg~size                        -- write the background info.
      segment = !||fg[f]~strip !||bg[b]' 'text' '!||fg[1]
      .OUTPUT~charout(segment)
    end

    .OUTPUT~lineout(' ')
  end

/* Write the various highlighting escape sequences. */
  prefix = '~[4m'~left(6)'   '!||hi[1]'Underlined'!||fg[1]
  .OUTPUT~lineout(prefix)
  prefix = '~[5m'~left(6)'   '!||hi[2]'Blinking'!||fg[1]
  .OUTPUT~lineout(prefix)
  prefix = '~[7m'~left(6)'   '!||hi[3]'Inverted'!||fg[1]
  .OUTPUT~lineout(prefix)
  prefix = '~[8m'~left(6)'   '!||hi[4]'Concealed'!||fg[1],
           "(Doesn't seem to work in my xterm; might in Windows?)"
  .OUTPUT~lineout(prefix)
  .OUTPUT~lineout(' ')
  .OUTPUT~lineout("Where ~ denotes the ASCII escape character ('1B'x).")
  .OUTPUT~lineout(' ')
exit

/*.--------------------------------------------------------.*/
/*|One might expect to be able to use directory collections|*/
/*|as below instead of array collections, but there is no  |*/
/*|way to guarantee that a directory's indices will be     |*/
/*|iterated over in a consistent sequence, since directory |*/
/*|objects are not ordered.  Oh, well...                   |*/
/*'--------------------------------------------------------'*/
  fg = .directory~new
  fg[Default]   = '[0m';    fg[DefaultBold] = '[1m'
  fg[Black]     = '[0;30m'; fg[DarkGray]    = '[1;30m'
  fg[Blue]      = '[0;34m'; fg[LightBlue]   = '[1;34m'
  fg[Green]     = '[0;32m'; fg[LightGreen]  = '[1;32m'
  fg[Cyan]      = '[0;36m'; fg[LightCyan]   = '[1;36m'
  fg[Red]       = '[0;31m'; fg[LightRed]    = '[1;31m'
  fg[Purple]    = '[0;35m'; fg[LightPurple] = '[1;35m'
  fg[Brown]     = '[0;33m'; fg[Yellow]      = '[1;33m'
  fg[LightGray] = '[0;37m'; fg[White]       = '[1;37m'
  bg = .directory~new;      hi = .directory~new
  bg[Black]     = '[0;40m'; hi[Underlined]  = '[4m'
  bg[Blue]      = '[0;44m'; hi[Blinking]    = '[5m'
  bg[Green]     = '[0;42m'; hi[Inverted]    = '[7m'
  bg[Cyan]      = '[0;46m'; hi[Concealed]   = '[8m'
  bg[Red]       = '[0;41m'
  bg[Purple]    = '[0;45m'
  bg[Brown]     = '[0;43m'
  bg[LightGray] = '[0;47m'

usage: procedure
  trace normal

  if arg(1) = '-h',
   | arg(1) = '-?',
   | arg(1) = '--help'
  then
    do
      line = '/*|'
      say

      do l = 3 by 1 while line~left(3) = '/*|'
        line = sourceline(l)
        parse var line . '/*|' text '|*/' .
        .OUTPUT~lineout(text)
      end

      say
      exit 0
    end
return


# basado en código de Antonio Rodrigo dos Santos Silva (gracias):
# http://statusgear.freeforums.net/thread/17/basic-256-tic-tac-toe

global playerturn$
global endGame$
global space$
global player1Score$
global player2Score$
global invalidMove$
global tecla$
global keyQ$
global keyW$
global keyE$
global keyA$
global keyS$
global keyD$
global keyZ$
global keyX$
global keyC$
global keySpace$
global keyEsc$

keyQ$ = 81
keyW$ = 87
keyE$ = 69
keyA$ = 65
keyS$ = 83
keyD$ = 68
keyZ$ = 90
keyX$ = 88
keyC$ = 67
keySpace$ = 32
keyEsc$ = 16777216

dim space$(9)

subroutine clearGameVars()
  playerturn$ = 1
  invalidMove$ = 0
  endGame$ = 0
  tecla$ = 0

  for t = 0 to space$[?]-1
    space$[t] = 0
  next t
end subroutine

subroutine endGame()
  cls
  print "¡Hasta pronto!..."
  end
end subroutine

subroutine printBoard()
  print "          " + space$[0]+" | "+space$[1]+" | "+space$[2]
  print "          " + "— + — + —"
  print "          " + space$[3]+" | "+space$[4]+" | "+space$[5]
  print "          " + "— + — + —"
  print "          " + space$[6]+" | "+space$[7]+" | "+space$[8]
  print ""
end subroutine

subroutine changePlayer()
  if playerturn$ = 1 then
    playerturn$ = 2
  else
    playerturn$ = 1
  end if
end subroutine

subroutine endMatchWithWinner()
  cls
  call printPlayerScore()
  call printBoard()
  endGame$ = 1

  if playerturn$ = 1 then
    player1Score$ += 1
  else
    player2Score$ += 1
  end if

  print "¡Jugador " + playerturn$ + " gana!" + chr(10)
  print "Pulsa [SPACE] para jugar otra partida"
  print "Pulsa [ESC] para dejar de jugar"
  do
    tecla$ = key
    pause .01
    if tecla$ = keySpace$ then call gamePlay()
    if tecla$ = keyEsc$ then call endGame()
  until false
end subroutine

subroutine endMatchWithoutWinner()
  cls
  call printPlayerScore()
  call printBoard()
  endGame$ = 1

  print "                 Nadie ganó :(                  " + chr(10)
  print " Pulsa [SPACE] para comenzar o [ESC] para salir. "
  do
    tecla$ = key
    pause .01
    if tecla$ = keySpace$ then call gamePlay()
    if tecla$ = keyEsc$ then call endGame()
  until false
end subroutine

subroutine printPlayerScore()
  print "--------------------------------------------"
  print " Jugador #1: " + player1Score$ + " pts"
  print " Jugador #2: " + player2Score$ + " pts"
  print "--------------------------------------------" + chr(10)
end subroutine

subroutine printPlayerMessage()
  print "Jugador: " + playerturn$ + ", elige una casilla, por favor."
end subroutine

subroutine gamePlay()
  call clearGameVars()
  cls
  call printPlayerScore()
  call printBoard()
  call printPlayerMessage()
  while 0 = 0
    invalidMove$ = 0

    if endGame$ = 0 then
      do
        tecla$ = key
        pause .01
        validKeypressed$ = 0
        if tecla$ = keyQ$ or tecla$ = keyW$  or tecla$ = keyE$ or tecla$ = keyA$ or tecla$ = keyS$ or tecla$ = keyD$ or tecla$ = keyZ$ or tecla$ = keyX$ or tecla$ = keyC$ then validKeypressed$ = 1
      until validKeypressed$ = 1
    endif

    if tecla$ = keyQ$ then
      if space$[0] = 0 then
        space$[0] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyW$ then
      if space$[1] = 0 then
        space$[1] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyE$ then
      if space$[2] = 0 then
        space$[2] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyA$ then
      if space$[3] = 0 then
        space$[3] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyS$ then
      if space$[4] = 0 then
        space$[4] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyD$ then
      if space$[5] = 0 then
        space$[5] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyZ$ then
      if space$[6] = 0 then
        space$[6] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyX$ then
      if space$[7] = 0 then
        space$[7] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if tecla$ = keyC$ then
      if space$[8] = 0 then
        space$[8] = playerturn$
      else
        invalidMove$ = 1
      endif
    endif

    if invalidMove$ = 0 then
      tecla$ = 0

      if space$[0] = 1 and space$[1] = 1 and space$[2] = 1 then call endMatchWithWinner()
      if space$[3] = 1 and space$[4] = 1 and space$[5] = 1 then call endMatchWithWinner()
      if space$[6] = 1 and space$[7] = 1 and space$[8] = 1 then call endMatchWithWinner()
      if space$[0] = 1 and space$[3] = 1 and space$[6] = 1 then call endMatchWithWinner()
      if space$[1] = 1 and space$[4] = 1 and space$[7] = 1 then call endMatchWithWinner()
      if space$[2] = 1 and space$[5] = 1 and space$[8] = 1 then call endMatchWithWinner()
      if space$[0] = 1 and space$[4] = 1 and space$[8] = 1 then call endMatchWithWinner()
      if space$[2] = 1 and space$[4] = 1 and space$[6] = 1 then call endMatchWithWinner()
      if space$[0] = 2 and space$[1] = 2 and space$[2] = 2 then call endMatchWithWinner()
      if space$[3] = 2 and space$[4] = 2 and space$[5] = 2 then call endMatchWithWinner()
      if space$[6] = 2 and space$[7] = 2 and space$[8] = 2 then call endMatchWithWinner()
      if space$[0] = 2 and space$[3] = 2 and space$[6] = 2 then call endMatchWithWinner()
      if space$[1] = 2 and space$[4] = 2 and space$[7] = 2 then call endMatchWithWinner()
      if space$[2] = 2 and space$[5] = 2 and space$[8] = 2 then call endMatchWithWinner()
      if space$[0] = 2 and space$[4] = 2 and space$[8] = 2 then call endMatchWithWinner()
      if space$[2] = 2 and space$[4] = 2 and space$[6] = 2 then call endMatchWithWinner()

      if space$[0] <> 0 and space$[1] <> 0 and space$[2] <> 0 and space$[3] <> 0 and space$[4] <> 0 and space$[5] <> 0 and space$[6] <> 0 and space$[7] <> 0 and space$[8] <> 0 then call endMatchWithoutWinner()

      call changePlayer()
      cls
      call printPlayerScore()
      call printBoard()
      call printPlayerMessage()
    end if

  end while
end subroutine

subroutine gameMenu()
  cls
  call clearGameVars()

  player1Score$ = 0
  player2Score$ = 0

  print "================================================="
  print "|                  TIC-TAC-TOE                  |"
  print "=================================================" + chr(10)
  print "  Teclas para jugar:"
  print "---------------------"
  print "    | q | w | e |"
  print "    | a | s | d |"
  print "    | z | x | c |" + chr(10)
  print " Pulsa [SPACE] para comenzar o [ESC] para salir. "

  do
    tecla$ = key
    pause .01
    if tecla$ = keySpace$ then call gamePlay()
    if tecla$ = keyEsc$ then call endGame()
  until false
end subroutine

call gameMenu()
end


program Colorizer;

uses CRT;

const SampleText = 'Lorem ipsum dolor sit amet';

var fg, bg: 0..15;

begin
    ClrScr;
    for fg := 0 to 7 do begin
        bg := 15 - fg;
        TextBackground(bg);
        TextColor(fg);
        writeln(SampleText)
    end;
    TextBackground(White);
    TextColor(Black);
end.


my %colors = (
    red     => "\e[1;31m",
    green   => "\e[1;32m",
    yellow  => "\e[1;33m",
    blue    => "\e[1;34m",
    magenta => "\e[1;35m",
    cyan    => "\e[1;36m"
);
$clr = "\e[0m";

print "$colors{$_}$_ text $clr\n" for sort keys %colors;

# the Raku code also works
use feature 'say';
use Term::ANSIColor;

say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow');


@echo off
setlocal enabledelayedexpansion
:newgame
set a1=1
set a2=2
set a3=3
set a4=4
set a5=5
set a6=6
set a7=7
set a8=8
set a9=9
set ll=X
set /a zz=0
:display1
cls
echo Player: %ll%
echo %a7%_%a8%_%a9%
echo %a4%_%a5%_%a6%
echo %a1%_%a2%_%a3%
set /p myt=Where would you like to go (choose a number from 1-9 and press enter)?
if !a%myt%! equ %myt% (
set a%myt%=%ll%
goto check
)
goto display1
:check
set /a zz=%zz%+1
if %zz% geq 9 goto newgame
if %a7%+%a8%+%a9% equ %ll%+%ll%+%ll% goto win
if %a4%+%a5%+%a6% equ %ll%+%ll%+%ll% goto win
if %a1%+%a2%+%a3% equ %ll%+%ll%+%ll% goto win
if %a7%+%a5%+%a3% equ %ll%+%ll%+%ll% goto win
if %a1%+%a5%+%a9% equ %ll%+%ll%+%ll% goto win
if %a7%+%a4%+%a1% equ %ll%+%ll%+%ll% goto win
if %a8%+%a5%+%a2% equ %ll%+%ll%+%ll% goto win
if %a9%+%a6%+%a3% equ %ll%+%ll%+%ll% goto win
goto %ll%
:X
set ll=O
goto display1
:O
set ll=X
goto display1
:win
echo %ll% wins!
pause
goto newgame


--
-- demo\rosetta\Coloured_text.exw
-- ==============================
--
with javascript_semantics
text_color(GRAY)
bk_color(BLACK)
printf(1,"Background color#     00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\n")
printf(1,"                      -----------------------------------------------\n")
for foreground=0 to 15 do
    printf(1,"Foreground color# %02d  ",foreground)
    for background=0 to 15 do
        text_color(foreground)
        bk_color(background)
        printf(1,"%02d",foreground)
        text_color(GRAY)
        bk_color(BLACK)
        printf(1," ")
    end for
    printf(1,"\n")
end for
printf(1,"\n\npress enter to exit")
{} = wait_key()


(unless (member (sys "TERM") '("linux" "xterm" "xterm-color" "xterm-256color" "rxvt"))
   (quit "This application requires a colour terminal") )

# Coloured text
(for X '((1 . "Red") (4 . "Blue") (3 . "Yellow"))
   (call 'tput "setaf" (car X))
   (prinl (cdr X)) )

# Blinking
(out '(tput "-S")
   (prinl "setab 1^Jsetaf 3^Jblink") )
(prin "Flashing text")

(call 'tput 'sgr0)   # reset
(prinl)


foreach ($color in [enum]::GetValues([System.ConsoleColor])) {Write-Host "$color color." -ForegroundColor $color}


If OpenConsole()
  PrintN("Background color#     00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15")
  PrintN("                      -----------------------------------------------")
  Define Foreground, Background
  For Foreground = 0 To 15
    ConsoleColor(7, 0) ;grey foreground, black background
    Print("Foreground color# " + RSet(Str(Foreground), 2, "0") + "  ")
    For Background = 0 To 15
      ConsoleColor(Foreground, Background)
      Print(RSet(Str(Foreground), 2, "0"))
      ConsoleColor(7, 0) ;grey foreground, black background
      Print(" ")
    Next
    PrintN("")
  Next

  ConsoleColor(7, 0) ;grey foreground, black background
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


from colorama import init, Fore, Back, Style
init(autoreset=True)

print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW  + "Rosetta Code!"
print Fore.CYAN    + "Rosetta Code!"
print Fore.GREEN   + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"


#lang racket

;; Utility interfaces to the low-level command
(define (capability? cap) (system (~a "tput "cap" > /dev/null 2>&1")))
(define (tput . xs) (system (apply ~a 'tput " " (add-between xs " "))) (void))
(define (colorterm?) (and (capability? 'setaf) (capability? 'setab)))
(define color-map '([black 0] [red 1] [green 2] [yellow 3]
                    [blue 4] [magenta 5] [cyan 6] [white 7]))
(define (foreground color) (tput 'setaf (cadr (assq color color-map))))
(define (background color) (tput 'setab (cadr (assq color color-map))))
(define (reset) (tput 'sgr0) (void))

;; Demonstration of use
(if (colorterm?)
  (begin (foreground 'blue)
         (background 'yellow)
         (displayln "Color output")
         (reset))
  (displayln "Monochrome only"))
(if (capability? 'blink)
  (begin (tput 'blink)
         (displayln "Blinking output")
         (reset))
  (displayln "Steady only"))


use Terminal::ANSIColor;

say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow');


/*REXX program to display sixteen lines,  each of a different color.    */
parse arg !;  if !all()  then exit     /*exit if documentation specified*/
if \!dos  &  \!os2       then exit     /*if this isn't DOS,  then exit. */
if \!pcrexx              then exit     /*if this isn't PC/REXX,   exit. */

color.0  = 'black'                     /*┌─────────────────────────────┐*/
color.1  = 'dark blue'                 /*│ Normally, all programs issue│*/
color.2  = 'dark green'                /*│ the  (above) error messages │*/
color.3  = 'dark cyan/turquois'        /*│ through another REXX program│*/
color.4  = 'dark red'                  /*│ ($ERR)  which has more      │*/
color.5  = 'dark pink/magenta'         /*│ verbiage and  explanations, │*/
color.6  = 'dark yellow (orange)'      /*│ and issues the error text in│*/
color.7  = 'dark white'                /*│ red (if color is available).│*/
color.8  = 'brite black (grey/gray)'   /*└─────────────────────────────┘*/
color.9  = 'bright blue'
color.10 = 'bright green'
color.11 = 'bright cyan/turquois'
color.12 = 'bright red'
color.13 = 'bright pink/magenta'
color.14 = 'bright yellow'
color.15 = 'bright white'

         do j=0  to 15                 /*show all sixteen color codes.  */
         call scrwrite ,,'color code=['right(j,2)"]" color.j,,,j;   say
         end   /*j*/                   /*the  "SAY"  forces a  NEWLINE. */
exit                                   /*stick a fork in it, we're done.*/
/*══════════════════════════════════general 1-line subs═════════════════*/
!all:!!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal:if symbol('!CALL')\=="VAR" then !call=;return !call
!env:!env='ENVIRONMENT';if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM';if !os2 then !env='OS2'!env;!ebcdic=1=='f0'x;return
!fid:parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;call !sys;if !dos then do;_=lastpos('\',!fn);!fm=left(!fn,_);!fn=substr(!fn,_+1);parse var !fn !fn '.' !ft;end;return word(0 !fn !ft !fm,1+('0'arg(1)))
!rex:parse upper version !ver !vernum !verdate .;!brexx='BY'==!vernum;!kexx='KEXX'==!ver;!pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver;!r4='REXX-R4'==!ver;!regina='REXX-REGINA'==left(!ver,11);!roo='REXX-ROO'==!ver;call !env;return
!sys:!cms=!sys=='CMS';!os2=!sys=='OS2';!tso=!sys=='TSO'|!sys=='MVS';!vse=!sys=='VSE';!dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD';call !rex;return
!var:call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env))