Почему на плате отображается только один x в консоли, и почему я не могу переключиться с x на o? - PullRequest
1 голос
/ 18 апреля 2020

Всякий раз, когда я пытаюсь переключиться с x на o, используя глобальную переменную, я получаю сообщение об ошибке «Поворот не определен». Таким образом, я переместил все в одну функцию, чтобы избавиться от необходимости глобальной, но она все еще не работает. Затем, после настройки некоторых отпечатков, я понял, что при нажатии нескольких полей доска [] переписывается полностью вместо того, чтобы просто присвоить значение и сохранить его. Как я могу это исправить? Для получения более четкого изображения проверьте консоль после нажатия 2 различных квадратов.

import turtle

from turtle import *

pen = turtle.Turtle()
pen.speed(0)
setup(601,601)
#Creating Menu option buttons
def button(length):
    for i in range(4):
        pen.forward(length)
        pen.left(90)

def column(n, length):
    pen.penup()
    pen.goto(-100,250)
    pen.pendown()
    pen.left(270)
    for i in range(n):
        button(length)
        pen.forward(length)
    pen.penup()
    pen.left(90)
    pen.forward(n * length)
    pen.left(180)
    pen.pendown()

column(5, 100)

#Menu Options
pen.penup()
pen.goto(-100, 190)
pen.write("START GAME", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-75, 90)
pen.write("RULES", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-97, -10)
pen.write("HIGH SCORE", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-65, -110)
pen.write("FAQ", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-93, -210)
pen.write("QUIT GAME", font=("Arial",12,"normal"))


def runGame():
    pen = turtle.Turtle()
    speed(0)
    setup(1366,738)
    title("Group 3's tictactoe")
    pensize(15)


    #Rows
    def dRow():
        up()
        goto(-500,-100)
        down()
        forward(1000)
        up()
        goto(-500, 100)
        down()
        forward(1000)
    dRow()
    #columns
    def dCol():
        up()
        goto(-175,-400)
        left(90)
        down()
        forward(1000)
        up()
        goto(175, -400)
        down()
        forward(1000)
    dCol()

    #Win conditions
    def place(x,y):
        global turn
        #Creating Board
        board = ["","","",
                 "","","",
                 "","","",] 
        turn = "X"
        point = ""

        #create X's
        def Xs(x, y):
            up()
            goto(x+30, y-35)
            setheading(130)
            down()
            forward(100)
            up()
            goto(x+30, y+40)
            setheading(230)
            down()
            forward(100)
            up()
            print(x, y)

        #Create O's
        def Os(x, y):
            up()
            goto(x,y-80)
            setheading(0)
            down()
            circle(80)
            up()
            print(x, y)

        #Check what square was clicked and assign that an (x or O) value to that point
        if -526<x<-182 and 360>y>107:
            point = 0
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -168<x<167 and 360>y>107:
            point = 1
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif 182<x<504 and 360>y>107:
            point = 2
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -506<x<-184 and 92>y>-92:
            point = 3
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -167<x<167 and 92>y>-92:
            point = 4
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        elif 185<x<505 and 92>y>-92:
            point = 5
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -504<x<-182 and -108>y>-360:
            point = 6
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -167<x<166 and -108>y>-360:
            point = 7
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        elif 185<x<531 and -108>y>-360:
            point = 8
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        else:
            print("Do something")


        print("The current entire board is: ",board)

        def drawPieces(board):
            for piece in board:
                if piece == "X":
                    Xs(x,y)
                elif board == "O":
                    Os(x,y)

        def clicked(x,y):
            if board[0] == "X" and board[4] == "X" and board[8] == "X":
                style = ('Courier', 80, 'bold')
                write('You WIN!', font=style, align='center')
            else:
                global turn
                if turn == "X":
                    turn = "O"
                    drawPieces(board)
                else:
                    turn = "X"
                    drawPieces(board)
                print("This turn is: ",turn)
        clicked(x, y)



    onscreenclick(place)
    mainloop()

#Making options clickable
def btnclick(x,y):
    if -100 < x < 1 and 250 > y > 150:
        print("Start Game")
        print(x, y)
        turtle.clearscreen()
        runGame()

    elif -100 < x < 1 and 150 > y > 50:
        print("Rules")
        print(x, y)
        turtle.clearscreen()
        screen = turtle.Screen()
        answer = screen.textinput("Welcome to Our GAME!", "Whats your name?")

    elif -100 < x < 1 and 50 > y > -50:
        print("Highscore")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -50 > y > -150:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -150 > y > -250:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -250 > y > -350:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    else:
        print("Click One Of The Options!")
        print(x, y)



turtle.onscreenclick(btnclick, 1)
turtle.listen()

turtle.done()

1 Ответ

2 голосов
/ 18 апреля 2020

Основная проблема в вашем коде заключается в том, что borad и turn инициализируются каждый раз, когда вызывается place.

def place(x,y):
        global turn
        #Creating Board
        board = ["","","",
                 "","","",
                 "","","",] 
        turn = "X"
        point = ""

Таким образом, новая доска создается и ход устанавливается "X" каждый раз, когда начинается новый ход.

Создайте bord и turn в глобальном пространстве имен и используйте его в place:

#Creating Board
board = ["","","",
              "","","",
              "","","",] 
turn = "X"

def runGame():
    # [...]

    #Win conditions
    def place(x,y):
        global turn, board

        point = ""

        #create X's
        # [...]

Кроме того, есть некоторые проблемы в clicked. Используйте глобальные переменные board и turn в clicked. drawPieces не работает вообще, потому что x и y никогда не меняются, и все фигуры рисуются в одной и той же позиции. Достаточно нарисовать новый кусок. Нарисуйте на фигуре Xs соответственно Os в clicked:

def runGame():
    # [...]

    #Win conditions
    def place(x,y):
        global turn, board

        point = ""
        # [...]

        def clicked(x,y):
            global board, turn
            if board[0] == "X" and board[4] == "X" and board[8] == "X":
                style = ('Courier', 80, 'bold')
                write('You WIN!', font=style, align='center')
            else:
                if turn == "X":
                    Xs(x,y)
                    turn = "O"
                else:
                    Os(x,y)
                    turn = "X"
                print("This turn is: ",turn)
        clicked(x, y)

Полный код:

import turtle

from turtle import *

pen = turtle.Turtle()
pen.speed(0)
setup(601,601)
#Creating Menu option buttons
def button(length):
    for i in range(4):
        pen.forward(length)
        pen.left(90)

def column(n, length):
    pen.penup()
    pen.goto(-100,250)
    pen.pendown()
    pen.left(270)
    for i in range(n):
        button(length)
        pen.forward(length)
    pen.penup()
    pen.left(90)
    pen.forward(n * length)
    pen.left(180)
    pen.pendown()

column(5, 100)

#Menu Options
pen.penup()
pen.goto(-100, 190)
pen.write("START GAME", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-75, 90)
pen.write("RULES", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-97, -10)
pen.write("HIGH SCORE", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-65, -110)
pen.write("FAQ", font=("Arial",12,"normal"))

pen.penup()
pen.goto(-93, -210)
pen.write("QUIT GAME", font=("Arial",12,"normal"))

#Creating Board
board = ["","","",
              "","","",
              "","","",] 
turn = "X"

def runGame():
    pen = turtle.Turtle()
    speed(0)
    setup(1366,738)
    title("Group 3's tictactoe")
    pensize(15)

    #Rows
    def dRow():
        up()
        goto(-500,-100)
        down()
        forward(1000)
        up()
        goto(-500, 100)
        down()
        forward(1000)
    dRow()
    #columns
    def dCol():
        up()
        goto(-175,-400)
        left(90)
        down()
        forward(1000)
        up()
        goto(175, -400)
        down()
        forward(1000)
    dCol()

    #Win conditions
    def place(x,y):
        global turn, board

        point = ""

        #create X's
        def Xs(x, y):
            up()
            goto(x+30, y-35)
            setheading(130)
            down()
            forward(100)
            up()
            goto(x+30, y+40)
            setheading(230)
            down()
            forward(100)
            up()
            print(x, y)

        #Create O's
        def Os(x, y):
            up()
            goto(x,y-80)
            setheading(0)
            down()
            circle(80)
            up()
            print(x, y)

        #Check what square was clicked and assign that an (x or O) value to that point
        if -526<x<-182 and 360>y>107:
            point = 0
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -168<x<167 and 360>y>107:
            point = 1
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif 182<x<504 and 360>y>107:
            point = 2
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -506<x<-184 and 92>y>-92:
            point = 3
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -167<x<167 and 92>y>-92:
            point = 4
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        elif 185<x<505 and 92>y>-92:
            point = 5
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -504<x<-182 and -108>y>-360:
            point = 6
            print("This is square: ",point)
            board[int(point)] = turn
            print("this board space is: ", board[point], board)
        elif -167<x<166 and -108>y>-360:
            point = 7
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        elif 185<x<531 and -108>y>-360:
            point = 8
            print("This is square: ",point)
            board[int(point)] = board[int(point)] + str(turn)
            print("this board space is: ", board[point], board)
        else:
            print("Do something")


        print("The current entire board is: ",board)

        def drawPieces(board):
            for piece in board:
                if piece == "X":
                    Xs(x,y)
                elif piece == "O":
                    Os(x,y)

        def clicked(x,y):
            global board, turn
            if board[0] == "X" and board[4] == "X" and board[8] == "X":
                style = ('Courier', 80, 'bold')
                write('You WIN!', font=style, align='center')
            else:
                if turn == "X":
                    Xs(x,y)
                    turn = "O"
                else:
                    Os(x,y)
                    turn = "X"
                print("This turn is: ",turn)
        clicked(x, y)



    onscreenclick(place)
    mainloop()

#Making options clickable
def btnclick(x,y):
    if -100 < x < 1 and 250 > y > 150:
        print("Start Game")
        print(x, y)
        turtle.clearscreen()
        runGame()

    elif -100 < x < 1 and 150 > y > 50:
        print("Rules")
        print(x, y)
        turtle.clearscreen()
        screen = turtle.Screen()
        answer = screen.textinput("Welcome to Our GAME!", "Whats your name?")

    elif -100 < x < 1 and 50 > y > -50:
        print("Highscore")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -50 > y > -150:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -150 > y > -250:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    elif -100 < x < 1 and -250 > y > -350:
        print("Hi")
        print(x, y)
        turtle.clearscreen()
    else:
        print("Click One Of The Options!")
        print(x, y)



turtle.onscreenclick(btnclick, 1)
turtle.listen()

turtle.done()
...