简体   繁体   中英

How to print highest score from an external text file

Help. I'm a starter coder and I am trying to build a top trumps game. I have created an external CSV file that stores the scores of the game. I am trying to get the game to print the highest score recorded but I am running in to a lot of errors: SOMEONE PLEASE HELP.(. I've been working on this for days now and the code keeps breaking more and more every time i try to fix it.

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()

This is one of the errors I get when I run the code

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

enter image description here

Here is a way to manage the score database. There's a "reader" that translates from CSV and returns a dictionary, and a "writer" that accepts a dictionary and writes it to file. This is called "serialization" and "deserialization".

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()

This script works when starting with this data. Note that it doesn't work if "score.csv" is missing; that's code you'd need to add. It's not hard to handle.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM