Skip to content

Instantly share code, notes, and snippets.

@timlg07
Created December 24, 2020 12:26
Show Gist options
  • Save timlg07/f8ed6821c58f58e0f1c4c23a3ec4e1bb to your computer and use it in GitHub Desktop.
Save timlg07/f8ed6821c58f58e0f1c4c23a3ec4e1bb to your computer and use it in GitHub Desktop.
The Tic Tac Toe game implemented as Batch script.
@echo off
setlocal enabledelayedexpansion
title tic tac toe
:init
set "options="
set "players=XO"
set /a rounds = 0
set "separator=+-----------+"
for /l %%i in (1 1 9) do (
set "board#%%i=%%i"
set "options=!options!%%i"
)
:game
set /a rounds += 1
:: Bitwise 'and' to check if player 0 or 1 is the current player.
set /a "currentPlayerIndex = !(rounds & 1)"
set "currentPlayer=!players:~%currentPlayerIndex%,1!"
call :repaint
echo.
echo Choose one of the remaining fields:
choice /c %options%
set /a choiceIndex = %errorlevel% - 1
set "chosenNumber=!options:~%choiceIndex%,1!"
:: Remove the chosen number from the available choices.
set "options=!options:%chosenNumber%=!"
:: Set the choice in the board.
set "board#%chosenNumber%=%currentPlayer%"
:: Check if that move lets the current player win.
for %%c in ("1 2 3" "4 5 6" "7 8 9" "1 4 7" "2 5 8" "3 6 9" "1 5 9" "3 5 7") do (
set "_isValid=true"
for %%i in (%%~c) do (
if "!board#%%i!" neq "%currentPlayer%" set "_isValid=false"
)
if "!_isValid!"=="true" (
rem Repaint to show the last move.
call :repaint
echo.
echo Congratulations %currentPlayer%, you won the game.
goto gameover
)
)
:: Check for a draw (if the board is full and no winner was found).
if "%options%"=="" (
rem Repaint to show the last move.
call :repaint
echo.
echo This is a draw, no one wins.
goto gameover
)
:: Next round
goto game
:repaint
cls
echo Round %rounds%. It is your turn, %currentPlayer%.
echo.
echo.%separator%
for %%l in ("1 2 3" "4 5 6" "7 8 9") do (
set "line="
for %%c in (%%~l) do (
set "line=!line!^| !board#%%c! "
)
echo.!line!^|
echo.%separator%
)
exit /b
:gameover
echo.
echo Press any key to play again...
pause > nul
goto init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment