在Python中,如何扫描特定的numb

2024-04-26 21:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在用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

Tags: thetonamegame游戏dataosping
1条回答
网友
1楼 · 发布于 2024-04-26 21:39:06

你没有提供足够的信息,但有一种方法:

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文档和实验的目的。你知道吗

还要注意,在选项1中使用“w”进行写入,它将(覆盖)写入而不是追加。不知道你是不是故意的,但是你也用不同的文件名来选择1和2。你知道吗

相关问题 更多 >