【发布时间】:2021-03-13 22:30:49
【问题描述】:
根据我的研究,msvcrt 函数应该允许您输入单个命令而无需按下“回车”。为什么它在我的游戏中不起作用?例如,如果我单击“w”,理论上该角色应该向北移动 1 个空格,而无需单击 Enter。游戏使用 input() 可以正常工作,但每次移动后您都需要单击 Enter
import os
import msvcrt
#map
dungeonMap = [["0","0","0","0","0","0","0","0","0"],
["0",".",".","0",".",".",".",".","0"],
["0",".",".",".",".",".",".","0","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".","0",".",".",".","0"],
["0",".","0","0",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0","0","0","0","0","0","0","0","0"]]
playerMap = [["0","0","0","0","0","0","0","0","0"],
["0",".",".","0",".",".",".",".","0"],
["0",".",".",".",".",".",".","0","0"],
["0","S",".",".",".",".",".",".","0"],
["0",".",".",".","0",".",".",".","0"],
["0",".","0","0",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0",".",".",".",".",".",".",".","0"],
["0","0","0","0","0","0","0","0","0"]]
x = 1
y = 3
def displayMapAround(maps,x,y):
for dy in (-1,0,1):
print( maps[y+dy][x-1:x+2] )
#Displaying the map
def displayMap(maps):
for y in range(0,9):
print(maps[y])
#selecting a map
mapChoice = dungeonMap
displayMapAround(playerMap,x,y)
#initialising the players position
position = mapChoice[0][0]
print(mapChoice[y][x])
while position != "E":
os.system('cls' if os.name == 'nt' else 'clear')
displayMapAround(playerMap,x,y)
displayMap(playerMap)
previousX = x
previousY = y
playerMap[y][x] = "."
print("W,S,D,A,MAP")
movement = msvcrt.getch()
movement=movement.upper()
if movement == "W":
y = y-1
position = mapChoice[y][x]
playerMap[y][x] = "S"
if movement == "S":
y = y+1
position = mapChoice[y][x]
playerMap[y][x] = "S"
if movement == "D":
x = x+1
position = mapChoice[y][x]
playerMap[y][x] = "S"
if movement == "A":
x = x-1
position = mapChoice[y][x]
playerMap[y][x] = "S"
position = mapChoice[y][x]
playerMap[y][x] = "S"
if position == "0" or position == "1":
print("You hit a wall, you stumble in the darkness back to your previous position...")
playerMap[y][x] = "0"
x = previousX
y = previousY
playerMap[y][x] = "S"``
【问题讨论】:
-
getch()返回一个字节字符串,而不是 unicode 字符串,因此您需要将它返回的值转换为 1 — 这可以通过movement = msvcrt.getch().decode()轻松完成。
标签: python windows ascii game-engine msvcrt