<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/tic-tac-toe-simulation-random-moves/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r.prevos.net/tic-tac-toe-simulation/"> The Devil is in the Data</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>
<img sizes="(max-width: 300px) 100vw, 300px" data-image-description="" data-orig-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2017/03/ttt_random.gif?fit=600%2C600" data-orig-size="600,600" data-image-title="ttt_random" class="wp-image-478" data-comments-opened="1" data-recalc-dims="1" data-attachment-id="478" data-permalink="http://r.prevos.net/tic-tac-toe-simulation/ttt_random/" alt="Tic Tac Toe Simulation - Part 1" data-medium-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2017/03/ttt_random.gif?fit=300%2C300" data-large-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2017/03/ttt_random.gif?fit=584%2C584" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2017/03/ttt_random.gif?resize=300%2C300">Tic Tac Toe might be a futile children’s game but it can also teach us about artificial intelligence. Tic Tac Toe, or Naughts and Crosses, is a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Zero-sum_game">zero-sum game</a> with perfect information. Both players know exactly what the other did and when nobody makes a mistake, the game will always end in a draw.</p>
<p>Tic Tac Toe is a simple game but also the much more complex game of chess is a zero-sum game with perfect information.</p>
<p>In this two-part post, I will build an unbeatable Tic Tac Toe Simulation. This first part deals with the mechanics of the game. The second post will present an algorithm for a perfect game.</p>
<h2>Drawing the Board</h2>
<p>This first code snippet draws the Tic Tac Toe simulation board. The variable <em>xo</em> holds the identity of the pieces and the vector <em>board</em> holds the current game. Player X is denoted with -1 and player O with +1. The first part of the function draws the board and the naughts and crosses. The second part of the code check for three in a row and draws the corresponding line.</p>
<pre>
draw.board &lt;- function(board) { # Draw the board
    xo &lt;- c(&quot;X&quot;, &quot; &quot;, &quot;O&quot;) # Symbols
    par(mar = rep(0,4))
    plot.new()
    plot.window(xlim = c(0,30), ylim = c(0,30))
    abline(h = c(10, 20), col=&quot;darkgrey&quot;, lwd = 4)
    abline(v = c(10, 20), col=&quot;darkgrey&quot;, lwd = 4)
    pieces &lt;- xo[board + 2]
    text(rep(c(5, 15, 25), 3), c(rep(25, 3), rep(15,3), rep(5, 3)), pieces, cex = 6)
    # Identify location of any three in a row
    square &lt;- t(matrix(board, nrow = 3))
    hor &lt;- abs(rowSums(square))
    if (any(hor == 3)) 
      hor &lt;- (4 - which(hor == 3)) * 10 - 5 
    else 
      hor &lt;- 0
    ver &lt;- abs(colSums(square))
    if (any(ver == 3)) 
      ver &lt;- which(ver == 3) * 10 - 5 
    else
      ver &lt;- 0
    diag1 &lt;- sum(diag(square))
    diag2 &lt;- sum(diag(t(apply(square, 2, rev)))) 
    # Draw winning lines 
    if (hor > 0) lines(c(0, 30), rep(hor, 2), lwd=10, col=&quot;red&quot;)
    if (ver > 0) lines(rep(ver, 2), c(0, 30), lwd=10, col=&quot;red&quot;)
    if (abs(diag1) == 3) lines(c(2, 28), c(28, 2), lwd=10, col=&quot;red&quot;)
    if (abs(diag2) == 3) lines(c(2, 28), c(2, 28), lwd=10, col=&quot;red&quot;)
}
</pre>
<h2>Random Tic Tac Toe</h2>
<p>The second part of the code generates ten random games and creates and animated GIF-file. The code adds random moves until one of the players wins (winner &lt;> 0) or the board is full (no zeroes in the <em>game</em> vector). The <em>eval.winner</em> function checks for three in a row and declares a winner when found.</p>
<p>There are <a target="_blank" rel="nofollow" href="http://www.se16.info/hgb/tictactoe.htm">255,168 possible legal games</a> in Tic Tac Toe, 46,080 of which end in a draw. This implies that these randomised games result in a draw 18% of the time.</p>
<pre>
eval.winner &lt;- function(board) { # Identify winner
    square &lt;- t(matrix(board, nrow = 3))
    hor &lt;- rowSums(square)
    ver &lt;- colSums(square)
    diag1 &lt;- sum(diag(square))
    diag2 &lt;- sum(diag(t(apply(square, 2, rev))))
    if (3 %in% c(hor, ver, diag1, diag2)) return (1)
    else
        if (-3 %in% c(hor, ver, diag1, diag2)) return (2)
    else
        return(0)
}

# Random game
library(animation)
saveGIF ({
 for (i in 1:10) {
 game &lt;- rep(0, 9) # Empty board
 winner &lt;- 0 # Define winner
 player &lt;- -1 # First player
 draw.board(game)
 while (0 %in% game &amp; winner == 0) { # Keep playing until win or full board
   empty &lt;- which(game == 0) # Define empty squares
   move &lt;- empty[sample(length(empty), 1)] # Random move
   game[move] &lt;- player # Change board
   draw.board(game)
   winner &lt;- eval.winner(game) # Evaulate game
   player &lt;- player * -1 # Change player
 }
 draw.board(game)
 }
 },
 interval = 0.25, movie.name = &quot;ttt.gif&quot;, ani.width = 600, ani.height = 600)
</pre>
<h2>Tic Tac Toe Simulation</h2>
<p>In a future post, I will outline how to program the computer to play against itself, just like in the 1983 movie <em>War Games</em>.</p>
<p><iframe width="450" allowfullscreen="true" src="https://www.youtube.com/embed/F7qOV8xonfY?version=3&rel=1&%23038;fs=1&%23038;autohide=2&%23038;showsearch=0&%23038;showinfo=1&%23038;iv_load_policy=1&%23038;wmode=transparent" type="text/html"></iframe></p>
<p>The post <a target="_blank" rel="nofollow" href="http://r.prevos.net/tic-tac-toe-simulation/">Tic Tac Toe Simulation — Random Moves</a> appeared first on <a target="_blank" rel="nofollow" href="http://r.prevos.net/">The Devil is in the Data</a>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r.prevos.net/tic-tac-toe-simulation/"> The Devil is in the Data</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/YNMmyFPmGu0"></a></div>