【问题标题】:TypeError: decoding str is not supported , How do i Decode String in PygameTypeError:不支持解码str,我如何在Pygame中解码字符串
【发布时间】:2021-11-13 08:58:19
【问题描述】:

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

这是代码:


# 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()

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python random pygame


【解决方案1】:

只需将字符串与+ 连接:

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

STR_xo = "You ARE" +  Character 

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

STR_xo = f"You ARE {Character}" 

但是,如果你想在 Pygame 中渲染一个多行的字符串,你需要单独渲染每一行。 见Rendering text with multiple lines in 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"

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2021-02-14
    • 2021-11-07
    • 2018-09-27
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多