maroph icon

HighScoreCSV

maroph | PRO | 11/10/19 01:35:28 PM UTC | 0 ⭐ | 390 👁️ | Never ⏰ | []
Python |

7.18 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python3
#
import csv
from datetime import datetime
import os
"""
10-NOV-2019
HighScoreCSV: a class to handle a highscore file
 
CSV file format:
Score,Name,Created
3,Player,2019-11-10T11:43:23
...
"""
 
 
class HighScoreCSV:
    """
    A highscore CSV file wrapper class
    """
 
    def __init__(self, csv_file, maxscores=10, verbose=False, create=True):
        """
        constructor
        """
        self.__csv_file = None
        if isinstance(csv_file, str):
            self.__csv_file = csv_file
            if create:
                if not os.path.isfile(csv_file):
                    try:
                        with open(csv_file, 'a'):
                            pass
                    except Exception as e:
                        print(e)
                        self.__csv_file = None
 
        if isinstance(maxscores, int):
            if maxscores > 0:
                self.__maxscores = maxscores
            else:
                self.__maxscores = 10
 
        if isinstance(verbose, bool):
            self.__verbose = verbose
        else:
            self.__verbose = False
 
        self.__fieldNames = ['Score', 'Name', 'Created']
        self.__properlyLoaded = False
        self.__data = []
        self.__entries = 0
 
        if self.__csv_file is not None:
            try:
                with open(self.__csv_file, 'r') as csvfile:
                    csvreader = csv.reader(csvfile)
                    header = next(csvreader, None)
                    if self.__verbose:
                        print("HighScoreCSV#init: HEADER>>>>>", header)
                    if header != self.__fieldNames:
                        print("HighScoreCSV: ERROR: wrong header detected")
                        # we don't know the CSV file format so we don't read the file
                    else:
                        for row in csvreader:
                            if self.__verbose:
                                print("HighScoreCSV#init:>>>>>", str(row[0]) + ',' + row[1] + ',' + row[2])
                            self.__entries = self.__entries + 1
                            self.__data.append(row)
            except Exception as e:
                print(e)
            else:
                self.__properlyLoaded = True
 
            if len(self.__data) > self.__maxscores:
                if self.__verbose:
                    print("HighScoreCSV#init: >>>>>truncate highscore list")
                self.__data = self.__data[:self.__maxscores]
                self.__entries = self.__maxscores
 
    def __str__(self):
        """
        string representation of this instance
        """
        return "HighScoreCSV:[csv_file:" + self.__csv_file + "|maxscores:" + str(self.__maxscores) + "|verbose:" + str(self.__verbose) + "]"
 
    @property
    def is_properly_loaded(self):
        return self.__properlyLoaded
 
    @property
    def csv_file(self):
        return self.__csv_file
 
    @property
    def entries(self):
        return self.__entries
 
    @property
    def maxscores(self):
        return self.__maxscores
 
    @property
    def verbose(self):
        return self.__verbose
 
    def add_score(self, score, name):
        """
        add a new entry to the highscore list
        """
        idx = 0
        for row in self.__data:
            if score <= int(row[0]):
                idx = idx + 1
                continue
            break
 
        if self.__verbose:
            print('HighScoreCSV#add_score: >>>>>idx', ':', idx)
 
        if idx < self.__maxscores:
            row = [score, name]
            now = datetime.now()
            dt_string = now.strftime("%Y-%m-%dT%H:%M:%S%Z")
            row.append(dt_string)
            self.__data.insert(idx, row)
            if self.__verbose:
                print("HighScoreCSV#add_score: >>>>>row added at idx:", idx)
            self.__entries = self.__entries + 1
            if len(self.__data) > self.__maxscores:
                if self.__verbose:
                    print("HighScoreCSV#add_score: >>>>>truncate highscore list")
                self.__data = self.__data[:self.__maxscores]
                self.__entries = self.__entries - 1
            if self.__verbose:
                print("HighScoreCSV#add_score: dump highscore data:")
                print(self.__data)
            return True
 
        if self.__verbose:
            print("HighScoreCSV#add_score: no row added")
        return False
 
    def print_scores(self):
        """
        print the content of the highscore list
        """
        for row in self.__data:
            print(str(row[0]) + ',' + row[1] + ',' + row[2])
 
    def save(self, new_csv_file=None):
        """
        save the the highscore list
        """
        store_file = None
        if isinstance(new_csv_file, str):
            store_file = new_csv_file
        else:
            store_file = self.__csv_file
 
        if store_file is None:
            if self.__verbose:
                print("HighScoreCSV#save: store file name not available")
            return False
 
        try:
            with open(store_file, 'w') as csvfile:
                csvwriter = csv.writer(csvfile, dialect='unix', quoting=csv.QUOTE_MINIMAL)
                csvwriter.writerow(self.__fieldNames)
                for row in self.__data:
                    csvwriter.writerow(row)
        except Exception as e:
            print("HighScoreCSV#save: ERROR:", e)
            return False
        return True
 
 
if __name__ == '__main__':
    hs = HighScoreCSV("./highscore.csv")
    # hs = HighScoreCSV("./highscore.csv", verbose=True)
    print('csv_file        ', ':', hs.csv_file)
    print('verbose         ', ':', hs.verbose)
    print('maxscores       ', ':', hs.maxscores)
    print('entries         ', ':', hs.entries)
    print('properly loaded ', ':', hs.is_properly_loaded)
    print("")
    hs.add_score(1, "Player1")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player2")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player3")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player4")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player5")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player6")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player7")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player8")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player9")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player10")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player11")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player12")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player13")
    print('entries   ', ':', hs.entries)
    hs.add_score(1, "Player14")
    print('entries   ', ':', hs.entries)
    hs.add_score(3, "Player15")
    print('entries   ', ':', hs.entries)
    print("----------")
    print("Highscore list:")
    hs.print_scores()
    print("----------")
    hs.save()
    # hs.save(new_csv_file='highscore2.csv')

Comments