【问题标题】:How to blit "print" onto screen in pygame [duplicate]如何在pygame中将“打印”到屏幕上[重复]
【发布时间】:2023-03-15 09:54:01
【问题描述】:

我写了一个简单的 RPG 战斗系统,如果你输入“y”,你就会攻击,但如果你输入“n”,敌人就会攻击你。在我实施攻击系统之前,输入是临时的,但所有输出都显示在命令提示符中。如何将打印内容粘贴到 pygame 窗口而不是显示在命令提示符中。

战斗系统代码:

heroHP = 1000

hero={'name' : 'Hero',
      'height':4,
      'lvl': 1,
      'xp' : 0,
      'reward' : 0,
      'lvlNext':25,
      'stats': {'str' : 12, # strength
                'dex' : 4, # dexterity
                'int' : 15, # intelligence
                'hp'  : heroHP, # health
                'atk' : [250,350]}} # range of attack values


boss1={'name' : 'Imp',
       'xp' : 0,
       'lvlNext':25,
       'reward' : 25,
       'stats': {'hp'  :400,
                'atk' : [300,350]}}


def level(char): # level up system
    #nStr, nDex, nInt=0,0,0
    while char['xp'] >= char['lvlNext']:
        char['lvl']+=1
        char['xp']=char['xp'] - char['lvlNext']
        char['lvlNext'] = round(char['lvlNext']*1.5)
        nStr=0.5*char['stats']['str']+1
        nDex=0.5*char['stats']['dex']+1
        nInt=0.5*char['stats']['int']+1
        print(f'{char["name"]} levelled up to level {char["lvl"]}!') # current level
        print(f'( INT {round((char["stats"]["int"] + nInt))} - STR {round(char["stats"]["str"] + nStr)} - DEX {round(char["stats"]["dex"] + nDex)} )') # print new statsm
        char['stats']['str'] += nStr
        char['stats']['dex'] += nDex
        char['stats']['int'] += nInt

from random import randint

def takeDmg(attacker, defender): # damage alorithm
    dmg = randint(attacker['stats']['atk'][0], attacker['stats']['atk'][1])
    defender['stats']['hp'] = defender['stats']['hp'] - dmg
    print(f'{defender["name"]} takes {dmg} damage!')
    if defender['stats']['hp'] <= 0:
            print(f'{defender["name"]} has been slain...')
            attacker['xp'] += defender['reward']
            level(attacker)
            if defender==hero:
                print("[ G A M E   O V E R ]")
                print('---------------------------')
                input('Press ENTER to quit. ')
                exit()
            else:
                hero['stats']['hp']=heroHP
            print('---------------------------')



def commands(player, enemy):
    while ((enemy['stats']['hp'])>0): # continue algorithm unless enemy is dead
        print('---------------------------')
        cmd = input(f'Do you want to attack {enemy["name"]}? y/n: ').lower()
        if 'y' in cmd:
            takeDmg(player, enemy)
            print(f'{enemy["name"]} takes the opportunity to attack!')
            takeDmg(enemy, player)
        elif 'n' in cmd:
            print(f'{enemy["name"]} takes the opportunity to attack!')
            takeDmg(enemy, player)
        else:
            break

commands(hero, boss1)

窗口代码:

from pygame import *
WIN_WIDTH = 640
WIN_HEIGHT = 400
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0

init()
screen = display.set_mode(DISPLAY, FLAGS, DEPTH)
saveState = False

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (30, 30, 30)
FONT = font.SysFont("Courier New", 20)


def Title():
    mouse.set_visible(1)
    clock = time.Clock()

    Text = Rect(70, 300, 500, 60)

    while True:
        for e in event.get():
            if e.type == QUIT:
                exit("Quit") # if X is pressed, exit program
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    exit()


        screen.fill(WHITE)

        draw.rect(screen, GRAY, Text)

        Text1_surf = FONT.render(("Test"), True, WHITE)


        screen.blit(Text1_surf, Text)

        display.update()

        clock.tick(30)

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    要在 pygame 窗口中显示任何文本,您可以首先设置字体

    font_1 = pygame.font.SysFont('Courier New', 15)
                                 #(font name,size)
    

    然后创建一个变量并为其赋值

    this_sentence=font_1.render('Write text here',True,(0,0,0))
                                                      #(0,0,0 is rgb value for 
                                                       # text color)
    

    然后

    screen.blit(this_sentence,(x,y))
                           #(x,y are coordinates respective to your display 
                             #screen)
    

    【讨论】:

    • 我已经在窗口测试代码中做到了,但我要问的是我已经在战斗系统代码中使用“打印”命令打印了几行文本。我的问题是我如何将那里打印的内容粘贴到窗口中的一个小矩形中。
    • 您必须手动调整多个 this_sentences 实例的 x,y 坐标并在屏幕上进行 blit,我制作的完整游戏可以正常运行
    • 你可以做的是在英雄死后调用一个函数,在整个屏幕上显示消息
    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多