Консоль Unicode Python для Windows

У меня есть программа для игры в блэкджек. Это не завершено, но у меня проблема с Unicode. Когда он печатает строку, она имеет неправильный формат (см. ниже). Это Питон 3.

from unicurses import *
import sys
import time
from random import choice as rc
import random

def total(hand): #total
    aces = hand.count(11)
    t = sum(hand)
    if t > 21 and aces > 0:
        while aces > 0 and t > 21:
            t -= 10
            aces -= 1
    return t

def random(one,two):
    import random
    number = random.randint(one,two)
    return number

def number():
    number = random(1,13)
    if number == 13:
        value = '0'
    elif number == 12:
        value = '0'
    elif number == 11:
        value = '0'
    elif number == 10:
        value = '0'
    elif number < 10:
        value = number
    return value

def card():
    cardnumber = number()
    card = cardnumber
    return card

def store10Cards():
    tenCards = [card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card()]
    return tenCards

stdscr = initscr()
cards = store10Cards()

mvaddstr(10, 10, '┌──────────┐\n│{}         │\n│           │\n│            │\n│            │\n│            │\n│            │\n│            │\n│            │\n│         {}│\n└──────────┘'.format(cards[0], cards[0]).encode('utf-8'))


#deck = [] #deck of cards

#cwin = 0 #computer wins
#pwin = 0 #player wins

#for i in range (2, 11):
   # for j in range ([24, 72][i == 10]):
       # deck.append(i)

#stdscr = initscr() #Start the standard screen 

start_color() #Start the color service

init_pair(1, COLOR_RED, 0) #color pair 1 is red text and no highlighting
init_pair(2, COLOR_WHITE, 0) #color pair 2 is white text and no highlighting

addstr('\n\n------------------------------------------------------------------------', color_pair(1) | A_BOLD)
addstr('\n\n\nAre You Ready To Try And Defeat The Undefeated Blackjack Master?\n\n\nThe First One To Win 10 Hands Wins!!!\n\n\nAces Are Counted As 11s And Automaticlly Change To 1 If You Go Over 21. \n\n\nWinning 1 Hand Does Not Mean You Win The Game\n\n\nIt Is Possible To Win But Very Hard!!!                  Good Luck!!!\n\n\n', color_pair(2))
addstr('------------------------------------------------------------------------', color_pair(1) | A_BOLD)
addstr('\n\nDo You Know The Rules Of Blackjack? (Y or N)\n\n', color_pair(2))
addstr('------------------------------------------------------------------------', color_pair(1) | A_BOLD)

refresh() #refreshes

cbreak() #lets user do Ctrl + C

noecho() #Stops inputs from being shown

a = getch() #Gets input

while a == ord('q'): #Checks if input is q
    clear() #clears before exit
    exit() #quits

while a == ord('n'): #Checks if input is n

    clear() #clears before displaying the next text

    addstr('\n\n\n----------------------------------------------------------------------------------', color_pair(1) | A_BOLD)
    addstr('\n\nOk. That Is Ok. The Rules Are As Follows: \n\nThe Goal Is To Get To 21.\n\nYou Can Hit A Card (Receive Another) Or Stand And See What The Dealer Has And Does.\n\nThe Person With The Higest Value 21 Or Below Wins That Hand.\n\nAces Start As 11s But Change Automatticly To 1s If You Go Over 21 To Save You.\n\nIf You Get 21 Exactly You Get A Blackjack.\n\nA Blackjack Means You Automaticly Win Unless The Computer Gets A 21 And Ties You.\n\nBe Careful Not To Hit Too Many Times Because If You Go Over 21 You Lose That Hand.\n\nAny Face Card Is Automaticly A 10 At All Times.\n', color_pair(2))
    addstr('\n----------------------------------------------------------------------------------\n\n\n', color_pair(1) | A_BOLD)

    sleep(15)

    a = getch() #resets input variable

    while a == ord('q'): #Checks if input is q
        clear() #Clears before exit
        exit() #quits

while a == ord('y'): #Checks if input is y

    clear() #clears before displaying the next text

    addstr('\n\n\n\n\n----------------------------------------------------------------------------------', color_pair(1) | A_BOLD)
    addstr('\n\n\n\nGreat!\n\n\n\nHave Fun!\n\n\n\nGood Luck!\n\n\n', color_pair(2))
    addstr('----------------------------------------------------------------------------------\n\n\n', color_pair(1) | A_BOLD)

    refresh()

    time.sleep(1)

    b = '1'

    a = '' #resets input variable

Вот строка, с которой у меня проблемы:

mvaddstr(10, 10, '┌──────────┐\n│{}         │\n│           │\n│            │\n│            │\n│            │\n│            │\n│            │\n│            │\n│         {}│\n└──────────┘'.format(cards[0], cards[0]).encode('utf-8'))

Я попытался закодировать его с помощью UTF-8 и установить для командной строки значение UTF-8, выполнив chcp, а затем, когда я запускаю эту программу, эта строка печатает:

b'\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\x e2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x823 \xe2\x94\x82\n\xe2\x94\x82 \t \xe2\x94\x82\n\xe2\x94\x82 \t \xe2 \x94\x82\n\xe2\x94\x82 \t \xe2\x94\x82\n\xe2\x94\x82 \t \xe2\x94\x82\n\x e2\x94\x82 \t \xe2\x94\x82\n\xe2\x94\x82 \t \xe2\x94\x82\n\xe2\x94\x82 \t \xe2\x94\x82\n\xe2\x94\x82 3\xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe 2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\ x94\x80\xe2\x94\x80\xe2\x94\x98'

Пожалуйста, помогите мне напечатать строку так, как она должна быть, а не в юникоде.

Если у вас есть другие предложения по моему коду, дайте мне знать.


person James    schedule 07.08.2016    source источник
comment
Какая кодировка исходного файла?   -  person BrenBarn    schedule 08.08.2016
comment
Вы печатаете байты, создавая их отладочное представление. Сначала декодируйте байты.   -  person Martijn Pieters    schedule 08.08.2016


Ответы (1)


В Windows unicurses использует ctypes для переноса PDCurses. Эта библиотека может быть построена с поддержкой Unicode в 32-разрядных библиотеках DLL, которые распространяются на сайте проекта. К вашему сведению, версии Unicode вызывают консольные API с расширенными символами, такие как WriteConsoleOutputW, поэтому не беспокойтесь о устаревшей кодовой странице консоли. Вам нужна сборка "pdc34dllu.zip", которая принимает параметры в кодировке UTF-8. Поскольку предварительно созданные библиотеки DLL являются только 32-разрядными, вам придется использовать 32-разрядный Python, если только у вас не установлена ​​Visual Studio 2015 для создания 64-разрядной библиотеки DLL.

Вам также придется внести пару изменений в unicurses, чтобы это заработало. Вот шаги, которые я выполнил, чтобы заставить это работать для 32-битного Python 3.5:

  1. Загрузите pdc34dllu.zip. Извлеките «pdcurses.dll» либо в каталог установки Python, т. е. там, где находится python.exe, либо в каталог, указанный в переменной среды PATH.
  2. Загрузите и распакуйте UniCurses-1.2.zip.
  3. Перед установкой внесите следующие изменения в unicurses.py. В строке 34 измените code = locale.getpreferredencoding() на code = 'utf-8'. Затем закомментируйте строки 52-54, которые начинаются с if not os.access("pdcurses.dll",os.F_OK), потому что эта проверка всегда завершается ошибкой, если "pdcurses.dll" отсутствует в рабочем каталоге.
  4. Установите пакет, запустив python setup.py install.

пример: печать карты

import unicurses

card_template = '\n'.join([
    '┌────────────┐',
    '│{card}           │',
    '│            │',
    '│            │',
    '│            │',
    '│            │',
    '│            │',
    '│            │',
    '│            │',
    '│           {card}│',
    '└────────────┘'])

def main():
    stdscr = unicurses.initscr()
    unicurses.clear()
    card_string = card_template.format(card=5)
    for i, line in enumerate(card_string.splitlines()):
        unicurses.mvaddstr(5 + i, 5, line)
    unicurses.refresh()
    unicurses.endwin()

if __name__ == '__main__':
    main()

выход

     ┌────────────┐
     │5           │
     │            │
     │            │
     │            │
     │            │
     │            │
     │            │
     │            │
     │           5│
     └────────────┘
person Eryk Sun    schedule 08.08.2016
comment
Ты самый лучший! Большое спасибо. Мне пришлось отредактировать ваш код, потому что я хочу, чтобы несколько карт были рядом друг с другом, но это сработало. Спасибо! - person James; 08.08.2016
comment
@BrendanNeiman Пожалуйста, не комментируйте, прося ответов на другой пост. - person Andrew Li; 09.08.2016