• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
phil67rpg

tic tac toe AI

13 posts in this topic

I am working on a very simple AI and tic tac toe. my problem is that the O's overwrite the X's. I have tried various routines but I am still stuck. I am convinced that all I need is a couple of lines of code to finish. Please keep the help as simple as possible. Here is the code I am using. [code] void Computer::move_player_O()
{
player_O = rand()%9+1;
if(player_X==player_O)
{
repeat[player_O]=true;
}
else
{
repeat[player_O]=false;
}
}
void Computer::check_player_O()
{
if(repeat[player_O]==true)
{
board[player_O]='O';
}
else
{
move_player_O();
board[player_O]='O';
}
}[/code] I am using a Boolean to keep track of what mark is being placed where and what mark it is.
0

Share this post


Link to post
Share on other sites
Pretty tough to say what's going on without seeing the rest of the code (such as how the variable player_X is set and when, etc...) But still, it seems as if you are kind of going about this oddly.

You have a board that can hold 'X', 'O' or ' ' (space for empty). To find a randomly selected space for player O, you could do something similar to this:

[code]
int Computer::findRandomSpace()
{
int move=-1;
do
{
space=rand()%9;
}
while (board[move]!=' '
return move;
}

[/code]

Of course, this method will hang if the board is full, so ensure that you test the board first for a win/loss/draw condition. Essentially, you loop until you find an empty space, generating a new random board index each time.

Another way would be to iterate through the board and find all the empty spaces, and add the empties to a vector:

[code]
std::vector<int> Computer::getValidMoves()
{
std::vector<int> moves;
for(int c=0; c<9; ++c)
{
if (board[c]==' ') moves.push_back(c);
}
return moves;
}
[/code]

After calling getValidMoves(), you will have a vector that is either empty (if the board is full), or holds the indices of all empty spaces in the board. Now, you can choose one at random:

[code]
int Computer::chooseMove()
{
std::vector<int> moves=getValidMoves();
if(moves.size()==0) return -1; // Board is full
int length=moves.size();
return moves[rand() % length];
}
[/code]

Another benefit of constructing a vector of all valid moves is that when you move on to a smarter AI, you can change the getValidMoves() method to prioritize spaces by how much closer they get you to a win condition. For example, if a space will generate a win condition for the player, it receives the highest priority; if a space will block the other player from a win condition, it gets the next highest priority. And so forth. You can sort the vector based on priority, then in the chooseMove() method, instead of grabbing a random space you grab the space at the back of the list (assuming you sort from lowest priority to highest). That way, you always choose the best move you can make. Edited by JTippetts
2

Share this post


Link to post
Share on other sites

Since you say that pieces override each other, you can keep a track of board state and play there only where its empty.

something like this.

 

 


for(int i=0;i<9;i++)
{
if(board[i]==EMPTY)
{
int sq_move=board[i];
......
}
}
0

Share this post


Link to post
Share on other sites

Hello, but speaking of wiser AI. Is there a good AI system to make tic tac toe forecast other person move?

As I know if you play second you can only draw. 

If you play first you can win, but if the other player is good enough he can also draw.

So priority to the center, then the corners and then it depends on the other person's moves.

I tried to create some schema based on weights of cells, but sometimes i managed to deceive my AI, so I'm asking

0

Share this post


Link to post
Share on other sites

You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

Edited by Álvaro
2

Share this post


Link to post
Share on other sites

It would actually be very easy to build a smarter AI for Tic Tac Toe, such as trying to block wins and what not.  First start by scanning the board for opponent boxes, when you find one start checking adjacent boxes, if they have the opponent's mark then check for the next box in the series and place your mark there.  If you scan through the entire board and don't find any potential wins you would do the process again in your favor.  Look for potential wins.  If you cant find a potential win look for a path that you can go that isn't blocked yet (eg find 2 empty boxes in a direction from one of your marks).  Here's a little mock up of the idea I'm thinking of (not real code)...

 

// we assume that gameBoard is a 2d array of ints
// gameBoard[row][col] = 0 for empty, -1 for x, +1 for o)

// we assume that the "Player" is X and the PC is O

bool defenseCheck()
{
    for(int r=0; r<3; r++)
    {
        for(int c=0; c<3; c++)
        {
            if(gameBoard[r][c] == -1)
            {
                // You would have to play with this but basically...
                if(gameBoard[r][c+1] == -1 && gameBoard[r][c+2] == 0)
                {
                    gameBoard[r][c+2] = 1;
                    return true;
                }
            }
        }
    }
}

bool winCheck()
{
    // Same as defense check but looking for +1's in a row that we can complete
}

bool moveCheck()
{
    // This assumes defenseCheck and winCheck both failed.  In this case we want to do the same thing but we're looking for +1 and then 2 empty 0's in a row
}

void npcMover()
{
    if(winCheck())
    {
        Say("I just beat you at Tic Tac Toe so ha!");
    }
    else if(defenseCheck())
    {
        Say("Ha, blocked your puny attempt to beat me!");
    }
    else if(moveCheck())
    {
        Say("Let's see what you do now mr tic");
    }
    else
    {
        Say("I don't know what to do!!!");
        ThrowTemperTantrum();
    }
}
0

Share this post


Link to post
Share on other sites
You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

So you'd enumerate the open cells, then assign each one a score based on how valuable a play there would be, considering wins, then blocks, then moves that would lead toward wins, right? (I've never implemented a minimax.) That would be easily extensible to larger board sizes too.


 

        ThrowTemperTantrum();

 

Oi, don't give away my secret move. happy.png

Edited by Khatharr
0

Share this post


Link to post
Share on other sites

You can make an interesting AI by implementing minimax search and assigning +1000 to winning, -1000 to losing and a random number R (with abs( R ) < 1000) for draws. The program will play optimally (never lose, win if it can), and it will also play in ways that reduce the options of the opponent, most of the time.

So you'd enumerate the open cells, then assign each one a score based on how valuable a play there would be, considering wins, then blocks, then moves that would lead toward wins, right? (I've never implemented a minimax.) That would be easily extensible to larger board sizes too. 



No, that's not how minimax works. Minimax examines the tree of moves available from the current position and, given desirability values for the leaves of the tree, it propagates these values to the interior nodes.
0

Share this post


Link to post
Share on other sites
So each node or branch represents a potential action and the leaves are end conditions?

Yes. You should search the web for the term "minimax". Since it is the basis of computer chess, there is a lot of information about it out there. The algorithm has been around since around 1950, but it is so natural that a lot of people have rediscovered it (including myself).
0

Share this post


Link to post
Share on other sites

You dont necessarily need to use Minimax. Here's the xkcd's optimal tic-tac-toe moves for each player.

 

And this is the list of rules you need to check if you choose to implement this kind of method(from tic-tac-toe page on wikipedia);

  1. Win: If the player has two in a row, they can place a third to get three in a row.
  2. Block: If the [opponent] has two in a row, the player must play the third themself to block the opponent.
  3. Fork: Creation of an opportunity where the player has two threats to win (two non-blocked lines of 2).
  4. Blocking an opponent's fork:
    • Option 1: The player should create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)
    • Option 2: If there is a configuration where the opponent can fork, the player should block that fork.
  5. Center: A player marks the center. (If it is the first move of the game, playing on a corner gives "O" more opportunities to make a mistake and may therefore be the better choice; however, it makes no difference between perfect players.)
  6. Opposite corner: If the opponent is in the corner, the player plays the opposite corner.
  7. Empty corner: The player plays in a corner square.
  8. Empty side: The player plays in a middle square on any of the 4 sides
Edited by cagdassalur
0

Share this post


Link to post
Share on other sites

You dont necessarily need to use Minimax. [...]

 

While that's true, using a game-specific recipe doesn't teach you anything you can apply in another game, and the whole point is to use tic-tac-toe as a learning tool.

 

You can also make a graph with all the positions in the game and use retrograde analysis to assign values to every node. This will also solve the game, and it will teach you how to create [url="http://en.wikipedia.org/wiki/Endgame_tablebase"]endgame tablebases[/url].

2

Share this post


Link to post
Share on other sites

If anyone cares,  There is a chapter for Tic-Tac-Toe in the book called "Begining C++ through Game Programming. That solves the problem

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0