1

I know most basic python syntax other than OOP stuff. I tried building this tic tac toe game but the code does not work. I think I messed up the while loop where I string together all the functions. Could you tell me what is wrong? I am very new to programming. Any help is deeply appreciated.

def tic_tac_toe():
    Numbers = [1,2,3,4,5,6,7,8,9]
    Win = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7)]
    def draw():
        print(Numbers[0],Numbers[1],Numbers[2])
        print(Numbers[3],Numbers[4],Numbers[5])
        print(Numbers[6],Numbers[7],Numbers[8])
    def p1():
        while True:
            try:
                main_input1 = int(raw_input("P1:Where do you want to go?"))
                draw()
                break
            except:
                print("Gimme a number")
        main_input1 -= 1
        if Numbers[main_input1]=="X" or Numbers[main_input1]=="O":
            print("That is taken")
            p1()
        else:
            Numbers[main_input1]=="X"
    def p2():
        while True:
            try:
                main_input2 = int(raw_input("P2:Where do you want to go?"))
                draw()
                break
            except:
                print("Gimme a number")
        main_input2 -= 1
        if Numbers[main_input2]=="X" or Numbers[main_input2]=="O":
            print("That is taken")
            p2()
        else:
            Numbers[main_input2]=="O"

    def have_you_won():
        for i in range(0,9):
            if Win[i][1] == Win[i][2] and Win[i][2] == Win[3] and Win[i][1]=="X":
                print("P1 has won")
            elif Win[i][1] == Win[i][2] and Win[i][2] == Win[3] and Win[i][1]=="O":
                print("P2 has won the game")
            else:
                return False
    draw()
    for i in range(0,10):
        p1()
        have_you_won()
        p2()
        have_you_won()
        if i==9:
            print("Its a tie!!")

tic_tac_toe()
8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

1 Answers1

0

It seems like you started out with javascript, writing a function with functions inside of it. Its not a recommended way in Python.

I refactored your code, changed it to work with Python 3 (with input rather then raw_input) and it works for me.

Please read the Python style guides if you will be diving into Python programming, specially PEP8.


This could be the content of a file game.py:

# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 ralf


BOARD = [
    1, 2, 3, 4, 5, 6, 7, 8, 9,
]
WINNING_COMBINATIONS = [
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9),
    (1, 4, 7),
    (2, 5, 8),
    (3, 6, 9),
    (1, 5, 9),
    (3, 5, 7),
]
P1 = 'X'
P2 = 'O'


def draw_board():
    print('')
    print('Current state of the board:')
    print('', BOARD[0], BOARD[1], BOARD[2])
    print('', BOARD[3], BOARD[4], BOARD[5])
    print('', BOARD[6], BOARD[7], BOARD[8])


def make_move(player):
    while True:
        try:
            draw_board()
            n = int(input('Player "{}": Where do you want to go?'.format(player)))

            if BOARD[n-1] == 'X' or BOARD[n - 1] == 'O':
                print('That is taken')
            else:
                BOARD[n - 1] = player
                return
        except ValueError:
            print('Error: Gimme a number')


def check_for_win(player):
    for i, j, k in WINNING_COMBINATIONS:
        if BOARD[i-1] == BOARD[j-1] == BOARD[k-1] == player:
            return True

    return False


def play():
    player = P1
    for _ in range(0, 10):
        # alternate players
        if player == P1:
            player = P2
        else:
            player = P1

        make_move(player)
        if check_for_win(player):
            print()
            print('Player "{}" has won'.format(player))
            draw_board()
            return

    print('Its a tie!!')


if __name__ == '__main__':
    play()

To run the game, just execute the file: python game.py. This will work because play() is executed inside the if __name__ == '__main__': clause (read more).

Or you could use the game.py module (Python file) inside other Python code:

from game import play   # import the game
play()                  # start the game
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • [See this post](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Ralf Mar 08 '18 at 10:24
  • could this be done in python 3 ?How does the last if statement be done? –  Mar 08 '18 at 10:31
  • Edited my answer with info how to run the game. – Ralf Mar 08 '18 at 10:33
  • This is written for Python3. For Python2 it should not need changes, as far as I now, but I did not test it with Python 2. – Ralf Mar 08 '18 at 10:34
  • so what is the diiference between raw input and input functions –  Mar 08 '18 at 10:36
  • You could do a little bit googling for yourself and find the definitions in the documentation: [Python3 input()](https://docs.python.org/3/library/functions.html#input), [Python2 input()](https://docs.python.org/2/library/functions.html#input) and [Python2 raw_input()](https://docs.python.org/2/library/functions.html#raw_input) or in [Stackoverflow](https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) – Ralf Mar 08 '18 at 10:52