To solve games using AI, we will introduce the concept of a game tree followed by minimax algorithm.

Overview

Tic Tac Toe

forthebadge forthebadge forthebadge

Running Tic-Tac-Toe:

  1. Make sure Python 3.6+ is installed.
  2. Install Flask Web Framework.
  3. Install requirements
    $ pip install requirements.txt
  1. Running the program:
	$ git clone https://github.com/krvaibhaw/tic-tac-toe.git
	$ cd tic-tac-toe
	$ python runner.py

Introduction

To solve games using AI, we will introduce the concept of a game tree followed by minimax algorithm. The different states of the game are represented by nodes in the game tree, very similar to the above planning problems. The idea is just slightly different. In the game tree, the nodes are arranged in levels that correspond to each player's turns in the game so that the “root” node of the tree (usually depicted at the top of the diagram) is the beginning position in the game. In tic-tac-toe, this would be the empty grid with no Xs or Os played yet. Under root, on the second level, there are the possible states that can result from the first player’s moves, be it X or O. We call these nodes the “children” of the root node.

Each node on the second level, would further have as its children nodes the states that can be reached from it by the opposing player's moves. This is continued, level by level, until reaching states where the game is over. In tic-tac-toe, this means that either one of the players gets a line of three and wins, or the board is full and the game ends in a tie.

What is Minimax?

Minimax is a artificial intelligence applied in two player games, such as tic-tac-toe, checkers, chess and go. This games are known as zero-sum games, because in a mathematical representation: one player wins (+1) and other player loses (-1) or both of anyone not to win (0).

How does it works?

The algorithm search, recursively, the best move that leads the Max player to win or not lose (draw). It consider the current state of the game and the available moves at that state, then for each valid move it plays (alternating min and max) until it finds a terminal state (win, draw or lose).

Understanding the Algorithm

The algorithm was studied by the book Algorithms in a Nutshell (George Heineman; Gary Pollice; Stanley Selkow, 2009). Pseudocode (adapted):

minimax(state, depth, player)

	if (player = max) then
		best = [null, -infinity]
	else
		best = [null, +infinity]

	if (depth = 0 or gameover) then
		score = evaluate this state for player
		return [null, score]

	for each valid move m for player in state s do
		execute move m on s
		[move, score] = minimax(s, depth - 1, -player)
		undo move m on s

		if (player = max) then
			if score > best.score then best = [move, score]
		else
			if score < best.score then best = [move, score]

	return best
end

Where,

  • state: the current board in tic-tac-toe (node)
  • depth: index of the node in the game tree
  • player: may be a MAX player or MIN player

The Python implementation of initial state, i.e. the initial state of the board. First of all, consider it:

def initial_state():

    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]

Both players start with your worst score. If player is MAX, its score is -infinity. Else if player is MIN, its score is +infinity. Note: infinity is an alias for inf (from math module, in Python).

if player(board) == X: 
        value = -math.inf

elseif player(board) == o:                           
        value = math.inf

If the depth is equal zero, then the board hasn't new empty cells to play. Or, if a player wins, then the game ended for MAX or MIN. So the score for that state will be returned.

def utility(board):
    
    if winner(board) == 'X':
        return 1
    
    elif winner(board) == 'O':
        return -1
    
    else:
        return 0
  • If MAX won: return +1
  • If MIN won: return -1
  • Else: return 0 (draw)

The action function will take the board as input and returns set of all possible actions (i, j) that are available on the board for the player to place his/her marker on.

def actions(board):

    possible_actions = []

    for i in range(3):
        for j in range(3):
            if board[i][j] == EMPTY:
                possible_actions.append((i,j))
                
    return possible_actions

For MAX player, a bigger score will be received. For a MIN player, a lower score will be received. And in the end, the best move is returned. It will loop through all the possible actions to find the optimal action and take it. Final algorithm:

def minimax(board):

    if terminal(board):     
        return None

    move = None

    alpha = -math.inf
    beta = math.inf

    if player(board) == X:  
        value = -math.inf

        for action in actions(board):
            updated_value = minmax_values(result(board, action),alpha, beta, O)

            alpha = max(value, updated_value)

            if updated_value > value:
                
                value = updated_value
                move = action

    else:                     
        value = math.inf

        for action in actions(board):
            updated_value = minmax_values(result(board, action),alpha, beta, X)

            beta = min(value, updated_value)

            if updated_value < value:
                
                value = updated_value
                move = action

    return move

Feel free to follow along the code provided along with mentioned comments for
better understanding of the project, if any issues feel free to reach me out.

Contributing

Contributions are welcome!
Please feel free to submit a Pull Request.

Owner
Vaibhaw
A passionate thinker, techno freak, comic lover, a curious computer engineering student. Machine Learning, Artificial Intelligence, Linux, Web Development.
Vaibhaw
Snake game mixed with Conway's Game of Life

SnakeOfLife Snake game mixed with Conway's Game of Life The rules are the same than a normal snake game but you have to avoid cells created by Conway'

Aidan 5 May 26, 2022
Box - a world simulator written in python with pygame

Box is a world simulator written in python with pygame. Features A world generation system A world editor Simulates creatures called boxlanders. You c

1up Community 3 Nov 14, 2022
An single python server emulator of MMORPG game WindSlayer also known as WS1.

PySlayer An single python server emulator of MMORPG game WindSlayer also known as WS1. Requirements Python = 3.7 Old windslayer client (Korea Yahoo!

mirusu400 29 Dec 19, 2022
This is an amazing game make using pygame.

This is an awesome balloon game. It is made in python using Pygame library. It is a project game while learning game development.

Rishikesh Kumar 2 Oct 10, 2021
2d war game single player

WarGame-third-version-0.0.4- 2d war game single player Hi ! Today, I publish on GitHub the version 0.0.4 of "WarGame". In this version, you can find a

Edouard Vincent 2 Apr 08, 2022
A top-down arcade space shooter made in pygame.

About: Journey Through Space is a top-down arcade shooter made in pygame. You play as a pilot who was left behind after a battle and the goal is to go

Crimson Sane 0 Jan 01, 2022
pygame is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

pygame is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

pygame 5.6k Jan 01, 2023
This is a basic virtual quiz game using opencv-python

Basic Virtual-Quiz-Game This is a basic structure of a virtual quiz game using opencv-python. As the camera window opens up we can see the questions a

2 Dec 11, 2021
A converter for the .BMR / .RLE bitmap files used in some Neversoft PS1 games.

Requirements python3 pyqt5 - can be installed with pip install PyQt5 pypng - Included Usage Instructions This program can be running py main.py in the

4 Jul 30, 2022
Multiple hacks that breaks the game

Blooket-Hack All of the cheats are based on a game mode.

glizzz_y 484 Feb 25, 2022
Space Invaders x Asteroid Game

Retro Journey 1: Space Invaders A simple implementation of a retro style video game where users compete against asteroids and the goal is to destroy a

Sandesh Lamsal 2 Aug 05, 2022
PLVRA is a TUI (Terminal User Interface) implementation of wordle / termo in portuguese, written in Python

PLVRA is a TUI (Terminal User Interface) implementation of wordle / termo in portuguese, written in Python

Enzo Shiraishi 1 Feb 11, 2022
A use of the python MCPI to enhance the multiplayer and singleplayer gameplay.

Morpheus 2.0 A use of the python MCPI to enhance the multiplayer and singleplayer gameplay. To Use: You will need to install the keyboard, pysimplegui

11 Oct 11, 2022
PyCraft - A Minecraft launcher made in python

A Minecraft launcher made in python. The main objective of this launcher is to enable players to enjoy minecraft (especially those without a mojang/microsoft account). This launcher is not illegal as

38 Dec 12, 2022
Arcade-like space shooter game written entirely in python

E.T.-Attack Arcade-like space shooter game written entirely in python Project description A space shooter game - inspired by the legendary game Space

Sven Eschlbeck 2 Dec 17, 2022
TetrisAI - Tetris AI Bot using computer vision to play game automatically

Tetris AI Tetris AI Bot using computer vision to play game automatically bot.py

11 Aug 29, 2022
Racing Fire - A simple game made with pygame.

Racing Fire A simple game in the making. Using pygame, this game is made to feel like an old arcade game. I developed a simple controller for it with

Builder212 1 Nov 09, 2021
Replicating Minecraft World Generation in Python

Minecraft World Generation in Python This is an attempt to replicate Minecraft world generation in Python. This is part of an article published on Med

Bilal Himite 159 Dec 19, 2022
This is Minesweeper coded in Python. It has almost all features from the main game

Minesweeper This is Minesweeper coded in Python. It has almost all features from the main game Use right click to open tile, right click on an open ti

3 Jul 12, 2022
A game based on Motus, to be played on Unix terminals.

Motus python game A game based on Motus, to be played on Unix terminals. How to play? Before playing, you need to install all the requirements needed

Arthur Molia 1 Feb 02, 2022