python 按键简单游戏

2024-01-28

我想在屏幕上看到一个符号,例如可能是(散列)“#”。符号会有一些起始位置,比如说 (0, 0)。如果我按向右箭头,我希望看到标志向右移动,如果按向左箭头,我希望看到标志向左移动,等等。 到目前为止,我的代码看起来像这样,它适用于读取 pos,但我想添加某种“动画”,这样我就可以看到标志在屏幕上移动:

!Update:只是为了给您提供线索,我创建了“图标”,现在当您按向右或向左键时,图标会向所需的方向移动。

from msvcrt import getch

icon = chr(254)
pos = [0, 0]
t = []
def fright():
    global pos
    pos[0] += 1
    print ' ' * pos[0], 
    print(icon) 

def fleft():
    global pos 
    pos[0] -= 1
    print ' ' * pos[0], 
    print(icon) 

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

def appendTab():
    global pos, t
    t.append(pos)

while True:
    print'Distance from zero: ', pos    
    key = ord(getch())

    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
        appendTab()
    elif key == 32: #Space, just a small test - skip this line
        print('jump')
        print(t)
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown()
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

您可以创建一个列表列表作为地图,并将玩家的单元格设置为'#'。然后只需打印地图,如果玩家移动,请使用以下命令清除命令行/终端os.system('cls' if os.name == 'nt' else 'clear') https://stackoverflow.com/a/2084628/6220679并打印更新后的地图。

import os
from msvcrt import getch

pos = [0, 0]
# The map is a 2D list filled with '-'.
gamemap = [['-'] * 5 for _ in range(7)]
# Insert the player.
gamemap[pos[1]][pos[0]] = '#'

while True:
    print('Distance from zero: ', pos    )
    key = ord(getch())

    if key == 27: #ESC
        break
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key in (80, 72, 75, 77):
            # Clear previous tile if player moves.
            gamemap[pos[1]][pos[0]] = '-'
        if key == 80: #Down arrow
            pos[1] += 1
        elif key == 72: #Up arrow
            pos[1] -= 1
        elif key == 75: #Left arrow
            pos[0] -= 1
        elif key == 77: #Right arrow
            pos[0] += 1

    print('clear')
    # Clear the command-line/terminal.
    os.system('cls' if os.name == 'nt' else 'clear')
    # Set the player to the new pos.
    gamemap[pos[1]][pos[0]] = '#'
    # Print the map.
    for row in gamemap:
        for tile in row:
            print(tile, end='')
        print()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 按键简单游戏 的相关文章

随机推荐