Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I built Tic-Tac-To
#1
I have been studying python in the last 2 weeks for many hours and last night I did the game Tic-Tac-To. I'm a beginner developer so I don't know whether my code is good enough. I want to know from you what I need to improve in my code and what is the next challenge I can try to build for practicing
?It's normal that I have no Idea what I did in my code but it works perfectly
I don't know exactly what I did in my code because it took me about 5 hours to build it and I need to review the code again after a good sleeping because I stayed up all night
sorry for my bad english I'm not a native speaker
this is link to the code
https://github.com/danielzZ1234/TicTacTo...Ik6G8x4zNo
Reply
#2
Hello and welcome to Python and the forums!
We prefer people to post code here directly. Could you copy the code in this thread? Be sure to use [python] code tags.
Reply
#3
(Apr-01-2020, 12:09 PM)dsad12 Wrote: I have been studying python in the last 2 weeks for many hours and last night I did the game Tic-Tac-To. I'm a beginner developer so I don't know whether my code is good enough. I want to know from you what I need to improve in my code and what is the next challenge I can try to build for practicing
?It's normal that I have no Idea what I did in my code but it works perfectly
I don't know exactly what I did in my code because it took me about 5 hours to build it and I need to review the code again after a good sleeping because I stayed up all night
sorry for my bad english I'm not a native speaker
this is link to the code
https://github.com/danielzZ1234/TicTacTo...Ik6G8x4zNo
 
import tkinter as tk
root = tk.Tk()
root.title("Welcome To Tic Tac Game")
root.geometry("500x500")
turn = 0
x = 0
y = 0
row = 0
col = 0
apn =0
draw = 0
btn = []
btn_text = []
Xgame = [ [0,0,0],[0,0,0],[0,0,0] ]
Ygame =  [[0,0,0],[0,0,0],[0,0,0]]
while apn < 9:
      btn.append(' ')
      btn_text.append('')
      btn_text[apn] = tk.StringVar()
      apn = apn + 1
def make3DarrayX(y):
    if y >= 0 and y <=2:
       Xgame[0][int(y/1)] = 1
    elif y>=3 and y <=5:
         Xgame[1][y-3] = 1
    elif y>=6 and y<=8:
        Xgame[2][y-6] = 1
def make3DarrayY(y):
    if y >= 0 and y <=2:
       Ygame[0][int(y/1)] = 1
    elif y>=3 and y <=5:
       Ygame[1][y-3] = 1
    elif y>=6 and y<=8:
        Ygame[2][y-6] = 1
def checkifXwon():
    global draw
    draw = draw + 1
    y = 0
    x = 0
    while y < 3:
      while x < 3:
         if Xgame[y][0] == 1 and Xgame[y][1] == 1 and Xgame[y][2] ==1:
             label = tk.Label(root, text="X won")
             label.grid(row=9,column=0)
         if Xgame[0][y] == 1 and Xgame[1][y] == 1 and Xgame[2][y] ==1:
             label = tk.Label(root, text="X won")
             label.grid(row=9,column=0)
         if Xgame[0][0] == 1 and Xgame[1][1] == 1 and Xgame[2][2] ==1:
             label = tk.Label(root, text="X won")
             label.grid(row=9,column=0)
         if Xgame[0][2] == 1 and Xgame[1][1] == 1 and Xgame[2][0] ==1:
             label = tk.Label(root, text="X won")
             label.grid(row=9,column=0)
         x = x+ 1
      if draw == 9:
          label = tk.Label(root, text="DRAW")
          label.grid(row=9,column=0)
          return 0
      x = 0
      y = y+1
def checkifYwon():
    global draw
    draw = draw + 1
    y = 0
    x = 0
    while y < 3:
        while x < 3:
            if Ygame[y][0] == 1 and Ygame[y][1] == 1 and Ygame[y][2] ==1:
                label = tk.Label(root, text="O WON")
                label.grid(row=9,column=0)
            if Ygame[0][y] == 1 and Ygame[1][y] == 1 and Ygame[2][y] ==1:
                label = tk.Label(root, text="O WON")
                label.grid(row=9,column=0)
            if Ygame[0][0] == 1 and Ygame[1][1] == 1 and Ygame[2][2] ==1:
                label = tk.Label(root, text="O WON")
                label.grid(row=9,column=0)
            if Ygame[0][2] == 1 and Ygame[1][1] == 1 and Ygame[2][0] ==1:
                label = tk.Label(root, text="O WON")
                label.grid(row=9,column=0)
            x = x+ 1
        if draw == 9:
            label = tk.Label(root, text="DRAW")
            label.grid(row=9,column=0)
        x = 0
        y = y+1
def update_btn_text(y):
    global turn
    global Xgame
    global Ygame
    turn = turn + 1
    if turn%2==1:
        btn_text[y].set("X")
        make3DarrayX(y)
        checkifXwon()
    if turn%2==0:
       btn_text[y].set("O")
       make3DarrayY(y)
       checkifYwon()
item=0
while y < 9:
     btn[y] = tk.Button(root,text=item, textvariable=btn_text[y], command = lambda s=item: update_btn_text(s),height = 9, width =18)
     btn_text[y].set('')
     item = item + 1
     y = y+1
while row < 3:
    while col < 3:
        btn[x].grid(row = row, column=col, sticky = 'nesw')
        col = col +1
        x = x+1
    col =0
    row = row + 1
label = tk.Label(root, text="")
label.grid(row=9,column=0)
root.mainloop()
Reply
#4
a couple things to improve-
1. when I start your script you set the geometry to 500X500 which
cuts off the button on the left and doesn't show the label on
the bottom- my first game I didn't see your win label: just increase the size.
2. Disable the button after it's been selected. state= 'disabled'
3. when someone wins it allows extra move figure out an end. Possibly
create a main function checking win or loss status and restarting game.
4. After that work on AI playing against the computer sometimes it's hard to
find a player.
Over all a good start. best of luck-
Reply
#5
The only problem is the game is not breaking when someone wins. It just continuous until all spaces are filled and it says draw. Please fix that. Goodluck
Reply
#6
(Apr-01-2020, 12:09 PM)dsad12 Wrote: I have been studying python in the last 2 weeks for many hours and last night I did the game Tic-Tac-To. I'm a beginner developer so I don't know whether my code is good enough. I want to know from you what I need to improve in my code and what is the next challenge I can try to build for practicing
?It's normal that I have no Idea what I did in my code but it works perfectly
I don't know exactly what I did in my code because it took me about 5 hours to build it and I need to review the code again after a good sleeping because I stayed up all night
sorry for my bad english I'm not a native speaker
this is link to the code
https://github.com/danielzZ1234/TicTacTo...Ik6G8x4zNo
The problems seems to be that, if a player wins, it doesn't stop running/start a new game or whatever you want it to do. That is one of the problems. Another problem is, I'm not sure if you meant to do it or not, suppose there is a game board, and I put X in the center. However, if the other person wishes, he can press the center area, and the X changes to O. Please tend to those problems. Otherwise, as of now everything else is fine. If you need help, go through these Tic Tac Toe games in our very own forum
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#7
def status_print(game):
    print("\n")
    print(game[0])
    print(game[1])
    print(game[2])





def entry_check(num, XO, entry, valid_entries):
    player_entry = input(f"Player {num}, enter positional number(1-9) of {XO}: ")
    if player_entry in entry:
        print("\nSorry! That position is already taken. Try again\n")
        return None

    elif player_entry in valid_entries:
        return player_entry
    else:
        print("\nonly 1-9 numbers are allowed. Try again\n")
        return None


def player_win(num, XO):
    print(f"Player {num} won ({XO}-{XO}-{XO})!!")
    print("Congratulations!!")


def start_game():
    new_game = [
        ['1', '2', '3'],
        ['4', '5', '6'],
        ['7', '8', '9']
    ]
    game_dict = {'1': (0, 0), '2': (0, 1), '3': (0, 2),
                 '4': (1, 0), '5': (1, 1), '6': (1, 2),
                 '7': (2, 0), '8': (2, 1), '9': (2, 2)}

    status_print(new_game)
    result_pending = True
    game = new_game.copy()
    entry_count = 0
    valid_entries = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    entry = []
    while result_pending or entry_count < 5:
        while True:
            player_1 = entry_check(1, 'X', entry, valid_entries)
            if player_1:
                break
        entry.append(player_1)
        entry_count += 1
        x, y = game_dict.get(player_1)
        game[x].pop(y)
        game[x].insert(y, 'X')
        status_print(game)
        any_rowX = list((game[0].count('X'), game[1].count('X'), game[2].count('X')))
        column1 = list((game[0][0], game[1][0], game[2][0]))
        column2 = list((game[0][1], game[1][1], game[2][1]))
        column3 = list((game[0][2], game[1][2], game[2][2]))
        any_columnX = list((column1.count('X'), column2.count('X'), column3.count('X')))
        diagonal1 = list((game[0][0], game[1][1], game[2][2]))
        diagonal2 = list((game[2][0], game[1][1], game[0][2]))
        any_diagonalX = list((diagonal1.count('X'), diagonal2.count('X')))

        if 3 in any_rowX or 3 in any_columnX or 3 in any_diagonalX:
            print("Player 1 won (X-X-X)!!")
            print("Congratulations!!")
            break
        if entry_count == 5:
            print("Drawn")
            break

        while True:
            player_2 = entry_check(2, 'O', entry, valid_entries)
            if player_2:
                break
        entry.append(player_2)
        x, y = game_dict.get(player_2)
        game[x].pop(y)
        game[x].insert(y, 'O')
        status_print(game)
        any_rowO = list((game[0].count('O'), game[1].count('O'), game[2].count('O')))
        column1 = list((game[0][0], game[1][0], game[2][0]))
        column2 = list((game[0][1], game[1][1], game[2][1]))
        column3 = list((game[0][2], game[1][2], game[2][2]))
        any_columnO = list((column1.count('O'), column2.count('O'), column3.count('O')))
        diagonal1 = list((game[0][0], game[1][1], game[2][2]))
        diagonal2 = list((game[2][0], game[1][1], game[0][2]))
        any_diagonalO = list((diagonal1.count('O'), diagonal2.count('O')))

        if 3 in any_rowO or 3 in any_columnO or 3 in any_diagonalO:
            print("Player 2 won (O-O-O)!!")
            print("Congratulations!!")
            break
    play_wish = input("Want to play again?(Y/N): ").upper()
    if play_wish == "Y":
        start_game()
    else:
        print("Thank you for playing")

print("\nLet's Play Tic-Tac-Toe Game")
start_game()
I have coded this same game but i haven't learn GUI implementation. Just like to share my code for reviews instead of making new thread.
Professional Dentist(32years) fell in love with Python during COVID-19 Lockdown.

"Nothing can stop you from learning new things except your own will"

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020