您好我正在用python制作一个游戏,我让游戏在文本文档上写入数据,并且有一种方法可以编码,所以如果文本文件说名为Bob的人在4级,那么make程序从第4级开始。我尝试使用for循环来完成这项工作,但它不会工作。它不会启动文本文件,只会转到1级。 这是游戏代码(用于阅读和写作:
import os
#---------------------------
os.system("color a")
#---------------------------
def ping(num):
os.system("ping localhost -i", num, ">nul")
def cls():
os.system("cls")
#--------------------------
print("the game")
ping(2)
cls()
print("1: New Game")
print("2: Continue")
print("3: Credits")
while True:
choice=input("Enter")
if choice==1:
name=input("Enter your name")
firstsave=open("data.txt", "W")
firstsave.write(name, " ")
# there will be the game data here
elif choice==2:
opendata=file("data")
#opening the file
while True:
''' is the place where the file scanning part needs to come.
after that, using if and elif to decide which level to start from.(there are a total of 15 levels in the game)
'''
文本文件:
User Level
Bob 5
George 12
答案 0 :(得分:1)
您没有提供足够的信息,但这是一种方法:
elif choice == 2:
with open("x.txt") as f:
f.readline() # skip the first line
for lines in f: # loop through the rest of the lines
name, level = line.split() # split each line into two variables
if name == playername: # assumes your player has entered their name
playlevel(int(level)) # alternatively: setlevel = level or something
break # assumes you don't need to read more lines
这假定了几件事情,比如你知道玩家的名字,玩家只有一行,名字只是一个单词,等等。如果事情不同,会变得更复杂,但这就是阅读Python文档的内容并且试验是为了。
另请注意,您使用'w'在选项1中写入,这将(写)而不是追加。不确定你的意思,但你也可以为选择1和2使用不同的文件名。