【发布时间】:2026-02-14 01:55:01
【问题描述】:
我需要查看列表中特定行和列的字符。我正在创建一个游戏,需要防止玩家穿过墙壁。
这是我目前的代码。
import copy
def print_house(h,sr,sc):
th = copy.deepcopy(h)
th[sr][sc] = "@"
for i in th:
print(''.join(str(x) for x in i), end='')
def build_house():
#print("Please enter the house file: ")
house_file = "house.txt"
housefp = open(house_file, "r")
global myhouse
myhouse = []
line = housefp.readline()
while line:
myhouse.append(list(line))
line = housefp.readline()
return myhouse
def check_north(h,sr,sc):
if sc-1 == "*":
return False
else:
return True
def check_south(h,sr,sc):
if sr+1 == "*":
return False
else:
return True
def check_east(h,sr,sc):
if sc+1 == "*":
return False
else:
return True
def check_west(h,sr,sc):
if sc-1 == "*":
return False
else:
return True
def main():
global house, startrow, startcol
house = build_house()
startrow, startcol = 1,3
num_treasures = 2
tcount = 0
while tcount < num_treasures:
print_house(myhouse, startrow, startcol)
print("You can go N,S,W,E")
command = input("Please enter where to do using the w,a,s,d keys or q to quit:")
if command == "w" and check_north(myhouse, startrow, startcol) == True:
trow = startrow-1
tcol = startcol
elif command == "a" and check_west(myhouse, startrow, startcol) == True:
trow = startrow
tcol = startcol-1
elif command == "s" and check_south(myhouse, startrow, startcol) == True:
trow = startrow+1
tcol = startcol
elif command == "d" and check_east(myhouse, startrow, startcol) == True:
trow = startrow
tcol = startcol+1
elif command == "q":
return
else:
print("Sorry, you can't go through walls")
startrow,startcol = trow,tcol
main()
它还在此处使用带有地图的文本文件。文本文件名为 house.txt
***************
*** 0 ********************************
*** 6 *
*********** ************************** *
* * * *
********5*************** * t *
* * ******
* t 1 *
************************
【问题讨论】:
-
你在这个列表中有什么?单个字符?有很多字符的行?你将它保存在一维列表还是二维列表(嵌套列表)中?坦率地说,我不明白你的问题是什么。我看到你使用
th[sr][sc],所以你已经知道如何从二维列表中获取字符。所以你可以用它来检查价值——即。if th[sr][sc] == "*": ... -
我想我知道你的问题出在哪里 - 你检查
if sc-1 == "*":但你应该getchar 就像你setchar -th[sr][sc]- 所以你需要if th[sr][sc-1] == "*":