首页 > 解决方案 > TypeError:不支持解码str,我如何在Pygame中解码字符串

问题描述

我正在开发井字游戏程序,但是当我尝试解码分配给我的东西时,您能帮我解决它吗?如果您无法修复它,还有另一种方法可以做到这一点,如果您想要我自己的代码,您也可以使用此代码:)

这是代码:


# Initalize pygame
pygame.init()

# Creating the Window
win = pygame.display.set_mode((500 , 500))

# Font
font = pygame.font.Font('freesansbold.ttf', 32)

# Variables
Blackk = 0 , 0 , 0
Redd = 255 , 0 , 0
Bluee = 0 , 0 , 255
Character = ""

# X or O
x_o = random.randint( 0 , 1 )
if x_o == 1:
    Character == "X"

elif x_o == 0:
    Character == "O"

STR_xo = str("You ARE \n" , Character)
    
# Text
You_R = font.render((STR_xo) , True , Blackk , (240 , 240 , 240))

# Make it Rect
textRect = You_R.get_rect()

# Title And Icon
pygame.display.set_caption("Tic Tac Toe")
#TitIco = pygame.image.load()
#pygame.display.set_icon()

# Main Game Loop
RunNow = True
while RunNow:
    for event in pygame.event.get():

        win.fill((240 , 240 , 240 ))

        pygame.draw.rect(win, Blackk, pygame.Rect(150, 0, 20, 500))
        pygame.draw.rect(win, Blackk, pygame.Rect(335, 0, 20, 500))
        
        pygame.draw.rect(win, Blackk, pygame.Rect(0, 150, 500, 20))
        pygame.draw.rect(win, Blackk, pygame.Rect(0, 335, 500, 20))

        win.blit(You_R, textRect)

        
        if event.type == pygame.QUIT:
            RunNow = False

    pygame.display.update()

标签: pythonrandompygame

解决方案


只需将字符串与+

STR_xo = str("You ARE \n" , Character)

STR_xo = "You ARE" +  Character 

或使用格式化的字符串文字:

STR_xo = f"You ARE {Character}" 

但是,如果你想在 Pygame 中渲染一个包含多行的字符串,则需要单独渲染每一行。请参阅在 pygame 中使用多行渲染文本

You_R_surf = font.render("You ARE" , True , Blackk , (240 , 240 , 240))
Character_surf = font.render( Character, True , Blackk , (240 , 240 , 240))

# [...]

RunNow = True
while RunNow:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            RunNow = False

    win.fill((240 , 240 , 240 ))

    pygame.draw.rect(win, Blackk, pygame.Rect(150, 0, 20, 500))
    pygame.draw.rect(win, Blackk, pygame.Rect(335, 0, 20, 500))
    
    pygame.draw.rect(win, Blackk, pygame.Rect(0, 150, 500, 20))
    pygame.draw.rect(win, Blackk, pygame.Rect(0, 335, 500, 20))

    win.blit(You_R_surf, (0, 0))
    win.blit(Character_surf, (0, 32))

    pygame.display.update()  

另外还有错别字。赋值运算符=代替==

x_o = random.randint( 0 , 1 )
if x_o == 1:
    Character = "X"
elif x_o == 0:
    Character = "O"

推荐阅读