python中的简单延迟计数器无法正常工作

时间:2018-04-04 19:08:31

标签: python python-3.x pygame

您好我是python的新手,我正在尝试将一个简单的计数器作为延迟来在pygame中显示一些文本,因此它不会立即显示。 我想做的是当玩家升级时让文字显示在一个框中。

def TEXT(A, B, C):
    global ONE, TWO, THREE, FOUR
    counter = 0
    text = True
    if text:
        if counter == 10:
            ONE = A
        if counter == 20:
            TWO = B
        elif counter == 30:
            THREE = C
        elif counter == 40:
            ONE = None
            TWO = None
            THREE = None
            text = False
        counter += 1

整个代码似乎工作正常,但我无法让计数器工作。 这是完整的程序作为参考:

from pygame import *
from userInterface import Title, Dead
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", 15)



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]}}


ONE = None
TWO = None
THREE = None
FOUR = None

def TEXT(A, B, C):
    global ONE, TWO, THREE, FOUR
    counter = 0
    text = True
    if text:
        if counter == 0:
            ONE = A
        if counter == 10:
            TWO = B
        elif counter == 20:
            THREE = C
        elif counter == 30:
            ONE = None
            TWO = None
            THREE = None
            text = False
        counter += 1




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
        A = (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 stats
        B = (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

        TEXT(A,B,None)

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!')
    #TEXT(f'{defender["name"]} takes {dmg} damage!')

    if defender['stats']['hp'] <= 0:
            print(f'{defender["name"]} has been slain...')
            #TEXT(f'{defender["name"]} has been slain...')

            attacker['xp'] += defender['reward']
            level(attacker)
            if defender==hero:
                #Dead()
                pass
            else:
                hero['stats']['hp']=heroHP
                #Title()
                pass


def Battle(player, enemy):
    global ONE, TWO, THREE, FOUR
    mouse.set_visible(1)
    clock = time.Clock()
    YES = Rect(100, 100, 50, 50)
    NO = Rect(500, 100, 50, 50)
    Text = Rect(70, 300, 500, 75)

    #while ((enemy['stats']['hp']) > 0):
    while True:
        for e in event.get():
            if e.type == QUIT:
                exit("Quit") # if X is pressed, exit program
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    exit()
            elif e.type == MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if e.button == 1:
                    # `event.pos` is the mouse position.
                    if YES.collidepoint(e.pos):
                        takeDmg(player, enemy)
                        print(f'{enemy["name"]} takes the opportunity to attack!')
                    #TEXT(f'{enemy["name"]} takes the opportunity to attack!')

                    takeDmg(enemy, player)
                elif NO.collidepoint(e.pos):
                    print(f'{enemy["name"]} takes the opportunity to attack!')
                    #TEXT(f'{enemy["name"]} takes the opportunity to attack!')

                    takeDmg(enemy, player)


    screen.fill(WHITE)
    draw.rect(screen, BLACK, YES)
    draw.rect(screen, BLACK, NO)
    draw.rect(screen, GRAY, Text)



    YES_surf = FONT.render(("YES"), True, WHITE)
    NO_surf = FONT.render(("NO"), True, WHITE)
    Text1_surf = FONT.render(ONE, True, WHITE)
    Text2_surf = FONT.render(TWO, True, WHITE)
    Text3_surf = FONT.render(THREE, True, WHITE)
    Text4_surf = FONT.render(FOUR, True, WHITE)



    screen.blit(YES_surf, YES)
    screen.blit(NO_surf, NO)
    screen.blit(Text1_surf, (80, 305))
    screen.blit(Text2_surf, (80, 320))
    screen.blit(Text3_surf, (80, 335))
    screen.blit(Text4_surf, (80, 350))





    display.update()

    clock.tick(60)

Battle(hero, boss1)

1 个答案:

答案 0 :(得分:0)

如果您只想让counter成为一个全局变量,只在程序开始时设置为0,而不是在每次调用时重置为0的局部变量,那么就这样做了。以同样的方式处理ONE和同一函数中的其他全局变量:

counter =0
def TEXT(A, B, C):
    global ONE, TWO, THREE, FOUR
    global counter
    text = True
    if text:
        if counter == 10:
            # etc.
    counter += 1

唯一的变化是将counter = 0从函数体移动到顶层,并在函数体的开头添加global counter