Data update

This commit is contained in:
Ingy döt Net 2026-02-01 16:33:20 -08:00
parent 5150844a7d
commit 4bb20c9b71
7735 changed files with 38060 additions and 199180 deletions

View file

@ -1,124 +0,0 @@
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;

View file

@ -1,100 +0,0 @@
include std/console.e
include std/text.e
include std/search.e
include std/sequence.e
sequence board
sequence players = {"X","O"}
function DisplayBoard()
for i = 1 to 3 do
for j = 1 to 3 do
printf(1,"%s",board[i][j])
if j < 3 then
printf(1,"%s","|")
end if
end for
if i < 3 then
puts(1,"\n-----\n")
else
puts(1,"\n\n")
end if
end for
return 1
end function
function CheckWinner()
sequence temp = board
for a = 1 to 2 do
for i = 1 to 3 do
if equal({"X","X","X"},temp[i]) then
puts(1,"X wins\n\n")
return 1
elsif equal({"O","O","O"},temp[i]) then
puts(1,"O wins\n\n")
return 1
end if
end for
temp = columnize(board)
end for
if equal({"X","X","X"},{board[1][1],board[2][2],board[3][3]}) or
equal({"X","X","X"},{board[1][3],board[2][2],board[3][1]}) then
puts(1,"X wins\n")
return 1
elsif equal({"O","O","O"},{board[1][1],board[2][2],board[3][3]}) or
equal({"O","O","O"},{board[1][3],board[2][2],board[3][1]}) then
puts(1,"O wins\n")
return 1
end if
if moves = 9 then
puts(1,"Draw\n\n")
return 1
end if
return 0
end function
integer turn, row, column, moves
sequence replay
while 1 do
board = repeat(repeat(" ",3),3)
DisplayBoard()
turn = rand(2)
moves = 0
while 1 do
while 1 do
printf(1,"%s's turn\n",players[turn])
row = prompt_number("Enter row: ",{})
column = prompt_number("Enter column: ",{})
if match(board[row][column]," ") then
board[row][column] = players[turn]
moves += 1
exit
else
puts(1,"Space already taken - pick again\n")
end if
end while
DisplayBoard()
if CheckWinner() then
exit
end if
if turn = 1 then
turn = 2
else
turn = 1
end if
end while
replay = lower(prompt_string("Play again (y/n)?\n\n"))
if match(replay,"n") then
exit
end if
end while

View file

@ -1,6 +1,6 @@
'`c t b'=. (?@#{])@([:I.0=b)`{.`}. NB. cpu's move; extract turn/board
v=. (0=]{b@[) :: 0 *. ]e.i.@9 NB. posn (y) valid and open on board (x)?
y=. ($:@[ echo@'no')^:(-.@v) _1+0".1!:1@1@echo@'move (1-9):' NB. your move
i=. (0=]{b@[) ::0 *: ]e.i.@9 NB. invalid posn? (x: state; y: posn)
y=. [ ($:@[ echo@'no')^:i _1+0".1!:1@1@echo@'move (1-9):' NB. your move
m=. (-,])@t [`(0,1+c`y@.(1=t)@])} ] NB. apply current player's move to board
o=. 'tie'"_`(' wins',~ {&'.XO'@-@t)@.w NB. print game outcome
d=. [ ''echo@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$b) NB. display the board

View file

@ -1,7 +1,7 @@
'`c t b e x'=.(?@#{])@([:I.0=b)`{.`}.`echo`(1:Z:1:) NB. cpu's move; turn; board; print; exit
'`wm tm'=. (''e@, {&'.XO'@-@t ,' wins'"_)`([:e LF&,@'tie') NB. print win/tie message
i=. (0=]{b@[) ::0 -.@*. ]e.i.@9 NB. invalid posn? (x: state; y: posn)
y=. ($:@[ e@'no')^:i _1+0".@(1!:1@1)@e@'move (1-9):' NB. your move
i=. (0=]{b@[) ::0 *: ]e.i.@9 NB. invalid posn? (x: state; y: posn)
y=. ($:@[ e@'no')^:i _1+0".1!:1@1@e@'move (1-9):' NB. your move
m=. -@t , c`y@.(1=t) t@]`[`(b@])} ] NB. apply current player's move to board
d=. ''e@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$b) NB. display the board
w=. 3 +./@:= |@(+/"1)@(],|:,(<@0 1|:|.),:<@0 1|:])@(3 3$b) NB. test whether game has been won

View file

@ -2,7 +2,7 @@
Until=. {{u^:(-.@:v)^:_.}} NB. apply u until v is true
full=. {{-. 0 e. board y}} NB. board is full (tie game)
open=. {{0 = x { board y}} NB. given pos is free on board
invalid=. {{-. (y open ::0 x) *. y e.i.9}} NB. test for invalid position
invalid=. {{(y open ::0 x) *: y e.i.9}} NB. test for invalid position
cpu=. {{(?#o) { o=.I.0=board y}} NB. cpu's move
pos=. {{cpu`you@.(1 = turn y)y}} NB. get cpu's or user's move
you=. {{y {{you x[echo'no'}}^:(y invalid p) p=.<:0".(1!:1)1[echo'move (1-9):'}} NB. your move

View file

@ -1,102 +0,0 @@
const winningpositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
[2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]]
function haswon(brd, xoro)
marked = findall(x -> x == xoro, brd)
for pos in winningpositions
if length(pos) <= length(marked) && pos == sort(marked)[1:3]
return true
end
end
false
end
function readcharwithprompt(prompt, expected)
ret = '*'
while !(ret in expected)
print("\n", prompt, " -> ")
ret = lowercase(chomp(readline()))[1]
end
ret
end
availablemoves(brd) = findall(x -> x == ' ', brd)
cornersopen(brd) = [x for x in [1, 3, 7, 9] if brd[x] == ' ']
int2char(x) = Char(x + UInt8('0'))
char2int(x) = UInt8(x) - UInt8('0')
getyn(query) = readcharwithprompt(query, ['y', 'n'])
gettheirmove(brd) = char2int(readcharwithprompt("Your move(1-9)", int2char.(availablemoves(brd))))
function findwin(brd, xoro)
tmpbrd = deepcopy(brd)
for mv in availablemoves(tmpbrd)
tmpbrd[mv] = xoro
if haswon(tmpbrd, xoro)
return mv
end
tmpbrd[mv] = ' '
end
return nothing
end
function choosemove(brd, mychar, theirchar)
if all(x -> x == ' ', brd)
brd[rand(cornersopen(brd))] = mychar # corner trap if starting game
elseif availablemoves(brd) == [] # no more moves
println("Game is over. It was a draw.")
exit(0)
elseif (x = findwin(brd, mychar)) != nothing || (x = findwin(brd, theirchar)) != nothing
brd[x] = mychar # win if possible, block their win otherwise if their win is possible
elseif brd[5] == ' '
brd[5] = mychar # take center if open and not doing corner trap
elseif (corners = cornersopen(brd)) != []
brd[rand(corners)] = mychar # choose a corner over a side middle move
else
brd[rand(availablemoves(brd))] = mychar # random otherwise
end
end
function display(brd)
println("+-----------+")
println("| ", brd[1], " | ", brd[2], " | ", brd[3], " |")
println("| ", brd[4], " | ", brd[5], " | ", brd[6], " |")
println("| ", brd[7], " | ", brd[8], " | ", brd[9], " |")
println("+-----------+")
end
function tictactoe()
board = fill(' ', 9)
println("Board move grid:\n 1 2 3\n 4 5 6\n 7 8 9")
yn = getyn("Would you like to move first (y/n)?")
if yn == 'y'
mychar = 'O'
theirchar = 'X'
board[gettheirmove(board)] = theirchar
else
mychar = 'X'
theirchar = 'O'
end
while true
choosemove(board, mychar, theirchar)
println("Computer has moved.")
display(board)
if haswon(board, mychar)
println("Game over. Computer wins!")
exit(0)
elseif availablemoves(board) == []
break
end
board[gettheirmove(board)] = theirchar
println("Player has moved.")
display(board)
if haswon(board, theirchar)
println("Game over. Player wins!")
exit(0)
elseif availablemoves(board) == []
break
end
end
println("Game over. It was a draw.")
end
tictactoe()

View file

@ -1,8 +1,7 @@
b::2 9#0 / the board
WINMASKS::((9#2)\)'7 56 448 73 146 292 273 84 / winning trios
fin:{`0:x," won";`exit 0}
b::2 9#0; WINMASKS::((9#2)\)'7 56 448 73 146 292 273 84 / the board and winning trios
{1}{({`1:"MOVE: ";$[(|/b)m:(`I$-1_1:`)-1;o`0:"NO";b[0;m]::1]} / your move
{b[1;(|/b)?0]::1})[x;0] / cpu's move
x{`0:" "/'`c$3 3#|/"XO*"*b,,~|/b}/0 / show board after cpu moves
$[+/3=0^WINMASKS(+/&)\:b x;fin "XO*" x;511=2/|/b;fin"the cat"] / test win
{b[1;*1?&~|/b]::1})[x;] / cpu's move
x{`0:" "/'`c$3 3#|/"XO*"*b,,~|/b}/0 / show board after each move
w:|/3=0^WINMASKS(+/&)\:b x;t:511=2/|/b / test win and tie conditions
$[w|t;{`0:x," won";`exit 0}("XO"x;"the cat")t;] / when game is over, exit and print winner
~x}/1 / now it's other player's turn

View file

@ -1,190 +0,0 @@
#!/usr/bin/env luajit
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
local board="123456789" -- board
local pval={1, -1} -- player 1=1 2=-1 for negamax
local pnum={} for k,v in ipairs(pval) do pnum[v]=k end
local symbol={'X','O'} -- default symbols X and O
local isymbol={} for k,v in pairs(symbol) do isymbol[v]=pval[k] end
math.randomseed(os.time()^5*os.clock()) -- time-seed the random gen
local random=math.random
-- usage of ffi variables give 20% speed
ffi.cdef[[
typedef struct{
char value;
char flag;
int depth;
}cData;
]]
-- draw the "board" in the way the numpad is organized
local function draw(board)
for i=7,1,-3 do
print(board:sub(i,i+2))
end
end
-- pattern for win situations
local check={"(.)...%1...%1","..(.).%1.%1..",
"(.)%1%1......","...(.)%1%1...","......(.)%1%1",
"(.)..%1..%1..",".(.)..%1..%1.","..(.)..%1..%1",
}
-- calculate a win situation for which player or draw
local function win(b)
local sub
for i=1,#check do
sub=b:match(check[i])
if sub then break end
end
sub=isymbol[sub]
return sub or 0
end
-- input only validate moves of not yet filled positions
local function input(b,player)
char=symbol[pnum[player]]
local inp
repeat
printf("Player %d (\"%s\") move: ",pnum[player],char)
inp=tonumber(io.read()) or 0
until inp>=1 and inp<=9 and b:find(inp)
b=b:gsub(inp,char)
return b,inp
end
-- ask how many human or AI players
local function playerselect()
local ai={}
local yn
for i=1,2 do
repeat
printf("Player %d human (Y/n)? ", i) yn=io.read():lower()
until yn:match("[yn]") or yn==''
if yn=='n' then
ai[pval[i]]=true
printf("Player %d is AI\n", i)
else
printf("Player %d is human\n", i)
end
end
return ai
end
local function endgame()
repeat
printf("\nEnd game? (y/n)? ", i) yn=io.read():lower()
until yn:match("[yn]")
if yn=='n' then
return false
else
printf("\nGOOD BYE PROFESSOR FALKEN.\n\nA STRANGE GAME.\nTHE ONLY WINNING MOVE IS\nNOT TO PLAY.\n\nHOW ABOUT A NICE GAME OF CHESS?\n")
return true
end
end
-- AI Routine
local function shuffle(t)
for i=#t,1,-1 do
local rnd=random(i)
t[i], t[rnd] = t[rnd], t[i]
end
return t
end
-- move generator
local function genmove(node, color)
return coroutine.wrap(function()
local moves={}
for m in node:gmatch("%d") do
moves[#moves+1]=m
end
shuffle(moves) -- to make it more interesting
for _,m in ipairs(moves) do
local child=node:gsub(m,symbol[pnum[color]])
coroutine.yield(child, m)
end
end)
end
--[[
Negamax with alpha-beta pruning and table caching
]]
local cache={}
local best, aimove, tDepth
local LOWERB,EXACT,UPPERB=-1,0,1 -- has somebody an idea how to make them real constants?
local function negamax(node, depth, color, α, β)
color=color or 1
α=α or -math.huge
β=β or math.huge
-- check for cached node
local αOrg=α
local cData=cache[node]
if cData and cData.depth>=depth and depth~=tDepth then
if cData.flag==EXACT then
return cData.value
elseif cData.flag==LOWERB then
α=math.max(α,cData.value)
elseif cData.flag==UPPERB then
β=math.min(β,cData.value)
end
if α>=β then
return cData.value
end
end
local winner=win(node)
if depth==0 or winner~=0 then
return winner*color
end
local value=-math.huge
for child,move in genmove(node, color) do
value=math.max(value, -negamax(child, depth-1, -color, -β, -α))
if value>α then
α=value
if depth==tDepth then
best=child
aimove=move
end
end
if α>=β then break end
end
-- cache known data
--cData={} -- if you want Lua tables instead of ffi you can switch the two lines here, costs 20% speed
cData=ffi.new("cData")
cData.value=value
if value<=αOrg then
cData.flag=UPPERB
elseif value>=β then
cData.flag=LOWERB
else
cData.flag=EXACT
end
cData.depth=depth
cache[node]=cData
return α
end
-- MAIN
do
local winner,value
local score={[-1]=0, [0]=0, [1]=0}
repeat
print("\n TIC-TAC-TOE\n")
local aiplayer=playerselect()
local player=1
board="123456789"
for i=1,#board do
draw(board)
tDepth=10-i
if aiplayer[player] then
negamax(board, tDepth, player, -math.huge, math.huge)
board=best
printf("AI %d moves %s\n", pnum[player], aimove)
else
board=input(board,player)
end
winner=win(board)
if winner~=0 then break end
player=-player
end
score[winner]=score[winner]+1
if winner and winner~=0 then
printf("*** Player %d (%s) has won\n", pnum[winner], symbol[pnum[winner]])
else
printf("*** No winner\n")
end
printf("Score Player 1: %d Player 2: %d Draw: %d\n",score[1],score[-1],score[0])
draw(board)
until endgame()
end