Forum Archive

Trying to write tic-tac-toe

Karina

I'm trying to write tic-tac-toe on pythonista, so that 'O' will be in blue color and 'X' in red. The blue color works, but the red doesn't and I can't understand why. Here's my code
Thank you very much for help

import console

x_o = [1,2,3,4,5,6,7,8,9]
turn = ['X', 'O']

class Color:
    def __init__(self, value):
        self.value = value
        self.red = 1
        self.green = 1
        self.blue = 1

    def switch_color(self):
        #all numbers will be white, 'X' - red, 'O' - blue
        if self.value == 'X':
            self.red, self.green, self.blue = 1, 0, 0
            print(self.__dict__)
        if self.value == 'O':
            self.red, self.green, self.blue = 0, 0, 1
        else:
            self.red, self.green, self.blue = 1, 1, 1
        console.set_color(self.red, self.green, self.blue)

    @classmethod    
    #asks where to put 'X'/'O' and replaces a number with it, making it an object of Color
    def putXO(cls, t):
        place = int(input(f'Where to put {t}? '))
        x_o[place-1] = cls(t)



def to_Color(list):
    #makes all numbers in list to be Color objects
    for i in range(len(list)):
        list[i] = Color(list[i])

def printXO(list):
    #makes the symbols to be printed in the color they need to be
    for num, i in enumerate(list,1):
        i.switch_color()
        if num%3 == 0:
            print(i.value)
        else:
            print(i.value, end='  ')

to_Color(x_o)
while x_o:
    for t in turn:
        Color.putXO(t)
        printXO(x_o)
cvp

@Karina because for self.value = 'X', you fall in the else...
Replace

        if self.value == 'O': 

By

        elif self.value == 'O': 

And, to avoid invisible white (on white) texts, set


        else:
            self.red, self.green, self.blue = 0.5,0.5,0.5

Karina

Thank you a lot! And can you explain what happens in the two cases of if and elif?

cvp

@Karina for me, it is so obvious that it is not easy to explain in words 😢

if a == 1:
    code executed if a = 1
if a == 2:
    code executed if a = 2
else:
    code executed for a not 2, thus also for a = 1

if a == 1:
    code executed only for a = 1
elif a == 2:
    code executed only for a = 2
else:
    code executed for a not 1 nor 2
Karina

Okay, thanks anyway