csv 如何从外部文本文件打印最高分

7rtdyuoh  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(110)

帮助!我是一个初学者编码器,我试图建立一个顶级王牌游戏。我已经创建了一个外部CSV文件,存储游戏的分数。我试图让游戏打印记录的最高分数,但我运行在很多错误。有人请帮助:(。我已经在这个工作了几天,现在和代码不断打破越来越多,每次我试图修复它。

import random
import requests
import csv

def random_person():
    person_number = random.randint(1, 82)
    url = 'https://swapi.dev/api/people/{}/'.format(person_number)
    response = requests.get(url)
    person = response.json()
    return {
        'name': person['name'],
        'height': person['height'],
        'mass': person['mass'],
        'birth year': person['birth_year'],
    }

def run():
    highest_score = 0
    with open('score.csv', 'r') as csv_file:

        spreadsheet = csv.DictReader(csv_file)
        for row in spreadsheet:

            intscore = int(row['score'])

            if intscore > highest_score:
                highest_score = intscore

    print('The highest score to beat is', highest_score)
    game = input('Do you think you can beat it? y/n')
    if game == 'y':
        print('Good Luck🙌🏽')
    else:
        print('You got this🙌🏽')
    print('Hello stranger, Welcome to StarWars Top Trump!')
    player_name = input('What is your name?')
    lives_remaining = 1
    score = 0
    while lives_remaining > 0:
        my_person = random_person()
        print(player_name, ', you were given', my_person['name'])

        while True:
            stat_choice = input('Which stat do you want to use? ( height, mass, birth year)')
            if stat_choice.lower() not in ('height', 'mass', 'birth year'):
                print('Not an appropriate answer. Try again.')
            else:
                break

        opponent_person = random_person()
        print('The opponent chose', opponent_person['name'])
        my_stat = my_person[stat_choice]
        opponent_stat = opponent_person[stat_choice]

        if my_stat > opponent_stat:
            print(player_name, 'You Win! 🙌🏽')
            score = score + 1
            print(player_name, 'You have ', lives_remaining, 'lives remaining!')
            print('Your score is', score)
        elif my_stat == opponent_stat:
            print('Its A Draw!')
            print(player_name, 'You have', lives_remaining, 'lives remaining!')
            print('Your score is', score)
        elif my_stat < opponent_stat:
            lives_remaining = lives_remaining - 1
            print(player_name,  'You have,', lives_remaining, 'lives remaining!')
            print('Your score is', score)

        field_names = ['player_name', 'score']
        with open("score.csv", "w") as csv_file:
            spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
            spreadsheet.writeheader()

        data = [{"player_name": player_name, 'score': score}]
        with open("score.csv", "w") as csv_file:
            spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
            spreadsheet.writeheader()

        with open("score.csv", "a") as csv_file:
            spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
            spreadsheet.writerows(data)
        with open('score.csv', 'r') as csv_file:
            print('open file for reading')
            spreadsheet = csv.DictReader(csv_file)
        for row in spreadsheet:
            print(row)
            intscore = int(row['score'])
            print('SCORE: ', intscore)
        if intscore > highest_score:
            highest_score = intscore
            print(highest_score)

run()

这是我运行代码时遇到的错误之一

line 26, in run
    intscore = int(row['score'])
ValueError: invalid literal for int() with base 10: 'score'

enter image description here

bzzcjhmw

bzzcjhmw1#

这里有一种管理分数数据库的方法。有一个“阅读器”,它从CSV翻译并返回一个字典,还有一个“写入器”,它接受字典并将其写入文件。这被称为“序列化”和“反序列化”。

import random
import requests
import csv

def readscores(filename):
    scores = {}
    with open(filename, 'r') as csv_file:
        for row in csv.DictReader(csv_file):
            scores[row['player_name']] = int(row['score'])
    return scores

def writescores(scores, filename):
    with open(filename, 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(['player_name','score'])
        writer.writerows( scores.items() )

def random_person():
    person_number = random.randint(1, 82)
    url = 'https://swapi.dev/api/people/{}/'.format(person_number)
    response = requests.get(url)
    person = response.json()
    return {
        'name': person['name'],
        'height': person['height'],
        'mass': person['mass'],
        'birth year': person['birth_year'],
    }

def run():
    scores = readscores('score.csv')
    highest_score = max(scores.values())

    print('The highest score to beat is', highest_score)
#    game = input('Do you think you can beat it? y/n')
#    if game == 'y':
#        print('Good Luck????')
#    else:
#        print('You got this????')
    print('Hello stranger, Welcome to StarWars Top Trump!')
    player_name = input('What is your name?')
    lives_remaining = 1
    score = 0
    while lives_remaining > 0:
        my_person = random_person()
        print(player_name, ', you were given', my_person['name'])

        while True:
            stat_choice = input('Which stat do you want to use? ( height, mass, birth year)')
            if stat_choice.lower() not in ('height', 'mass', 'birth year'):
                print('Not an appropriate answer. Try again.')
            else:
                break

        opponent_person = random_person()
        print('The opponent chose', opponent_person['name'])
        my_stat = my_person[stat_choice]
        opponent_stat = opponent_person[stat_choice]

        if my_stat > opponent_stat:
            print(player_name, 'You Win! ????')
            score = score + 1
        elif my_stat == opponent_stat:
            print('Its A Draw!')
        elif my_stat < opponent_stat:
            lives_remaining = lives_remaining - 1

        print(player_name,  'You have,', lives_remaining, 'lives remaining!')
        print('Your score is', score)

        scores[player_name] = score
        writescores( scores, 'score.csv' )

        print('SCORE: ', score)
        if score > highest_score:
            highest_score = score
            print(highest_score)

run()

此脚本在使用此数据开始时有效。请注意,如果缺少“score.csv”,则此脚本无效;这是你需要添加的代码,并不难处理。

c:\tmp>type score.csv
player_name,score
Tim,1
Joe,1
Bill,0

相关问题