Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,915 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,145 people online right now. Registration is fast and FREE... Join Now!




Tic Tac Toe Program That Learns

4 Pages V  1 2 3 > »   
Reply to this topicStart new topic

Tic Tac Toe Program That Learns, I want to make a tic tac toe program that remembers the moves that all

devilsson2010
2 Jan, 2008 - 07:35 PM
Post #1

New D.I.C Head
*

Joined: 2 Jan, 2008
Posts: 46


My Contributions
Hi, I'm a new c++ coder and I've been experimenting with some code lately and I figured it couldn't be too hard to make a c++ tic tac toe ai that will remember how it won and lost. Basically you just play a crappy ai at the start but each time you or the bot wins it will save the steps that were made into a text file, and then whenever it is the bots turn it will check the text file and see if it has any relevant information, and if not it will move randomly. But of course I really don't know where to start in any of this. Also I know that there is probably an easier program to do this in but I'm going to stick with c++ for now.

Here is what I was thinking the lines in the text file would look like:
623918754
948365217

Well you get it. Each number represents a space on the tic tac toe board and the computer will see if it can use them. Any one have any help that they can give me on how to start programming the ai and such?
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Tic Tac Toe Program That Learns
2 Jan, 2008 - 07:54 PM
Post #2

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,589



Thanked: 12 times
Dream Kudos: 325
My Contributions
You would also have to store the other player's moves. One losing move sequence could easily be a winning one depending on how the other player moves.

You might want to take a look at this pdf.

You've also got to keep in mind that a perfect AI playing against a human (assuming the human doesn't do anything stupid).

I suggest you design and program your Tic-Tac-Toe game first, and then work on the AI. smile.gif
User is online!Profile CardPM
+Quote Post

devilsson2010
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 02:37 PM
Post #3

New D.I.C Head
*

Joined: 2 Jan, 2008
Posts: 46


My Contributions
QUOTE(Tom9729 @ 2 Jan, 2008 - 08:54 PM) *

I suggest you design and program your Tic-Tac-Toe game first, and then work on the AI. smile.gif


Yeah I have the tic tac toe code mostly figured out, I'll post it in a few, but I don't really no where to start to code an ai, let alone saving to a file and reading it.
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 03:08 PM
Post #4

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,589



Thanked: 12 times
Dream Kudos: 325
My Contributions
Writing to/reading from text files in C++ is easy.
http://www.cplusplus.com/doc/tutorial/files.html

As for the AI, I suggest you get some mind mapping software ( http://freemind.sourceforge.net/wiki/index.php/Main_Page ) and start brainstorming.

Your game should have a loop, part of which should be getting input from the players (the human player, and the AI).

Something like..
CODE

while(game_running)
{
    switch (turn)
    {
        case 0:
            player_move();
            turn = 1;
            break;

        case 1:
            ai_move();
            turn = 0;
            break;
    }
}


Where ai_move() could involve calling functions like analyze_old_moves() and do_move() (just ideas).

Edit: I've attached a Freemind mindmap for part of my checkers game. It doesn't really describe a complete AI (it just enforces the rules during one player's turn), but it's a start.

You could probably do something similar for Tic-Tac-Toe.

This post has been edited by Tom9729: 3 Jan, 2008 - 03:14 PM


Attached File(s)
Attached File  checkers_mm.zip ( 1.14k ) Number of downloads: 95
User is online!Profile CardPM
+Quote Post

devilsson2010
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 03:22 PM
Post #5

New D.I.C Head
*

Joined: 2 Jan, 2008
Posts: 46


My Contributions
icon_up.gif
QUOTE(Tom9729 @ 3 Jan, 2008 - 04:08 PM) *

Writing to/reading from text files in C++ is easy.
http://www.cplusplus.com/doc/tutorial/files.html

As for the AI, I suggest you get some mind mapping software ( http://freemind.sourceforge.net/wiki/index.php/Main_Page ) and start brainstorming.

Your game should have a loop, part of which should be getting input from the players (the human player, and the AI).

Something like..
CODE

while(game_running)
{
    switch (turn)
    {
        case 0:
            player_move();
            turn = 1;
            break;

        case 1:
            ai_move();
            turn = 0;
            break;
    }
}


Where ai_move() could involve calling functions like analyze_old_moves() and do_move() (just ideas).

Edit: I've attached a Freemind mindmap for part of my checkers game. It doesn't really describe a complete AI (it just enforces the rules during one player's turn), but it's a start.

You could probably do something similar for Tic-Tac-Toe.



Extremely helpful, thanks icon_up.gif .
User is offlineProfile CardPM
+Quote Post

devilsson2010
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 04:09 PM
Post #6

New D.I.C Head
*

Joined: 2 Jan, 2008
Posts: 46


My Contributions
Quick question about the input and output. When I try to write to a file called win.txt it says that it worked but in the folder that I have all of the source code and stuff in, the win.txt file still has nothing in it.

This is the code I used: (yeah there are some idiotic comments, but I make them for myself so I know what does what quickly)

CODE
#include <stdlib.h>
#include <fstream>
using namespace std;

int sWin() // Make a function to save to the Win File (win.txt)
{
  ofstream WinFile ("win.txt");

  if (WinFile.is_open()) // Checks if win.txt is open and then writes to it if it is
  {
  WinFile << "Writing this to win.txt.\n";
  WinFile.close();
  std::cout << "win.txt was successfully written to!" << std::endl;
  }
  else std::cout << "Unable to open win.txt!" << std::endl;;

} // End the sWin() function


main() // Start the main() function
{
  sWin(); // Run the main function


  system("PAUSE"); // Make the console wait for a response from the user to close
} // End the main() function

User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 04:55 PM
Post #7

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
Well, this doesn't look like it should compile.

You should be using <cstdlib>, not stdlib.h. And I don't know how you're getting it to run without #including <iostream>, as that's where cout is defined. system("PAUSE") is windows specific, but that's okay (sort of) if you're not required to write portable code. main() should also specify an return type, and actually return one:
CODE
int main() {
    sWin();
    system("PAUSE");
    return 0;
}


But with those fixed, it should run properly.

What compiler are you using?

p.s. those aren't idiotic comments. overly-abundant commenting (which you haven't done) can be problematic if it makes the code hard to read, but commenting sufficiently to clarify everything for yourself and others is a very good thing smile.gif

This post has been edited by jjhaag: 3 Jan, 2008 - 04:55 PM
User is offlineProfile CardPM
+Quote Post

devilsson2010
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 05:39 PM
Post #8

New D.I.C Head
*

Joined: 2 Jan, 2008
Posts: 46


My Contributions
QUOTE(jjhaag @ 3 Jan, 2008 - 05:55 PM) *

Well, this doesn't look like it should compile.

You should be using <cstdlib>, not stdlib.h. And I don't know how you're getting it to run without #including <iostream>, as that's where cout is defined. system("PAUSE") is windows specific, but that's okay (sort of) if you're not required to write portable code. main() should also specify an return type, and actually return one:
CODE
int main() {
    sWin();
    system("PAUSE");
    return 0;
}


But with those fixed, it should run properly.

What compiler are you using?

p.s. those aren't idiotic comments. overly-abundant commenting (which you haven't done) can be problematic if it makes the code hard to read, but commenting sufficiently to clarify everything for yourself and others is a very good thing smile.gif


Well I changed the include file names you told me to and added return 0 to the end. Here is all of the code for a 2 player tic tac toe (I used some of the code from xoax.net): But I get an error when compiling with Devc++; "parse error at end of input" line 166. Line 166 is the last line.

CODE

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

char cSquare1('1');// Make the square variables that will make up each place on the board
char cSquare2('2');
char cSquare3('3');
char cSquare4('4');
char cSquare5('5');
char cSquare6('6');
char cSquare7('7');
char cSquare8('8');
char cSquare9('9');
int iPlayerTurn('1');
bool bGameOver(true);
char cNextMove;
bool bValidMove;
char cMark;



void ShowBoard() // Make a function to show the board
{
std::cout << " " << cSquare7 << " | " << cSquare8 << " | " << cSquare9 << " " << std::endl;
std::cout << " --+---+-- "<< std::endl;
std::cout << " " << cSquare4 << " | " << cSquare5 << " | " << cSquare6 << " " << std::endl;
std::cout << " --+---+-- "<< std::endl;
std::cout << " " << cSquare1 << " | " << cSquare2 << " | " << cSquare3 << " " << std::endl;
std::cout << "------------------------" << std::endl;
} // End the ShowBoard() function



void sWin() // Make a function to save to the Win File (win.txt)
{
  ofstream WinFile ("win.txt");

  if (WinFile.is_open()) // Checks if win.txt is open and then writes to it if it is
  {
  WinFile << "Writing this to win.txt.\n";
  WinFile.close();
  std::cout << "win.txt was successfully written to!" << std::endl;
  }
  else std::cout << "Unable to open win.txt!" << std::endl;

} // End the sWin() function



int main() // Start the main() function
{
    bool bGameOver(false);

    while (!bGameOver) { // Start of 'if game not over' code

  if (iPlayerTurn=='1') { // Make player 1 use 'X' and player 2 use 'O'
  cMark = 'X'; }
  else {cMark = 'O';} // Ends cMark if statement



     if (iPlayerTurn=='1') { // Make player 1 use 'X' and player 2 use 'O'
      cMark = 'X'; }
       else {cMark = 'O';} // Ends cMark if statement

    ShowBoard(); // Show the playing board
    std::cout << "Player " << iPlayerTurn << "'s turn." << std::endl; // Asks player to go
    std::cin >>cNextMove; // The player's move


            do { // Start of 'check valid move' do while statement
              if (cNextMove == '1' && cSquare1 == '1')
              {cSquare1 = cMark;}
              else if (cNextMove == '2' && cSquare1 == '2')
              {cSquare1 = cMark;}
              else if (cNextMove == '3' && cSquare1 == '3')
              {cSquare1 = cMark;}
              else if (cNextMove == '4' && cSquare1 == '4')
              {cSquare1 = cMark;}
              else if (cNextMove == '5' && cSquare1 == '5')
              {cSquare1 = cMark;}
              else if (cNextMove == '6' && cSquare1 == '6')
              {cSquare1 = cMark;}
              else if (cNextMove == '7' && cSquare1 == '7')
              {cSquare1 = cMark;}
              else if (cNextMove == '8' && cSquare1 == '8')
              {cSquare1 = cMark;}
              else if (cNextMove == '9' && cSquare1 == '9')
              {cSquare1 = cMark;}
              else {
              ShowBoard();
              std::cout << "Invalid move, please try again." << std::endl;
              bValidMove = false;} while (!bValidMove) // End of 'check valid move' do while statement

            bGameOver = false;
            bool bWinGame = true;

        // Check for end of game conditions
        if (cSquare1 != '1') {
            if (cSquare2 == cSquare1 && cSquare3 == cSquare1) {
                bGameOver = true;
            }
            if (cSquare4 == cSquare1 && cSquare7 == cSquare1) {
                bGameOver = true;
            }
        }
        if (cSquare5 != '5') {
            if (cSquare1 == cSquare5 && cSquare9 == cSquare5) {
                bGameOver = true;
            }
            if (cSquare2 == cSquare5 && cSquare8 == cSquare5) {
                bGameOver = true;
            }
            if (cSquare4 == cSquare5 && cSquare6 == cSquare5) {
                bGameOver = true;
            }
            if (cSquare3 == cSquare5 && cSquare7 == cSquare5) {
                bGameOver = true;
            }
        }
        if (cSquare9 != '9') {
            if (cSquare3 == cSquare9 && cSquare6 == cSquare9) {
                bGameOver = true;
            }
            if (cSquare7 == cSquare9 && cSquare8 == cSquare9) {
                bGameOver = true;
            }
        } // End of checking for end game conditions

        // Check board for no win condition (draw)
        if (cSquare1 != '1' && cSquare2 != '2' && cSquare3 != '3' &&
            cSquare4 != '4' && cSquare5 != '5' && cSquare6 != '6' &&
            cSquare7 != '7' && cSquare8 != '8' && cSquare9 != '9' && !bGameOver)
        { // End of checking for draw

           if (bGameOver) {
           if (bWinGame) {
                std::cout << "Player " << iPlayerTurn << " wins!" << std::endl;}

           char cPlayAgain;
           std::cout << "Game Over, want to play again (y/n)?" << std::endl; // Play again question
           std::cin >> cPlayAgain;

           if (cPlayAgain == 'y') { // Play again check
               bGameOver = false;
               cSquare1 = '1'; // if yes then clear baord and restart
               cSquare1 = '2';
               cSquare1 = '3';
               cSquare1 = '4';
               cSquare1 = '5';
               cSquare1 = '6';
               cSquare1 = '7';
               cSquare1 = '8';
               cSquare1 = '9';} // end play again check

     if (iPlayerTurn=='1') { // Switches turns between player 1 and 2
         iPlayerTurn = '2';}
     else {iPlayerTurn = '1';}

   } // End of 'if game not over' code

  return 0; // Returns value from main() function
} // End the main() function


User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 05:55 PM
Post #9

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
You're missing at least a couple of closing braces ( } )in there somewhere, and possibly some other stuff as well. The indentation and code block style that you're using aren't all that clear, so it's tough to see exactly where it is. If I get a chance, I'll take a look and try to find it.
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 05:58 PM
Post #10

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,589



Thanked: 12 times
Dream Kudos: 325
My Contributions
Just a few things.

* If you declared "using namespace std", you don't have to include the "std::" part when calling functions from there.

* I might be mistaken, but I think the reason your text file isn't being written to is because you never called "WinFile.open()".

* Your code would be a bit cleaner if you used a "char" array instead of having individual "char"'s.

* Count your braces and parentheses, somewhere you misplaced a few and that's the reason for the compiler error.

This post has been edited by Tom9729: 3 Jan, 2008 - 06:00 PM
User is online!Profile CardPM
+Quote Post

jjhaag
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 06:04 PM
Post #11

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
QUOTE(Tom9729 @ 3 Jan, 2008 - 06:58 PM) *

* I might be mistaken, but I think the reason your text file isn't being written to is because you never called "WinFile.open()".


The opening of the file is handled in the constructor, in this case.
CODE
ofstream WinFile ("win.txt");

is functionally equivalent to:
CODE
ofstream WinFile;
WinFile.open("win.txt");


This post has been edited by jjhaag: 3 Jan, 2008 - 06:05 PM
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Tic Tac Toe Program That Learns
3 Jan, 2008 - 06:16 PM
Post #12

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,589



Thanked: 12 times
Dream Kudos: 325
My Contributions
QUOTE(jjhaag @ 3 Jan, 2008 - 07:04 PM) *

The opening of the file is handled in the constructor

Ahhhh ok. I don't know very much about C++.

CODE

char cSquare3('3');
char cSquare4('4');
char cSquare5('5');
char cSquare6('6');

I've never seen variables initialized like that. Is that common in C++?
User is online!Profile CardPM
+Quote Post

4 Pages V  1 2 3 > » 
Reply to this topicStart new topic
Time is now: 1/8/09 02:19PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos Th