【问题标题】:I want to write the data in text file and overwrite again if the existing file is over 20 lines如果现有文件超过 20 行,我想将数据写入文本文件并再次覆盖
【发布时间】:2020-08-12 04:48:36
【问题描述】:

跟踪玩家玩游戏的每一轮的高分。如果分数高 高于高分列表中的条目之一,更新高分列表。高分榜 应跟踪多达 20 个高分。 这是编码

我是 Python 的初学者,我不知道一些函数。你可以在thank()函数中查看这些代码

# Python program for jumbled words game.
# import random module
import random
# function for choosing random word.
def choose():
    # list of word
    words = open('words.txt').read().splitlines()

    # choice() method randomly choose
    # any word from the list.
    pick = random.choice(words)
    return pick
# Function for shuffling the
# characters of the chosen word.
def jumble(word):
    # sample() method shuffling the characters of the word
    random_word = random.sample(word, len(word))
    # join() method join the elements
    # of the iterator(e.g. list) with particular character .
    jumbled = ''.join(random_word)
    return jumbled
# Function for showing final score.
def thank(p1n, p2n, p1, p2):
    print(p1n, 'Your score is :', p1) #one
    f = open("high_scores.txt", "a")
    print(p1n, 'Your score is :', p1, file=f)
    f.close()

    print(p2n, 'Your score is :', p2) #two
    f = open("high_scores.txt", 'r+')
    print(p2n, 'Your score is :', p2, file=f)

    # check_win() function calling
    check_win(p1n, p2n, p1, p2)
    print('Thanks for playing...')
# Function for declaring winner
def check_win(player1, player2, p1score, p2score):
    if p1score > p2score:
        print("winner is :", player1)

    elif p2score > p1score:
        print("winner is :", player2)

    else:
        print("Draw..Well Played guys..")

# Function for playing the game.
def play():
    # enter player1 and player2 name
    p1name = input("player 1, Please enter your name :")
    p2name = input("Player 2 , Please enter your name: ")
    # variable for counting score.
    pp1 = 0
    pp2 = 0
    # variable for counting turn
    turn = 0
    # keep looping
    while True:
        # choose() function calling
        picked_word = choose()
        # jumble() fucntion calling
        qn = jumble(picked_word)
        print("jumbled word is :", qn)
        # checking turn is odd or even
        if turn % 2 == 0:
            # if turn no. is even
            # player1 turn
            print(p1name, 'Your Turn.')
            ans = input("what is in your mind? ")
            # checking ans is equal to picked_word or not
            if ans == picked_word:
                # incremented by 1
                pp1 += 1
                print('Your score is :', pp1)
                turn += 1
            else:
                print("Better luck next time ..")
                # player 2 turn
                print(p2name, 'Your turn.')
                ans = input('what is in your mind? ')
                if ans == picked_word:
                    pp2 += 1
                    print("Your Score is :", pp2)
                else:
                    print("Better luck next time...correct word is :", picked_word)
                c = int(input("press 1 to continue and 0 to quit :"))
                # checking the c is equal to 0 or not
                # if c is equal to 0 then break out
                # of the while loop o/w keep looping.
                if c == 0:
                    # thank() function calling
                    thank(p1name, p2name, pp1, pp2)
                    break
        else:
            # if turn no. is odd
            # player2 turn
            print(p2name, 'Your turn.')
            ans = input('what is in your mind? ')
            if ans == picked_word:
                pp2 += 1
                print("Your Score is :", pp2)
                turn += 1
            else:
                print("Better luck next time.. :")
                print(p1name, 'Your turn.')
                ans = input('what is in your mind? ')
                if ans == picked_word:
                    pp1 += 1
                    print("Your Score is :", pp1)
                else:
                    print("Better luck next time...correct word is :", picked_word)
                    c = int(input("press 1 to continue and 0 to quit :"))
                    if c == 0:
                        # thank() function calling
                        thank(p1name, p2name, pp1, pp2)
                        break
            c = int(input("press 1 to continue and 0 to quit :"))
            if c == 0:
                # thank() function calling
                thank(p1name, p2name, pp1, pp2)
                break
# Driver code
if __name__ == '__main__':
    # play() function calling
    play()

【问题讨论】:

  • 问题是什么?
  • 跟踪玩家玩游戏的每一轮的高分。如果高分高于高分列表中的条目之一,则更新高分列表。高分列表最多应跟踪 20 个高分。
  • 请有人解释一下,我非常渴望得到它:"))))
  • 亲爱的蜜蜂先生,我们并不清楚您想要达到的目标。请清楚地重新表述您的问题。

标签: python save leaderboard


【解决方案1】:

我相信你离答案不远了,因为你已经知道如何读写文件了。这是一个例子:

def update_high_score_file(f_name, score_keep_maxn, new_score):
    """

    :param f_name:              read and write-out file name
    :param score_keep_maxn:     how many max scores you want to record
    :param new_score:           the new score
    :return:
    """
    # read current scores
    with open(f_name, 'r') as f:
        lines = f.readlines()
    scores = [int(line.strip()) for line in lines if line.strip() != '']

    # update
    scores = scores + [new_score]
    scores = sorted(scores, reverse=True)
    scores = scores[:score_keep_maxn]

    # write out new scores
    scores = [str(s)+'\n' for s in scores]
    with open(f_name, 'w') as f:
        f.writelines(scores)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2011-05-08
    • 2020-12-25
    • 2022-12-05
    相关资源
    最近更新 更多