Tic-tac-toe: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Tailspin}}: typed array indices) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 26:
{{trans|Python}}
<
F nonrandom_choice(lst)
:seed = 1664525 * :seed + 1013904223
Line 111:
L.break
L.was_no_break
print("\nA draw")</
{{out}}
Line 158:
=={{header|Ada}}==
<
-- 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;</
{{out}}
Line 396:
=={{header|ALGOL W}}==
The user can play O, X, both or neither. O goes first whether user or computer controlled.
<
string(10) board;
Line 575:
do begin end
end.</
{{out}}
<pre>
Line 621:
=={{header|AppleScript}}==
<
property XMask : missing value
property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448}
Line 733:
end repeat
return theResult as integer
end BWAND</
=={{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.
<
Gui, Add, Button, x52 y12 w30 h30 vB2 gButtonHandler,
Gui, Add, Button, x92 y12 w30 h30 vB3 gButtonHandler,
Line 844:
GuiClose:
ExitApp
</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TIC-TAC-TOE.AWK
BEGIN {
Line 961:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
=={{header|Bash}}==
Line 983:
#encourage use of bash for more interesting tasks.
<
#!/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>
{{out}} (nice ANSI formatting is not shown)
<pre>
Line 1,091:
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight 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>
===Microsoft Small Basic===
This game has a simple AI.
<
place2 = 2
place3 = 3
Line 1,511:
Else
Goto reset
EndIf</
===ZX Spectrum Basic===
<
</syntaxhighlight>
=={{header|Batch File}}==
This is just a game between two human players.
<
setlocal enabledelayedexpansion
:newgame
Line 1,567:
pause
goto newgame
</syntaxhighlight>
===Advanced===
This code makes a version of Tic Tac Toe with more features:
<
:BEGIN
REM Skill level
Line 1,890:
set t7=
set t8=
set t9=</
=={{header|Befunge}}==
Line 1,897:
Plays reasonably well, but not perfectly, so can be beaten.
<
>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>
{{out}}
Line 1,957:
=={{header|C}}==
Opening alternates between human and computer. Computer never loses.
<
#include <stdlib.h>
Line 2,059:
while (1) printf("%s", game(first = !first));
return 0;
}</
=={{header|C sharp}}==
Line 2,065:
It tries to show a number of C# code features while still keeping each function small and understandable.
<
using System.Collections.Generic;
using System.Linq;
Line 2,310:
}
}</
{{out}}
Line 2,356:
=={{header|C++}}==
<
#include <windows.h>
#include <iostream>
Line 2,536:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
{{out}} Computer plays 'X' and human plays 'O'
<pre>
Line 2,549:
=={{header|Common 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>
{{out}}
Line 2,671:
=={{header|D}}==
<
std.ascii, std.array, std.range, std.math;
Line 2,785:
break;
}
}</
{{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</
=={{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">
-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>
{{out}}
<pre>
Line 3,384:
{{works with|OpenEuphoria}}
No computer AI
<
include std/console.e
include std/text.e
Line 3,485:
end while
</syntaxhighlight>
{{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.
<
| Empty
| Computer
Line 3,715:
let b = set Computer emptyBoard (choose (freeSpace emptyBoard))
printBoard b
gameLoop b User</
Example game:
Line 3,794:
Game between two humans.
<
\ board: 0=empty, 1=player X, 2=player O
Line 3,847:
game
</syntaxhighlight>
{{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.
<
! 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>
=={{header|FreeBASIC}}==
===graphics mode===
<
'About 400 lines of code, but it is a graphical (GUI ish) i.e. mouse driven.
Line 4,434:
End
End Sub
</syntaxhighlight>
===text mode===
<
Screenres 320,240,32
Line 4,680:
Loop Until Multikey(&H01)
End
</syntaxhighlight>
=={{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.
<
import (
Line 4,844:
{0, 4, 8}, // diagonals
{2, 4, 6},
}</
=={{header|Groovy}}==
Simplified version of Tic Tac Toe for player vs. player (no AI computer-controlled option).
<
def input = new Scanner(System.in)
Line 4,981:
return builder.toString();
}
}</
=={{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">
module Main where
Line 5,207:
putStrLn "3 : player X is human and player O is computer"
putStrLn "Player X always begins."
</syntaxhighlight>
{{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">
# Play TicTacToe
Line 5,449:
play_game ()
end
</syntaxhighlight>
=={{header|J}}==
To subsequent j poster: replacing this entry is fine by me.
<syntaxhighlight lang="j">
Note 'ttt adjudicates or plays'
Line 5,548:
nor=: 8 b.
infix_pairs_agree=: 2&(=/\)
</syntaxhighlight>
=={{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.
<
import java.io.BufferedReader;
import java.io.InputStreamReader;
Line 5,877:
}
}
</syntaxhighlight>
<pre>
Line 5,927:
This version uses javax.swing.
<
import java.awt.*;
import java.awt.event.*;
Line 6,090:
}
}
</syntaxhighlight>
Graphical Java Example
<
import javax.swing.*;
import java.awt.event.*;
Line 6,568:
}
}
</syntaxhighlight>
The following program may be executed for a player-against-player game.
<
import javax.swing.*;
import javax.swing.border.Border;
Line 6,851:
}
}
</syntaxhighlight>
=={{header|Javascript}}==
HTML5 Canvas implementation. Should play perfectly or near-perfectly.
<syntaxhighlight lang="javascript">
<!DOCTYPE html>
Line 7,292:
</html>
</syntaxhighlight>
Line 7,300:
Human is X and goes first.
<syntaxhighlight lang="javascript">
// Board
const topLeft = 1;
Line 7,485:
}
});
</syntaxhighlight>
{{out}}
Line 7,512:
=={{header|Julia}}==
One move look-ahead algorithm. Computer plays to win or at least draw.
<
[2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]]
Line 7,614:
tictactoe()
</
Board move grid:
1 2 3
Line 7,661:
=={{header|Kotlin}}==
{{trans|C}}
<
import java.util.Random
Line 7,767:
println()
}
}</
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">[
session_start('user')
session_addvar('user', 'matrix')
Line 7,921:
$matrix = array('-','-','-','-','-','-','-','-','-')
$turn = 'x'
}]</
=={{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.
<
global gBoard -- current board image
global gBoardTemplate -- empty board image
Line 8,163:
on sum (aLine)
return aLine[1]+aLine[2]+aLine[3]
end</
=={{header|Lua}}==
Version for LuaJIT with or without ffi, negamax algorithm with alpha-beta pruning and caching of results. Human can't win.
<
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
Line 8,356:
draw(board)
until endgame()
end</
{{out}}
Line 8,421:
=={{header|M2000 Interpreter}}==
Computer May loose;
<syntaxhighlight lang="m2000 interpreter">
Module Tic.Tac.Toe {
Dim Board$(1 to 3, 1 to 3)=" "
Line 8,533:
}
Tic.Tac.Toe
</syntaxhighlight>
{{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}]</
=={{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).
<
% 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</
{{out}}
Computer goes first and plays perfectly:
Line 8,991:
=={{header|mIRC Scripting Language}}==
<
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)
}
}</
=={{header|МК-61/52}}==
<
ПП 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 В/О</
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.
<
type
Line 9,140:
echo "Input the index of where you wish to place your mark at your turn."
randomize()
play()</
{{out}}
Line 9,203:
=={{header|Objeck}}==
Tic-tac-toe game using Minimax algorithm.
<
@board : Char[,];
@cpu_opening : Bool;
Line 9,574:
"===========\n"->PrintLine();
}
}</
=={{header|Pascal}}==
Line 9,582:
I would expect this version should compile with most Pascal variants including Delphi, but YMMR.
<
type
Line 9,745:
player := swapPlayer(player);
end
end.</
=={{header|Perl}}==
Line 9,756:
the computer. Anyone who can identify the mistake, is welcome to fix it.
<
use strict;
Line 9,855:
$whose_turn = !$whose_turn;
}
</syntaxhighlight>
{{out}}
Line 9,913:
</pre>
===Alternate with GUI===
<
use strict;
Line 9,984:
(sort {$a->[0] <=> $b->[0]} shuffle @moves)[ -($who eq 'X') ]
};
}</
=={{header|Phix}}==
Line 9,991:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Tic_tac_toe.htm here].
<!--<
<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>
<!--</
=={{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">
<?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>
=={{header|PicoLisp}}==
This solution doesn't bother about the game logic, but simply uses the alpha-beta-pruning 'game' function in the "simul" library.
<
(de display ()
Line 10,363:
((find3 T) "Congratulation, you won!")
((not (myMove)) "No moves")
((find3 0) "Sorry, you lost!") ) )</
{{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.
<
:-dynamic box/2.
Line 10,606:
computer(o).
</syntaxhighlight>
Module min-max.pl defines minimax algorithm.
<
% minimax(Player, Deep, MaxDeep, B, V-B)
Line 10,635:
lie(TTT, V-_, V-TTT).
</syntaxhighlight>
=={{header|Python}}==
The computer enforces the rules but plays a random game.
<
'''
Tic-tac-toe game player.
Line 10,714:
else:
print('\nA draw')
</syntaxhighlight>
'''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.
<
'''
Tic-tac-toe game player.
Line 10,848:
break
else:
print('\nA draw')</
{{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">
rm(list=ls())
library(RColorBrewer)
Line 11,347:
#start("name", "mode" = 0 - 2, type = 0,1)
</syntaxhighlight>
=={{header|Racket}}==
Line 11,368:
The <tt>minimax.rkt</tt> module:
<
#lang lazy
(provide minimax)
Line 11,389:
(next (cdr x)
(min β (minimax (car x) α β (not max-player))))))]))))
</
The <tt>game.rkt</tt> module:
<
#lang lazy
(require racket/class
Line 11,503:
(set-field! opponent p2 p1)
(send p1 your-turn initial-state))
</syntaxhighlight>
The <tt>tick-tack.rkt</tt> module:
<
(require "game.rkt"
Line 11,597:
(new (interactive-player o%) [name "Dummy"] [look-ahead 0]))
</syntaxhighlight>
Sample games:
Line 11,724:
As an example of another zero-sum game consider the classical [http://en.wikipedia.org/wiki/Nim Nim] game:
<
#lang racket
Line 11,764:
(define player-B
(new (interactive-player second%) [name "B"] [look-ahead 4]))
</syntaxhighlight>
Computer plays with the computer:
Line 11,800:
The computer plays a random game.
<syntaxhighlight lang="raku"
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!";
}</
=={{header|REXX}}==
Line 11,865:
<br>A fair amount of code was dedicated to error detection and the displaying of error messages, and
<br>also the presentation of the tic─tac─toe game boards (grids).
<
$= 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 " " " */</
This REXX program makes use of '''LINESIZE''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console); 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]
<
Load "guilib.ring"
Line 12,340:
next
if tie=true return 3 ok return 0
</syntaxhighlight>
{{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.
<
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</
{{out}}
Line 12,606:
=={{header|Run BASIC}}==
<
' TIC TAC TOE
' ---------------------------
Line 12,707:
input "Play again (y/n)";p$
if upper$(p$) = "Y" then goto [newGame]
end</
=={{header|Rust}}==
<
use GameState::{ComputerWin, Draw, PlayerWin, Playing};
Line 12,831:
}
</syntaxhighlight>
{{out}}
<pre>
Line 12,863:
Computer vs. human. Human starts. Computer plays 'O' and human plays 'X'.
Computer moves are legal, but random.
<
val Human = 'X'
val Computer = 'O'
Line 12,944:
}
}</
{{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()</
=={{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">
--Setup
drop table if exists board;
Line 13,449:
.print "->update board set p = 'X' where rowid = ?; select * from ui; select * from msg;"'
</syntaxhighlight>
{{out}}
<pre>
Line 13,481:
=={{header|Swift}}==
Some Basic AI for obvious losing and winning conditions
<syntaxhighlight lang="swift">
import Darwin
Line 13,688:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 13,792:
=={{header|Tailspin}}==
<
processor Tic-Tac-Toe
@: [position´1..position´9];
Line 13,850:
end play
$play -> !VOID</
{{out}}
<pre>
Line 13,907:
=={{header|Tcl}}==
{{trans|Python}}
<
# This code splits the players from the core game engine
Line 14,027:
# Assemble the pieces
set ttt [TicTacToe new HumanPlayer RandomRoboPlayer]
$ttt game</
Sample game:
<pre>
Line 14,079:
=={{Header|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 </
=={{header|UNIX Shell}}==
Line 14,285:
The computer plays randomly.
<
# play tic-tac-toe
main() {
Line 14,389:
}
main "$@"</
{{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">
Option Explicit
Line 14,567:
IsEnd = True
End Function
</syntaxhighlight>
{{out}}
<pre>Loop 0
Line 14,603:
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
<
import "/ioutil" for Input
Line 14,702:
if (yn == "n" || yn == "N") return
System.print()
}</
{{out}}
Line 14,765:
=={{header|XPL0}}==
[[File:TTTXPL0.GIF|right]]
<
\ numeric keypad is used to make the player's move.
\
Line 14,909:
[SetVid(3); exit]; \clear screen & restore normal text mode
];
]</
=={{header|Yabasic}}==
In the classic style.
<
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>
{{omit from|GUISS}}
|