简体   繁体   中英

Python program not responding when play moves

I am writing a roguelike in python with libtcod. movement worked fine before I switched to object orientation. When I run my python game it pops up but as soon as I try to move the player, it freezes. Here is my code:

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

It might have something to do with the while loop and movement... ugh i don't know

Maybe instead of

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

you want

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

Otherwise, you just set the position of the player to (-1, 0) (outside the screen) if you press KEY_LEFT for example. Maybe that is why you think it is frozen.

Beside that, your code is working fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM