0

您好,我正在用 python 制作游戏,并且我让游戏在文本文档上写入数据,有没有一种方法可以编码,所以如果文本文件显示名为 Bob 的人处于 4 级,则让程序启动在第 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
4

1 回答 1

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 使用了不同的文件名。

于 2013-11-06T12:49:21.410 回答