为什么我在python中得到unicode编码错误? [重复]

问题描述 投票:0回答:2

我开始学习Python,我只是复制了一个粘贴的代码,以便在崇高的文本编辑器中运行,但它在第163和30行显示了三个错误。它显示的另一个错误如下所示

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>

有人能帮我吗?

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
python sublimetext
2个回答
0
投票

通常,在代码中使用非ASCII字符时会显示此错误消息。解决方案是删除非ASCII字符或启用UTF-8字符编码。添加此行应允许您在代码中打印非ASCII字符。加

# -*- coding: utf-8 -*-

要么

# coding: utf-8

到你的.py文件的顶部


0
投票

回溯中的错误消息表明您在drawBoard中使用了系统当前编码中没有的字符,Windows code page 1252.

在调用Python之前更改系统编码,或者将消息更改为仅使用代码页1252中存在的字符。

理想的解决方案是将系统更改为完全的Unicode支持,但我知道在许多Windows版本中这可能不可行。

© www.soinside.com 2019 - 2024. All rights reserved.