Tic-tac-toe: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Tailspin}}: typed array indices)
m (syntax highlighting fixup automation)
Line 26:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">UInt32 seed = 0
F nonrandom_choice(lst)
:seed = 1664525 * :seed + 1013904223
Line 111:
L.break
L.was_no_break
print("\nA draw")</langsyntaxhighlight>
 
{{out}}
Line 158:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">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
Line 281:
Ada.Text_IO.Put_Line("The winner is: " & Find_Winner(The_Board));
end if;
end Tic_Tac_Toe;</langsyntaxhighlight>
 
{{out}}
Line 396:
=={{header|ALGOL W}}==
The user can play O, X, both or neither. O goes first whether user or computer controlled.
<langsyntaxhighlight lang="algolw">begin
 
string(10) board;
Line 575:
do begin end
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 621:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">property OMask : missing value
property XMask : missing value
property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448}
Line 733:
end repeat
return theResult as integer
end BWAND</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
This program uses a Gui with 9 buttons. Clicking on one will place an X there, disable the button, and cause the program to go somewhere.
It plays logically, trying to win, trying to block, or playing randomly in that order.
<langsyntaxhighlight AutoHotkeylang="autohotkey">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,
Line 844:
GuiClose:
ExitApp
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TIC-TAC-TOE.AWK
BEGIN {
Line 961:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
</lang>
 
=={{header|Bash}}==
Line 983:
#encourage use of bash for more interesting tasks.
 
<langsyntaxhighlight lang="bash">
#!/bin/bash
declare -a B=( e e e e e e e e e ) # Board
Line 1,048:
show; [[ RANDOM%2 -eq 0 ]] && { turn O X; exit $?; } || turn X O
 
</syntaxhighlight>
</lang>
{{out}} (nice ANSI formatting is not shown)
<pre>
Line 1,091:
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
# basado en código de Antonio Rodrigo dos Santos Silva (gracias):
# http://statusgear.freeforums.net/thread/17/basic-256-tic-tac-toe
Line 1,363:
call gameMenu()
end
</syntaxhighlight>
</lang>
 
 
===Microsoft Small Basic===
This game has a simple AI.
<langsyntaxhighlight lang="smallbasic">place1 = 1
place2 = 2
place3 = 3
Line 1,511:
Else
Goto reset
EndIf</langsyntaxhighlight>
 
===ZX Spectrum Basic===
<langsyntaxhighlight lang="zxbasic">
</syntaxhighlight>
</lang>
 
=={{header|Batch File}}==
This is just a game between two human players.
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
:newgame
Line 1,567:
pause
goto newgame
</syntaxhighlight>
</lang>
===Advanced===
This code makes a version of Tic Tac Toe with more features:
<langsyntaxhighlight lang="dos">@ECHO OFF
:BEGIN
REM Skill level
Line 1,890:
set t7=
set t8=
set t9=</langsyntaxhighlight>
 
=={{header|Befunge}}==
Line 1,897:
Plays reasonably well, but not perfectly, so can be beaten.
 
<langsyntaxhighlight Befungelang="befunge">v123456789 --- >9 >48*,:55+\-0g,1v
>9>066+0p076+0p^ ^,," |"_v#%3:- <
:,,0537051v>:#,_$#^5#,5#+<>:#v_55+
Line 1,911:
>"yM">:#,_$ :. 1234+++, 789*+ \0^<
"a s't"98:*+>:#,_$@>365*+"ward"48*
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,957:
=={{header|C}}==
Opening alternates between human and computer. Computer never loses.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 2,059:
while (1) printf("%s", game(first = !first));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
Line 2,065:
It tries to show a number of C# code features while still keeping each function small and understandable.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 2,310:
}
 
}</langsyntaxhighlight>
 
{{out}}
Line 2,356:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 2,536:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}} Computer plays 'X' and human plays 'O'
<pre>
Line 2,549:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun generate-board ()
(loop repeat 9 collect nil))
Line 2,642:
(format t "The winner is ~a!" (find-winner board))
(format t "It's a tie.")))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,671:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.conv, std.random,
std.ascii, std.array, std.range, std.math;
 
Line 2,785:
break;
}
}</langsyntaxhighlight>
{{out}}
<pre>Tic-tac-toe game player.
Line 2,836:
[https://easylang.online/apps/tictactoe.html Run it]
 
<syntaxhighlight lang="text">len f[] 9
state = 0
textsize 14
Line 2,988:
.
.
call init</langsyntaxhighlight>
 
=={{header|Erlang}}==
The program will randomly chose if the computer ("X") or the user ("O") starts. The computer look ahead is only one level. Perhaps the computer might lose?
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(tic_tac_toe).
 
Line 3,098:
turn_next_move_ok( true, _Prompt, _Ns, N ) -> N;
turn_next_move_ok( false, Prompt, Ns, _N ) -> turn_next_move( Prompt, Ns ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,384:
{{works with|OpenEuphoria}}
No computer AI
<langsyntaxhighlight lang="euphoria">
include std/console.e
include std/text.e
Line 3,485:
 
end while
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,583:
A purely-functional solution with a naive (but perfect) computer player implementation. The first move is played randomly by the computer.
 
<langsyntaxhighlight lang="fsharp">type Brick =
| Empty
| Computer
Line 3,715:
let b = set Computer emptyBoard (choose (freeSpace emptyBoard))
printBoard b
gameLoop b User</langsyntaxhighlight>
 
Example game:
Line 3,794:
Game between two humans.
 
<langsyntaxhighlight lang="forth">create board 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
 
\ board: 0=empty, 1=player X, 2=player O
Line 3,847:
 
game
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,906:
=={{header|Fortran}}==
Objective: write program in less than 100 lines, not using semicolons. Computer never loses, but plays as random as possible. Player gets first move of first game. Afterwards, first move alternates between computer and player.
<langsyntaxhighlight lang="fortran">
! This is a fortran95 implementation of the game of tic-tac-toe.
! - Objective was to use less than 100 lines.
Line 4,006:
enddo mainloop
end program
</syntaxhighlight>
</lang>
=={{header|FreeBASIC}}==
===graphics mode===
<langsyntaxhighlight lang="freebasic">
 
'About 400 lines of code, but it is a graphical (GUI ish) i.e. mouse driven.
Line 4,434:
End
End Sub
</syntaxhighlight>
</lang>
 
 
===text mode===
<langsyntaxhighlight lang="freebasic">
Screenres 320,240,32
 
Line 4,680:
Loop Until Multikey(&H01)
End
</syntaxhighlight>
</lang>
 
 
=={{header|Go}}==
Intermediate, like Python's "Better skilled player." Computer wins and blocks where it can, but otherwise plays randomly. Plays multiple games and keeps score. Player gets first move of first game. Afterwards, loser gets to go first, or after cat games, first move alternates.
<langsyntaxhighlight lang="go">package main
 
import (
Line 4,844:
{0, 4, 8}, // diagonals
{2, 4, 6},
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Simplified version of Tic Tac Toe for player vs. player (no AI computer-controlled option).
<langsyntaxhighlight Groovylang="groovy">class Main {
 
def input = new Scanner(System.in)
Line 4,981:
return builder.toString();
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Computer player has three strategies: 1. Try to block the opponent first, 2. Try to guess a good position for the next move, 3. Place a piece randomly.
There are lots of comments throughout the code.
<syntaxhighlight lang="haskell">
<lang Haskell>
module Main where
 
Line 5,207:
putStrLn "3 : player X is human and player O is computer"
putStrLn "Player X always begins."
</syntaxhighlight>
</lang>
{{out}}
Player X is computer, O is human.
Line 5,336:
The following works in both Icon and Unicon. The computer plays randomly against a human player, with legal moves enforced and wins/draws notified.
 
<syntaxhighlight lang="icon">
<lang Icon>
# Play TicTacToe
 
Line 5,449:
play_game ()
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
To subsequent j poster: replacing this entry is fine by me.
<syntaxhighlight lang="j">
<lang J>
Note 'ttt adjudicates or plays'
 
Line 5,548:
nor=: 8 b.
infix_pairs_agree=: 2&(=/\)
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
This version works in the terminal itself, and uses the numpad for data entry. The computer is unbeatable, but some lines can be removed to avoid that. There's also an override that thrown in, just for fun.
<langsyntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.InputStreamReader;
Line 5,877:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 5,927:
 
This version uses javax.swing.
<langsyntaxhighlight lang="java">import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Line 6,090:
}
}
</syntaxhighlight>
</lang>
 
Graphical Java Example
<langsyntaxhighlight lang="java">
import javax.swing.*;
import java.awt.event.*;
Line 6,568:
}
}
</syntaxhighlight>
</lang>
The following program may be executed for a player-against-player game.
<langsyntaxhighlight lang="java">
import javax.swing.*;
import javax.swing.border.Border;
Line 6,851:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Javascript}}==
HTML5 Canvas implementation. Should play perfectly or near-perfectly.
<syntaxhighlight lang="javascript">
<lang Javascript>
<!DOCTYPE html>
 
Line 7,292:
 
</html>
</syntaxhighlight>
</lang>
 
 
Line 7,300:
Human is X and goes first.
 
<syntaxhighlight lang="javascript">
<lang Javascript>
// Board
const topLeft = 1;
Line 7,485:
}
});
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,512:
=={{header|Julia}}==
One move look-ahead algorithm. Computer plays to win or at least draw.
<langsyntaxhighlight lang="julia">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]]
 
Line 7,614:
 
tictactoe()
</langsyntaxhighlight> {{output}} <pre>
Board move grid:
1 2 3
Line 7,661:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import java.util.Random
Line 7,767:
println()
}
}</langsyntaxhighlight>
 
Sample game:
Line 7,827:
 
As image uploads has been disabled, a live version can be viewed at: [http://jono.guthrie.net.nz/rosetta/Tic-tac-toe.lasso http://jono.guthrie.net.nz/rosetta/Tic-tac-toe.lasso]
<syntaxhighlight lang="lasso">[
<lang Lasso>[
session_start('user')
session_addvar('user', 'matrix')
Line 7,921:
$matrix = array('-','-','-','-','-','-','-','-','-')
$turn = 'x'
}]</langsyntaxhighlight>
 
=={{header|Lingo}}==
Line 7,927:
Screenshot of application window: http://valentin.dasdeck.com/lingo/tic-tac-toe/tic-tac-toe-lingo.png<br />
"Human" cannot win this game.
<langsyntaxhighlight Lingolang="lingo">global $ -- object representing simple framework
global gBoard -- current board image
global gBoardTemplate -- empty board image
Line 8,163:
on sum (aLine)
return aLine[1]+aLine[2]+aLine[3]
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Version for LuaJIT with or without ffi, negamax algorithm with alpha-beta pruning and caching of results. Human can't win.
<langsyntaxhighlight Lualang="lua">#!/usr/bin/env luajit
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
Line 8,356:
draw(board)
until endgame()
end</langsyntaxhighlight>
 
{{out}}
Line 8,421:
=={{header|M2000 Interpreter}}==
Computer May loose;
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Tic.Tac.Toe {
Dim Board$(1 to 3, 1 to 3)=" "
Line 8,533:
}
Tic.Tac.Toe
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 8,607:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">DynamicModule[{board = ConstantArray[0, {3, 3}], text = "Playing...",
first, rows =
Join[#, Transpose@#, {Diagonal@#, Diagonal@Reverse@#}] &},
Line 8,642:
text = "Draw."]]]]], {i, 1, 3}, {j, 1, 3}], Thickness[.01],
Line[{{{1, 0}, {1, 3}}, {{2, 0}, {2, 3}}, {{0, 1}, {3, 1}}, {{0,
2}, {3, 2}}}]}], Dynamic@text}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Allows for choice between any combination of human or computer players. Computer players are intelligent, but not perfect. It implements the "rules" used by the Newell and Simon's 1972 tic-tac-toe program (as explained by Wikipedia), but this implementation does not factor in the move before the move causing the fork (either for creation or prevention).
<langsyntaxhighlight MATLABlang="matlab">function TicTacToe
% Set up the board (one for each player)
Line 8,869:
% boards - 3x3x2 logical representation of all players' pieces
draw = all(all(boards(:, :, 1) | boards(:, :, 2)));
end</langsyntaxhighlight>
{{out}}
Computer goes first and plays perfectly:
Line 8,991:
 
=={{header|mIRC Scripting Language}}==
<langsyntaxhighlight lang="mirc">alias ttt {
if ($2 isin %ttt) || (!%ttt) {
var %ttt~ = $remove($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X,O)
Line 9,021:
echo -ag � $+ $iif($7 isnum,$chr(32),$7) $+ $chr(124) $+ $iif($8 isnum,$chr(32),$8) $+ $chr(124) $+ $iif($9 isnum, ,$9)
}
}</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<langsyntaxhighlight lang="mk-61">9 С/П ПП 28 пи * cos x<0 16 ИП2
ПП 28 1 - БП 51 ИП7 ПП 28 ИП7
ПП 28 КИП2 ИП2 ВП 4 4 С/П 1 -
x=0 33 8 П2 С/П П7 ИП2 4 - x#0
43 x<0 45 8 + П8 ИП7 - x#0 55
ИП8 ВП 6 6 С/П ИП2 В/О</langsyntaxhighlight>
 
Cell numbering 1 to 9; starts from the upper left cell, then clockwise in a spiral. The first move is a calculator. Result: 44 - draw, 66 - victory of the calculator.
Line 9,037:
This is a translation of the second version with the better AI, but with some differences. For instance, we have chosen to display the board in the same way as the first version. All procedures have a parameter "board" rather accessing a global variable. We use also base 1-indexing for the board. Etc.
 
<langsyntaxhighlight Nimlang="nim">import options, random, sequtils, strutils
 
type
Line 9,140:
echo "Input the index of where you wish to place your mark at your turn."
randomize()
play()</langsyntaxhighlight>
 
{{out}}
Line 9,203:
=={{header|Objeck}}==
Tic-tac-toe game using Minimax algorithm.
<langsyntaxhighlight lang="objeck">class TicTacToe {
@board : Char[,];
@cpu_opening : Bool;
Line 9,574:
"===========\n"->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 9,582:
I would expect this version should compile with most Pascal variants including Delphi, but YMMR.
 
<langsyntaxhighlight Pascallang="pascal">program tic(Input, Output);
 
type
Line 9,745:
player := swapPlayer(player);
end
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 9,756:
the computer. Anyone who can identify the mistake, is welcome to fix it.
 
<langsyntaxhighlight Perllang="perl">use warnings;
use strict;
 
Line 9,855:
$whose_turn = !$whose_turn;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 9,913:
</pre>
===Alternate with GUI===
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
 
use strict;
Line 9,984:
(sort {$a->[0] <=> $b->[0]} shuffle @moves)[ -($who eq 'X') ]
};
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 9,991:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Tic_tac_toe.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Tic_tac_toe.exw
Line 10,229:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
Line 10,235:
NOTE: While PHP can considered a super-set of HTML/JS, usage has been kept to a minimum to focus on the more specific PHP parts.
 
<syntaxhighlight lang="php">
<lang PHP>
<?php
const BOARD_NUM = 9;
Line 10,293:
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
This solution doesn't bother about the game logic, but simply uses the alpha-beta-pruning 'game' function in the "simul" library.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l") # for 'game' function
 
(de display ()
Line 10,363:
((find3 T) "Congratulation, you won!")
((not (myMove)) "No moves")
((find3 0) "Sorry, you lost!") ) )</langsyntaxhighlight>
{{out}}
<pre>: (main)
Line 10,397:
Uses a minimax algorithm with no Alpha-beta pruning, as the max depth of the recursion is 8. Computer never loses.<br>
A GUI interface written in XPCE is given.
<langsyntaxhighlight Prologlang="prolog">:- use_module('min-max.pl').
 
:-dynamic box/2.
Line 10,606:
computer(o).
 
</syntaxhighlight>
</lang>
Module min-max.pl defines minimax algorithm.
<langsyntaxhighlight lang="prolog">:- module('min-max.pl', [minimax/5]).
 
% minimax(Player, Deep, MaxDeep, B, V-B)
Line 10,635:
lie(TTT, V-_, V-TTT).
 
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
The computer enforces the rules but plays a random game.
<langsyntaxhighlight lang="python">
'''
Tic-tac-toe game player.
Line 10,714:
else:
print('\nA draw')
</syntaxhighlight>
</lang>
 
'''Sample Game'''
Line 10,757:
In this version, The computer player will first complete a winning line of its own if it can, otherwise block a winning line of its opponent if they have two in a row, or then choose a random move.
 
<langsyntaxhighlight lang="python">
'''
Tic-tac-toe game player.
Line 10,848:
break
else:
print('\nA draw')</langsyntaxhighlight>
 
{{out}}
Line 10,933:
This program simulates a game of Tic-Tac-Toe inside of an interactive window. It includes three player modes, which are a two-player game, a human versus random AI, or human versus maximized AI. This implementation belongs to "X", and can also be found here.
 
<syntaxhighlight lang="r">
<lang R>
rm(list=ls())
library(RColorBrewer)
Line 11,347:
#start("name", "mode" = 0 - 2, type = 0,1)
 
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 11,368:
 
The <tt>minimax.rkt</tt> module:
<langsyntaxhighlight lang="racket">
#lang lazy
(provide minimax)
Line 11,389:
(next (cdr x)
(min β (minimax (car x) α β (not max-player))))))]))))
</langsyntaxhighlight>
 
The <tt>game.rkt</tt> module:
 
<langsyntaxhighlight lang="racket">
#lang lazy
(require racket/class
Line 11,503:
(set-field! opponent p2 p1)
(send p1 your-turn initial-state))
</syntaxhighlight>
</lang>
 
The <tt>tick-tack.rkt</tt> module:
<langsyntaxhighlight lang="racket">#lang racket
 
(require "game.rkt"
Line 11,597:
(new (interactive-player o%) [name "Dummy"] [look-ahead 0]))
 
</syntaxhighlight>
</lang>
 
Sample games:
Line 11,724:
As an example of another zero-sum game consider the classical [http://en.wikipedia.org/wiki/Nim Nim] game:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 11,764:
(define player-B
(new (interactive-player second%) [name "B"] [look-ahead 4]))
</syntaxhighlight>
</lang>
 
Computer plays with the computer:
Line 11,800:
The computer plays a random game.
 
<syntaxhighlight lang="raku" perl6line>my @board = 1..9;
my @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8],
[0,4,8], [6,4,2];
Line 11,846:
} else {
say "How boring, a draw!";
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 11,865:
<br>A fair amount of code was dedicated to error detection &nbsp; and &nbsp; the displaying of error messages, &nbsp; and
<br>also the presentation of the tic─tac─toe game boards (grids).
<langsyntaxhighlight lang="rexx">/*REXX program plays (with a human) the tic─tac─toe game on an NxN grid. */
$= copies('─', 9) /*eyecatcher for error messages, prompt*/
oops = $ '***error*** ' /*literal for when an error happens. */
Line 12,006:
 
if _==N | (_>=w & ec\=='') then return 1==1 /*a winner has been determined.*/
return 0==1 /*no winner " " " */</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''LINESIZE''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console); &nbsp; this is used to determine the amount of padding for a centered display of the two grids.
 
Line 12,210:
 
The tecTacToe.ring is provided [https://github.com/AbdelrahmanGIT/RingSamples/blob/master/src/TecTacToe.ring here]
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 12,340:
next
if tie=true return 3 ok return 0
</syntaxhighlight>
</lang>
 
{{out}}
Line 12,352:
This implementation stores the board as a one-dimensional array and hardcodes all possible straight lines in <code>LINES</code>, rather than storing the board as a two-dimensional matrix and identifying straight lines dynamically.
 
<langsyntaxhighlight lang="ruby">module TicTacToe
LINES = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
Line 12,537:
puts
players_with_human = [HumanPlayer, ComputerPlayer].shuffle
Game.new(*players_with_human).play</langsyntaxhighlight>
 
{{out}}
Line 12,606:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' ---------------------------
' TIC TAC TOE
' ---------------------------
Line 12,707:
input "Play again (y/n)";p$
if upper$(p$) = "Y" then goto [newGame]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use GameState::{ComputerWin, Draw, PlayerWin, Playing};
 
Line 12,831:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 12,863:
Computer vs. human. Human starts. Computer plays 'O' and human plays 'X'.
Computer moves are legal, but random.
<langsyntaxhighlight lang="scala">package object tictactoe {
val Human = 'X'
val Computer = 'O'
Line 12,944:
}
 
}</langsyntaxhighlight>
 
{{out}}(human is always first)
Line 12,979:
Can be a game of human v. human, human v. machine, or machine v. machine. Machine moves have a hierarchy: firstly, it looks for a winning move; secondly, it looks for a way to block the opponent's victory; lastly, it makes a random move.
 
<syntaxhighlight lang="text">function [] = startGame()
//Board size and marks
N = 3;
Line 13,357:
endfunction
 
startGame()</langsyntaxhighlight>
 
=={{header|SQL}}==
Basic playable TicTacToe in SQLite using only the sqlite3 CLI.
The CLI wasn't really designed for this, making the interactivity a little bit clunky. However, some of the higher-level constructs in SQL allow for some intriguingly elegant game logic.
<syntaxhighlight lang="sql">
<lang SQL>
--Setup
drop table if exists board;
Line 13,449:
.print "->update board set p = 'X' where rowid = ?; select * from ui; select * from msg;"'
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 13,481:
=={{header|Swift}}==
Some Basic AI for obvious losing and winning conditions
<syntaxhighlight lang="swift">
<lang Swift>
import Darwin
 
Line 13,688:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 13,792:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
processor Tic-Tac-Toe
@: [position´1..position´9];
Line 13,850:
end play
 
$play -> !VOID</langsyntaxhighlight>
{{out}}
<pre>
Line 13,907:
=={{header|Tcl}}==
{{trans|Python}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# This code splits the players from the core game engine
Line 14,027:
# Assemble the pieces
set ttt [TicTacToe new HumanPlayer RandomRoboPlayer]
$ttt game</langsyntaxhighlight>
Sample game:
<pre>
Line 14,079:
 
=={{Header|Tiny BASIC}}==
<langsyntaxhighlight Tinylang="tiny BASICbasic"> REM Tic-tac-toe for Tiny BASIC
REM
REM Released as public domain by Damian Gareth Walker, 2019
Line 14,279:
IF M=8 THEN LET Y=P
IF M=9 THEN LET Z=P
RETURN </langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 14,285:
The computer plays randomly.
 
<langsyntaxhighlight lang="sh">#!/usr/bin/env bash
# play tic-tac-toe
main() {
Line 14,389:
}
 
main "$@"</langsyntaxhighlight>
 
{{Out}}
Line 14,440:
=={{header|VBA}}==
Human play first with the "X". You must choose the row and the column you want to play...
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 14,567:
IsEnd = True
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>Loop 0
Line 14,603:
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/ioutil" for Input
 
Line 14,702:
if (yn == "n" || yn == "N") return
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 14,765:
=={{header|XPL0}}==
[[File:TTTXPL0.GIF|right]]
<langsyntaxhighlight XPL0lang="xpl0">\The computer marks its moves with an "O" and the player uses an "X". The
\ numeric keypad is used to make the player's move.
\
Line 14,909:
[SetVid(3); exit]; \clear screen & restore normal text mode
];
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
In the classic style.
<langsyntaxhighlight Yabasiclang="yabasic">5 REM Adaptation to Yabasic of the program published in Tim Hartnell's book "Artificial Intelligence: Concepts and Programs", with some minor modifications. 6/2018.
10 REM TICTAC
15 INPUT "English (0), Spanish (other key): " IDIOMA : IF NOT IDIOMA THEN RESTORE 2020 ELSE RESTORE 2010 END IF
Line 15,055:
2010 DATA "YO GANO,TU GANAS,ES SIMPLEMENTE UN DIBUJO,ESTA ES MI PRIORIDAD ACTUALIZADA,PULSE LA TECLA <RETURN> PARA CONTINUAR,REALICE SU MOVIMIENTO,MOVIMIENTO: "
2020 DATA "I WIN,YOU WIN,IT'S JUST A DRAWING,THIS IS MY PRIORITY UPDATE,PRESS <RETURN> TO CONTINUE,TO MAKE YOUR MOVE,MOVEMENT: "
</syntaxhighlight>
</lang>
 
{{omit from|GUISS}}
10,333

edits