1

我正在用 libtcod 在 python 中写一个 roguelike。在我切换到面向对象之前,运动效果很好。当我运行我的 python 游戏时,它会弹出,但一旦我尝试移动播放器,它就会冻结。这是我的代码:

import libtcodpy as libtcod;

SCREEN_WIDTH = 80;
SCREEN_HEIGHT = 50;
LIMIT_FPS = 20;

class Object:
    def __init__(self, x, y, char, color):
        self.x = x
        self.y = y
        self.char = char
        self.color = color

    def move(self, dx, dy):
        self.x = dx
        self.y = dy

    def draw(self):
        #libtcod.console_set_default_foreground(con, self.color)
        libtcod.console_put_char(con, self.x, self.y, self.char, libtcod.BKGND_NONE)

    def clear(self):
        libtcod.console_put_char(con, self.x, self.y, ' ', libtcod.BKGND_NONE)

def handle_keys():
    key = libtcod.console_check_for_keypress()
    if key.vk == libtcod.KEY_ENTER and key.lalt:
        libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

    elif key.vk == libtcod.KEY_ESCAPE:
        return True  #exit game

    if libtcod.console_is_key_pressed(libtcod.KEY_UP):
        player.move(0, -1)

    elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN):
        player.move(0, 1)

    elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT):
        player.move(-1, 0)

    elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT):
        player.move(1, 0)

libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD);
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Lets Crawl', False);
libtcod.sys_set_fps(LIMIT_FPS);
con = libtcod.console_new(SCREEN_WIDTH, SCREEN_HEIGHT)

player = Object(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, '@', libtcod.white)
#npc = Object(SCREEN_WIDTH/2 - 5, SCREEN_HEIGHT/2, '@', libtcod.yellow)
objects = [player]

while not libtcod.console_is_window_closed():

    for object in objects:
        object.draw()


    #libtcod.console_check_for_keypress()
    libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
    libtcod.console_flush();

    for object in objects:
        object.clear()

    exit = handle_keys()
    if exit:
        break

它可能与while循环和运动有关......呃我不知道

4

1 回答 1

1

也许代替

def move(self, dx, dy):
    self.x = dx
    self.y = dy

你要

def move(self, dx, dy):
    self.x += dx
    self.y += dy

否则,如果您按下例如,您只需将播放器的位置设置为(-1, 0)(屏幕外) 。KEY_LEFT也许这就是你认为它被冻结的原因。

除此之外,您的代码对我来说运行良好。

于 2013-02-21T09:46:00.017 回答