Python Forum
Type Error: bad operand type for unary +: 'str'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type Error: bad operand type for unary +: 'str'
#1
Hello everyone, I'm making a dynamic Tic Tac Toe game, I need to get in the practice.
I'm getting this type error and I am not sure how to resolve it. It came up when i modified the code to add a bit of color from lines 62 to 70. I'm assuming that's where the issue is

import itertools
from colorama import init, Fore, Back, Style

init()


def win(current_game):
    def all_same(l):
        if l.count(l[0]) == len(l) and l[0] != 0:
            return True
        else:
            return False

    # Horizontal
    for row in game:
        print(row)
        if all_same(row):
            print(f"Player {row[0]} is the winner horizontally!")
            return True

    # Diagonal
    diags = []
    for col, row in enumerate(reversed(range(len(game)))):
        diags.append(game[row][col])
    if all_same(diags):
        print(f"Player {diags[0]} is the winner diagonally (/)")
        return True

    diags = []
    for ix in range(len(game)):
        diags.append(game[ix][ix])
    if all_same(diags):
        print(f"Player {diags[0]} is the winner diagonally (\\)")
        return True

    # Vertical
    for col in range(len(game)):

        check = []

        for row in game:
            check.append(row[col])

        if all_same(check):
            print(f"Player {check[0]} is the winner vertically!")
            return True

    return False


def game_board(game_map, player=0, row=0, column=0, just_display=False):
    try:
        if game_map[row][column] != 0:
            print("Position taken")
            return game_map, False
        print("   " + "  ".join([str(i) for i in range(len(game_map))]))
        if not just_display:
            game_map[row][column] = player

        for count, row in enumerate(game_map):

            colored_row = ""
            for item in row:
                if item == 0:
                    colored_row += "   "
                elif item == 1:
                    colored_row += Fore.GREEN + ' X ' + + Style.RESET_ALL
                elif item == 2:
                    colored_row += Fore.MAGENTA + ' O ' + + Style.RESET_ALL
            print(count, colored_row)

        return game_map, True

    except IndexError as e:
        print("Error: Make sure you input row/column as 0 1 or 2?", e)
        return game_map, False

    except Exception as e:
        print("Big Whoopsie!", e)
        return game_map, False


play = True
players = [1, 2]

while play:
    game_size = int(input("What size game do you want to play? "))
    game = [[0 for i in range(game_size)] for i in range(game_size)]

    game_won = False
    game, _ = game_board(game, just_display=True)
    player_choice = itertools.cycle([1, 2])
    while not game_won:
        current_player = next(player_choice)
        print(f"Current Player: {current_player}")
        played = False

        while not played:
            column_choice = int(input("What column do you want to play? (0, 1, 2) "))
            row_choice = int(input("What row do you want to play? (0, 1, 2) "))
            game, played = game_board(game, current_player, row_choice, column_choice)

        if win(game):
            game_won = True
            again = input("Thegame is over Do you want to play again? (y/n) ")
            if again.lower() == "y":
                print("restarting... ")
            elif again.lower() == "n":
                print("Au revoir!")
                play = False
            else:
                print("Not valid!")
                play = False
Thank you
Reply
#2
(Aug-12-2019, 04:00 AM)Psypher1 Wrote: I'm assuming that's where the issue is
The error message gives you detailed information where and what is wrong.
So when asking for help providing this error message is a vital thing to do.
Without we can only guess that likely here
                elif item == 1:
                    colored_row += Fore.GREEN + ' X ' + + Style.RESET_ALL
                elif item == 2:
                    colored_row += Fore.MAGENTA + ' O ' + + Style.RESET_ALL
you need to convert the constants Fore.<color> and Style.RESET_ALL into strings
OR if these are strings than the error is due to the double + + in these lines.
                elif item == 1:
                    colored_row += str(Fore.GREEN) + ' X ' + str(Style.RESET_ALL)
                elif item == 2:
                    colored_row += str(Fore.MAGENTA) + ' O ' + str(Style.RESET_ALL)
Reply
#3
Okay, I'll remember to include the message next time.

Thank you for the help
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to get a removable disc type in drive Daring_T 12 971 Feb-11-2024, 08:55 AM
Last Post: Gribouillis
  all of attributes and methods related to a special type akbarza 4 425 Jan-19-2024, 01:11 PM
Last Post: perfringo
  Precision with Decimal Type charlesrkiss 9 667 Jan-18-2024, 06:30 PM
Last Post: charlesrkiss
  How to detect this type of images AtharvaZ 0 312 Jan-02-2024, 03:11 PM
Last Post: AtharvaZ
  problem with help(type(self)) in Idle akbarza 1 432 Dec-26-2023, 12:31 PM
Last Post: Gribouillis
  Static type checking with PyPy pitosalas 1 391 Dec-14-2023, 09:29 PM
Last Post: deanhystad
  How does sqlite3 module determine value type mirlos 2 894 Dec-12-2023, 09:37 AM
Last Post: mirlos
  mypy, type aliases and type variables tomciodev 1 657 Oct-18-2023, 10:08 AM
Last Post: Larz60+
  ValueError: Unknown label type: 'continuous-multioutput' hobbyist 7 1,193 Sep-13-2023, 05:41 PM
Last Post: deanhystad
  determine parameter type in definition function akbarza 1 550 Aug-24-2023, 01:46 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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