1

I am beginning to learn Python and I simply copied an pasted this code to run in sublime text editor but it is showing three errors in line 163 and 30. Another error it is showing is as follows

File "C:\Users\JAYPA\Documents\Sublime_TicAI.py", line 164, in <module>
    `drawBoard()`
  File "C:\Users\JAYPA\Documents\Sublime_TicAI.py", line 31, in `drawBoard
    board_status[1], board_status[2], board_status[3]`))
  File "C:\Users\JAYPA\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-13: character maps to <undefined>

Can someone help me?

from random import randint, choice
from os import system as bash
from time import time


def intInput(StringToDisplay):
    # Simply checks that input is valid integer
    while True:
        try:
            x = int(input(StringToDisplay))
            return x
            break
        except ValueError:
            print('Input integer number, please')
        except Exception:
            print('Unexpected error or keyboard interrupt')


def drawBoard():
    print('\
 ╔═══╦═══╦═══╗\n\
 ║ {0} ║ {1} ║ {2} ║\n\
 ╠═══╬═══╬═══╣\n\
 ║ {3} ║ {4} ║ {5} ║\n\
 ╠═══╬═══╬═══╣\n\
 ║ {6} ║ {7} ║ {8} ║\n\
 ╚═══╩═══╩═══╝ '.format(
               board_status[7], board_status[8], board_status[9],
               board_status[4], board_status[5], board_status[6],     
               board_status[1], board_status[2], board_status[3]))


def askPlayerLetter():
    # Function that asks which letter player wants to use
    print('Do you want to be X or O?')
    Letter = input().upper()
    while Letter != 'X' and Letter != 'O':
        print('Please type appropriate symbol')
        Letter = input('Prompt: ').upper()
    if Letter == 'X':  # then X will be used by player; O by computer
        return ['X', 'O']
    else:
        return ['O', 'X']


def whoGoesFirst():
    # Timer used to count 0.75 seconds while displaying who goes first
    if randint(0, 1) == 0:
        CurrentTime, Timer = time(), time() + 0.75
        print('You go first')
        while Timer > CurrentTime:
            CurrentTime = time()
        return 'player'
    else:
        CurrentTime, Timer = time(), time() + 0.75
        print('Computer goes first')
        while Timer > CurrentTime:
            CurrentTime = time()
        return 'computer'


def makeMove(Board, Move, Letter):
    Board[Move] = Letter


def isSpaceFree(Board, Move):
    return Board[Move] == ' '


def playerMove():
    Move = 0
    while not (0 < Move < 10) or not (isSpaceFree(board_status, int(Move))):
        Move = intInput('Enter your move: ')
    return int(Move)


def isWinner(brd, lttr):
    # Returns a boolean value. brd (board) and lttr (letter) used to make
    # code block compact.
    return ((brd[7] == lttr and brd[8] == lttr and brd[9] == lttr) or
            (brd[4] == lttr and brd[5] == lttr and brd[6] == lttr) or
            (brd[1] == lttr and brd[2] == lttr and brd[3] == lttr) or
            (brd[7] == lttr and brd[5] == lttr and brd[3] == lttr) or
            (brd[9] == lttr and brd[5] == lttr and brd[1] == lttr) or
            (brd[7] == lttr and brd[4] == lttr and brd[1] == lttr) or
            (brd[8] == lttr and brd[5] == lttr and brd[2] == lttr) or
            (brd[9] == lttr and brd[6] == lttr and brd[3] == lttr))


def computerMove():
    '''
    Simple AI that checks
    1)Can computer win in the next move
    2)Can player win in the next move
    3)Is there any free corner
    4)Is center is free
    5)Is there any free side
    And returns a move digit

    '''


    for i in range(1, 10):
        Copy = board_status.copy()
        if isSpaceFree(Copy, i):
            makeMove(Copy, i, ComputerLetter)
            if isWinner(Copy, ComputerLetter):
                return i

    for i in range(1, 10):
        Copy = board_status.copy()
        if isSpaceFree(Copy, i):
            makeMove(Copy, i, PlayerLetter)
            if isWinner(Copy, PlayerLetter):
                return i

    move = randomMoveFromList([7, 9, 1, 3])
    if move is not None:
        return move

    if isSpaceFree(board_status, 5):
        return 5

    move = randomMoveFromList([8, 4, 2, 6])
    if move is not None:
        return move


def randomMoveFromList(MovesList):
    PossibleMoves = []
    for i in MovesList:
        if isSpaceFree(board_status, i):
            PossibleMoves.append(i)
    if len(PossibleMoves) != 0:
        return choice(PossibleMoves)
    else:
        return None


def isBoardFull():
    for i in range(1, 10):
        if isSpaceFree(board_status, i):
            return False
    return True


def playAgain():
    print('Do you want to play again? [y/N]')
    PlayAgainInput = input().lower()
    return (PlayAgainInput.startswith('y') or PlayAgainInput == '')

# "bash('clear')" function simply clears the screen of the terminal.
# If you want run this script on system that uses other shell then
# substitute "clear" with a command that your shell uses to clear the screen
# P.S. for windows it is "cls".

bash('clear')
print('Welcome to Tic Tac Toe')
PlayAgainWish = True
print('To win, you have to place 3 X-s or O-s in a row.\n\
Use NumPad to enter your move (!). Here is the key map.')
board_status = ['', 1, 2, 3, 4, 5, 6, 7, 8, 9]
drawBoard()
print('You have to be sure that you are making move to a free cell.\n\n')
PlayerLetter, ComputerLetter = askPlayerLetter()
while PlayAgainWish:
    bash('clear')
    board_status = 10 * [' ']
    turn = whoGoesFirst()
    while True:
        if turn == 'player':
            bash('clear')
            print('   YOUR MOVE')
            drawBoard()
            move = playerMove()
            makeMove(board_status, move, PlayerLetter)
            turn = 'computer'
            if isWinner(board_status, PlayerLetter):
                bash('clear')
                print('Hooray, you have won the game!')
                drawBoard()
                PlayAgainWish = playAgain()
                break
            elif isBoardFull():
                bash('clear')
                print("It's a tie!")
                drawBoard()
                PlayAgainWish = playAgain()
                break
        else:
            # All this dots and timers are used to make animation of
            # computer moving. You will understand if you will run the script.
            for i in ['', '.', '..', '...']:
                bash('clear')
                print(' Computer is making move' + i)
                drawBoard()
                CurrentTime, Timer = time(), time() + 0.15
                while Timer > CurrentTime:
                    CurrentTime = time()
                if i == '..':
                    move = computerMove()
                    makeMove(board_status, move, ComputerLetter)
                    turn = 'player'
            if isWinner(board_status, ComputerLetter):
                bash('clear')
                print('Oops, you lose!')
                drawBoard()
                PlayAgainWish = playAgain()
                break
            elif isBoardFull():
                bash('clear')
                print("It's a tie!")
                DrawBoard()
                PlayAgainWish = playAgain()
                break
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Are you using Python 2 or Python 3? – Daweo Apr 07 '19 at 07:37
  • I am using Python 3 – Nikhil Sharma Apr 07 '19 at 07:41
  • Python 3 defaults to UTF-8; if the encoding you are using in your Python source file is something else (which we can't guess from the information in the question, either), you have to tell Python the encoding, as explained in [PEP-263](http://www.python.org/peps/pep-0263.html). But it's not clear if this is actually the problem; if not, please [edit] the question to include the full traceback you get from the error. – tripleee Apr 07 '19 at 09:18
  • @tripleee hi! I have edited question which contains full traceback from the error – Nikhil Sharma Apr 07 '19 at 10:31
  • in last word it is ` ` I couldn't paste it at there because of quotation as it doesn't support `< and >` sign at last there – Nikhil Sharma Apr 07 '19 at 10:39
  • The immediate problem is not with the source file encoding. It's failing to encode the text that's written to stdout because you're working in an IDE instead of running the script normally as a console application. With the console we have Unicode support since Python 3.6. However, pipes and files default to the system ANSI codepage (e.g. 1252). – Eryk Sun Apr 07 '19 at 15:46
  • If your IDE is running Python in a subprocess with standard I/O connected to pipes, then it will default to ANSI. You can try to set the environment variable `PYTHONIOENCODING=utf-8`, but that may result in mojibake if the IDE's terminal assumes ANSI. If that's the case, and you're using an updated Windows 10 system, you can change the system ANSI and OEM codepages to UTF-8 (codepage 65001) in the control panel. It's beta and may cause problems with programs that assume ANSI is a single-byte or double-byte encoding, since UTF-8 is a variable-length encoding (1-4 bytes per character). – Eryk Sun Apr 07 '19 at 15:51
  • @eryksun your control panel utf-8 idea worked thanks! – Nikhil Sharma Apr 21 '19 at 08:39

1 Answers1

0

The error message in the traceback indicates that you have used characters in drawBoard which are not available in your system's current encoding, Windows code page 1252.

Either change the system encoding before calling Python, or change the message to use only characters which exist in code page 1252.

The ideal solution would be to change your system to full Unicode support, but I understand this may not be feasible in many versions of Windows.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • describe me how to do the all three fixes you told. I am pretty much novice and it would be great help! BTW I am currently using Win10 – Nikhil Sharma Apr 07 '19 at 12:09
  • This is a common FAQ; again, probably simply look at the latest proposed duplicate; if the answers there solve your problem, please accept the duplicate nomination. – tripleee Apr 07 '19 at 12:25
  • Perhaps this is a better duplicate for Python 3: https://stackoverflow.com/q/14630288/874188 – tripleee Apr 07 '19 at 12:29
  • I am not quite understanding those answers as they are too complex for me as I am still beginner so can you tell me how to change system to full unicode support? It will be a huge help?! And also tell me how to accept duplicate nomination – Nikhil Sharma Apr 07 '19 at 12:56
  • also I noticed one thing that it works well in notepad++ but doesn't work with sublime text editor – Nikhil Sharma Apr 07 '19 at 13:13
  • This has already been closed as a duplicate so no need for you to accept the nomination any longer. – tripleee Apr 07 '19 at 13:19
  • I'm no Windows person but I understand you should finally be able to set code page 65001 as your system code page in recent version of Windows 10. I have no insight as to whether this has undesired effects on other software but it seems to me like the way to go if you can't get rid of Windows entriely. – tripleee Apr 07 '19 at 13:21
  • What works in Notepad, the box drawing characters? This would depend more on the font you use than the editor itself. I guess both editors support Unicode. – tripleee Apr 07 '19 at 13:23
  • I mean it showed no error in notepad but did in sublime and I copied pasted same stuff – Nikhil Sharma Apr 07 '19 at 13:30
  • you didn't reply! – Nikhil Sharma Apr 07 '19 at 15:04
  • 1
    @NikhilSharma, Stack Overflow is a wiki-forum, not a chat. Do not expect replies to come promptly, and pestering people doesn't help. A polite reminder the next day is fine. – Eryk Sun Apr 07 '19 at 16:06
  • Reply to what anyway? I have shared what I know about this problem. – tripleee Apr 07 '19 at 17:04
  • @tripleee finally it is solved by enabling utf-8 in control panel – Nikhil Sharma Apr 21 '19 at 08:40
  • @Nikhil I added a third duplicate; can you confirm that the one I added seems correct? – tripleee Apr 21 '19 at 09:05
  • @tripleee that seems correct except that there is no mention of enabling utf-8 in control panel for windows users of build 1804 and later as a decisive solution. – Nikhil Sharma Apr 21 '19 at 10:19
  • Perhaps you could post an additional answer to the duplicate? I don't have access to this platform so I have no idea what its control panel looks like. – tripleee Apr 21 '19 at 10:21
  • It seems good idea so confirmed – Nikhil Sharma Apr 21 '19 at 10:29