Tkinter не может вызвать функцию (TicTacToe в tkinter) - PullRequest
0 голосов
/ 27 мая 2018

У меня проблема с моим кодом.Итак, я пытаюсь сделать игру TicTacToe, но я хочу, чтобы компьютер выбрал поле, чтобы поставить свой маркер.Я уже сделал код, где пользователь может поставить свой маркер, но я не могу решить проблему, когда он не выбирает поле для маркера компьютера.Вы можете увидеть мой код здесь.Y1, Y2, Y3 .... и т. Д. - это все функции, которые, когда вы нажимаете кнопку, изменяют ее.C1, C2, C3 .... и т. Д. - все коды для компьютера, чтобы поставить свой маркер.

import tkinter as tk
from tkinter import messagebox
import random

one_flag= True
two_flag= True
three_flag= True
four_flag= True
five_flag= True
six_flag= True
seven_flag= True
eight_flag= True
nine_flag= True
pk = tk.Tk()
frame = tk.Frame(pk)
frame.grid()
def X():
    print("test")
def Y1():
    global one_flag
    if one_flag:
        print("Your Marker Is Now On This Square")
        one.config(text="X",fg='red')
        one_flag = False
def Y2():
    global two_flag
    if two_flag:
        print("Your Marker Is Now On This Square")
        two.config(text="X",fg='red')
        two_flag = False
def Y3():
    global three_flag
    if three_flag:
        print("Your Marker Is Now On This Square")
        three.config(text="X",fg='red')
        three_flag = False
def Y4():
    global four_flag
    if four_flag:
        print("Your Marker Is Now On This Square")
        four.config(text="X",fg='red')
        four_flag = False
def Y5():
    global five_flag
    if five_flag:
        print("Your Marker Is Now On This Square")
        five.config(text="X",fg='red')
        five_flag = False
def Y6():
    global six_flag
    if six_flag:
        print("Your Marker Is Now On This Square")
        six.config(text="X",fg='red')
        six_flag = False
def Y7():
    global seven_flag
    if seven_flag:
        print("Your Marker Is Now On This Square")
        seven.config(text="X",fg='red')
        seven_flag = False
def Y8():
    global eight_flag
    if eight_flag:
        print("Your Marker Is Now On This Square")
        eight.config(text="X",fg='red')
        eight_flag = False
def Y9():
    global nine_flag
    if nine_flag:
        print("Your Marker Is Now On This Square")
        nine.config(text="X",fg='red')
        nine_flag = False
def C1():
    global one_flag
    if one_flag:
        print("The Computer's Marker Is Now On This Square")
        one.config(text="O",fg='blue')
        one_flag = False
def C2():
    global two_flag
    if two_flag:
        print("The Computer's Marker Is Now On This Square")
        two.config(text="O",fg='blue')
        two_flag = False
def C3():
    global three_flag
    if three_flag:
        print("The Computer's Marker Is Now On This Square")
        three.config(text="O",fg='blue')
        three_flag = False
def C4():
    global four_flag
    if four_flag:
        print("The Computer's Marker Is Now On This Square")
        four.config(text="O",fg='blue')
        four_flag = False
def C5():
    global five_flag
    if five_flag:
        print("The Computer's Marker Is Now On This Square")
        five.config(text="O",fg='blue')
        five_flag = False
def C6():
    global six_flag
    if six_flag:
        print("The Computer's Marker Is Now On This Square")
        six.config(text="O",fg='blue')
        six_flag = False
def C7():
    global seven_flag
    if seven_flag:
        print("The Computer's Marker Is Now On This Square")
        seven.config(text="O",fg='blue')
        seven_flag = False
def C8():
    global eight_flag
    if eight_flag:
        print("The Computer's Marker Is Now On This Square")
        eight.config(text="O",fg='blue')
        eight_flag = False
def C9():
    global nine_flag
    if nine_flag:
        print("The Computer's Marker Is Now On This Square")
        nine.config(text="O",fg='blue')
        nine_flag = False

one=tk.Button(pk,
            text="1",
            fg="blue",
            command=Y1)
two=tk.Button(pk,
            text="2",
            fg="blue",
            command=Y2)
three=tk.Button(pk,
            text="3",
            fg="blue",
            command=Y3)
four=tk.Button(pk,
            text="4",
            fg="blue",
            command=Y4)
five=tk.Button(pk,
            text="5",
            fg="blue",
            command=Y5)
six=tk.Button(pk,
            text="6",
            fg="blue",
            command=Y6)
seven=tk.Button(pk,
            text="7",
            fg="blue",
            command=Y7)
eight=tk.Button(pk,
            text="8",
            fg="blue",
            command=Y8)
nine=tk.Button(pk,
            text="9",
            fg="blue",
            command=Y9)

one.grid(row=0,column=0)
two.grid(row=0,column=1)
three.grid(row=0,column=2)
four.grid(row=1,column=0)
five.grid(row=1,column=1)
six.grid(row=1,column=2)
seven.grid(row=2,column=0)
eight.grid(row=2,column=1)
nine.grid(row=2,column=2)


pk.mainloop()
ho=one_flag,two_flag,three_flag,four_flag,five_flag,six_flag,seven_flag,eight_flag,nine_flag

boxes=['one','two','three','four','five','six','seven','eight','nine']
if one_flag==False:
    boxes.remove('one')
if two_flag==False:
    boxes.remove('two')
if three_flag==False:
    boxes.remove('three')
if four_flag==False:
    boxes.remove('four')
if five_flag==False:
    boxes.remove('five')
if six_flag==False:
    boxes.remove('six')
if seven_flag==False:
    boxes.remove('seven')
if eight_flag==False:
    boxes.remove('eight')
if nine_flag==False:
    boxes.remove('nine')

cs=random.choice(boxes)
if cs=='one':
    C1()
if cs=='two':
    C2()
if cs=='three':
    C3()
if cs=='four':
    C4()
if cs=='five':
    C5()
if cs=='six':
    C6()
if cs=='seven':
    C7()
if cs=='eight':
    C8()
if cs=='nine':
    C9()
print(boxes)

1 Ответ

0 голосов
/ 15 августа 2018

Так как вы importing random, я подумал, что вы хотите, чтобы компьютер выбирал поле случайным образом.Я отредактировал и улучшил ваш код.

Изменения:

  • Случайный выбор ящиков компьютера.
  • Цвет свободных ячеек green, тогда как цвет кнопки, выбранной компьютером, blue.
  • Кнопки, выбранные компьютером, не могут быть нажаты снова.
  • Реалистичное нажатие кнопки на компьютере

Работа со случайным выбором:

Каждый раз, когда мы нажимаем кнопку, следующий ход идет с компьютера.Поэтому, когда мы нажимаем кнопку, она запускает функцию.Функция составляет список всех кнопок в виде [True,True,False.....].После этого появляется цикл while True, и элемент случайным образом выбирается из ["0","1"] в цикле for, варьирующемся от 0 до 9.Если выходные данные равны 1, то это return s индекс элемента (текущее значение цикла).После этого он видит, какая случайная кнопка для компьютера выбрана.if returned == 0: Выполнить C1(), if returned == 1: Выполнить C2() и т. Д.

Код:

import tkinter as tk
from tkinter import messagebox
import random

one_flag= True
two_flag= True
three_flag= True
four_flag= True
five_flag= True
six_flag= True
seven_flag= True
eight_flag= True
nine_flag= True
pk = tk.Tk()
frame = tk.Frame(pk)
frame.grid()
def pressed(button):
    button["relief"] = tk.SUNKEN
    pk.after(100,func = lambda : button.config(relief= tk.RAISED,state="disabled"))
def select_r():
    try:del avalist
    except:pass
    avalist = [one_flag,two_flag,three_flag,four_flag,five_flag,six_flag,seven_flag,eight_flag,nine_flag]
    print(avalist)
    while True:
        for x in range(0,9):
            toutput = random.choice(["0","1"])
            if toutput == "1" and avalist[x] != False:return x
            y = 0
            for a in avalist:
                if a == False:y += 1
            if y == 9:return None
def select_r2():
    option = select_r()
    if option == 0:C1()
    if option == 1:C2()
    if option == 2:C3()
    if option == 3:C4()
    if option == 4:C5()
    if option == 5:C6()
    if option == 6:C7()
    if option == 7:C8()
    if option == 8:C9()
def X():
    print("test")
def Y1():
    global one_flag
    if one_flag:
        print("Your Marker Is Now On This Square")
        one.config(text="X",fg='red')
        one_flag = False
        select_r2()
def Y2():
    global two_flag
    if two_flag:
        print("Your Marker Is Now On This Square")
        two.config(text="X",fg='red')
        two_flag = False
        select_r2()
def Y3():
    global three_flag
    if three_flag:
        print("Your Marker Is Now On This Square")
        three.config(text="X",fg='red')
        three_flag = False
        select_r2()
def Y4():
    global four_flag
    if four_flag:
        print("Your Marker Is Now On This Square")
        four.config(text="X",fg='red')
        four_flag = False
        select_r2()
def Y5():
    global five_flag
    if five_flag:
        print("Your Marker Is Now On This Square")
        five.config(text="X",fg='red')
        five_flag = False
        select_r2()
def Y6():
    global six_flag
    if six_flag:
        print("Your Marker Is Now On This Square")
        six.config(text="X",fg='red')
        six_flag = False
        select_r2()
def Y7():
    global seven_flag
    if seven_flag:
        print("Your Marker Is Now On This Square")
        seven.config(text="X",fg='red')
        seven_flag = False
        select_r2()
def Y8():
    global eight_flag
    if eight_flag:
        print("Your Marker Is Now On This Square")
        eight.config(text="X",fg='red')
        eight_flag = False
        select_r2()
def Y9():
    global nine_flag
    if nine_flag:
        print("Your Marker Is Now On This Square")
        nine.config(text="X",fg='red')
        nine_flag = False
        select_r2()
def C1():
    global one_flag
    if one_flag:
        print("The Computer's Marker Is Now On This Square")
        one.config(text="O",fg='blue')
        pressed(one)
        one_flag = False
def C2():
    global two_flag
    if two_flag:
        print("The Computer's Marker Is Now On This Square")
        two.config(text="O",fg='blue')
        pressed(two)
        two_flag = False
def C3():
    global three_flag
    if three_flag:
        print("The Computer's Marker Is Now On This Square")
        three.config(text="O",fg='blue')
        pressed(three)
        three_flag = False
def C4():
    global four_flag
    if four_flag:
        print("The Computer's Marker Is Now On This Square")
        four.config(text="O",fg='blue')
        pressed(four)
        four_flag = False
def C5():
    global five_flag
    if five_flag:
        print("The Computer's Marker Is Now On This Square")
        five.config(text="O",fg='blue')
        pressed(five)
        five_flag = False
def C6():
    global six_flag
    if six_flag:
        print("The Computer's Marker Is Now On This Square")
        six.config(text="O",fg='blue')
        pressed(six)
        six_flag = False
def C7():
    global seven_flag
    if seven_flag:
        print("The Computer's Marker Is Now On This Square")
        seven.config(text="O",fg='blue')
        pressed(seven)
        seven_flag = False
def C8():
    global eight_flag
    if eight_flag:
        print("The Computer's Marker Is Now On This Square")
        eight.config(text="O",fg='blue')
        pressed(eight)
        eight_flag = False
def C9():
    global nine_flag
    if nine_flag:
        print("The Computer's Marker Is Now On This Square")
        nine.config(text="O",fg='blue')
        pressed(nine)
        nine_flag = False

one=tk.Button(pk,
            text="1",
            fg='green',
            command=Y1)
two=tk.Button(pk,
            text="2",
            fg='green',
            command=Y2)
three=tk.Button(pk,
            text="3",
            fg='green',
            command=Y3)
four=tk.Button(pk,
            text="4",
            fg='green',
            command=Y4)
five=tk.Button(pk,
            text="5",
            fg='green',
            command=Y5)
six=tk.Button(pk,
            text="6",
            fg='green',
            command=Y6)
seven=tk.Button(pk,
            text="7",
            fg='green',
            command=Y7)
eight=tk.Button(pk,
            text="8",
            fg='green',
            command=Y8)
nine=tk.Button(pk,
            text="9",
            fg='green',
            command=Y9)

one.grid(row=0,column=0)
two.grid(row=0,column=1)
three.grid(row=0,column=2)
four.grid(row=1,column=0)
five.grid(row=1,column=1)
six.grid(row=1,column=2)
seven.grid(row=2,column=0)
eight.grid(row=2,column=1)
nine.grid(row=2,column=2)


pk.mainloop()

Анимация:

Running

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...