maroph

HighScoreCSV

Nov 10th, 2019
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.18 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. #
  3. import csv
  4. from datetime import datetime
  5. import os
  6. """
  7. 10-NOV-2019
  8. HighScoreCSV: a class to handle a highscore file
  9.  
  10. CSV file format:
  11. Score,Name,Created
  12. 3,Player,2019-11-10T11:43:23
  13. ...
  14. """
  15.  
  16.  
  17. class HighScoreCSV:
  18.     """
  19.    A highscore CSV file wrapper class
  20.    """
  21.  
  22.     def __init__(self, csv_file, maxscores=10, verbose=False, create=True):
  23.         """
  24.        constructor
  25.        """
  26.         self.__csv_file = None
  27.         if isinstance(csv_file, str):
  28.             self.__csv_file = csv_file
  29.             if create:
  30.                 if not os.path.isfile(csv_file):
  31.                     try:
  32.                         with open(csv_file, 'a'):
  33.                             pass
  34.                     except Exception as e:
  35.                         print(e)
  36.                         self.__csv_file = None
  37.  
  38.         if isinstance(maxscores, int):
  39.             if maxscores > 0:
  40.                 self.__maxscores = maxscores
  41.             else:
  42.                 self.__maxscores = 10
  43.  
  44.         if isinstance(verbose, bool):
  45.             self.__verbose = verbose
  46.         else:
  47.             self.__verbose = False
  48.  
  49.         self.__fieldNames = ['Score', 'Name', 'Created']
  50.         self.__properlyLoaded = False
  51.         self.__data = []
  52.         self.__entries = 0
  53.  
  54.         if self.__csv_file is not None:
  55.             try:
  56.                 with open(self.__csv_file, 'r') as csvfile:
  57.                     csvreader = csv.reader(csvfile)
  58.                     header = next(csvreader, None)
  59.                     if self.__verbose:
  60.                         print("HighScoreCSV#init: HEADER>>>>>", header)
  61.                     if header != self.__fieldNames:
  62.                         print("HighScoreCSV: ERROR: wrong header detected")
  63.                         # we don't know the CSV file format so we don't read the file
  64.                     else:
  65.                         for row in csvreader:
  66.                             if self.__verbose:
  67.                                 print("HighScoreCSV#init:>>>>>", str(row[0]) + ',' + row[1] + ',' + row[2])
  68.                             self.__entries = self.__entries + 1
  69.                             self.__data.append(row)
  70.             except Exception as e:
  71.                 print(e)
  72.             else:
  73.                 self.__properlyLoaded = True
  74.  
  75.             if len(self.__data) > self.__maxscores:
  76.                 if self.__verbose:
  77.                     print("HighScoreCSV#init: >>>>>truncate highscore list")
  78.                 self.__data = self.__data[:self.__maxscores]
  79.                 self.__entries = self.__maxscores
  80.  
  81.     def __str__(self):
  82.         """
  83.        string representation of this instance
  84.        """
  85.         return "HighScoreCSV:[csv_file:" + self.__csv_file + "|maxscores:" + str(self.__maxscores) + "|verbose:" + str(self.__verbose) + "]"
  86.  
  87.     @property
  88.     def is_properly_loaded(self):
  89.         return self.__properlyLoaded
  90.  
  91.     @property
  92.     def csv_file(self):
  93.         return self.__csv_file
  94.  
  95.     @property
  96.     def entries(self):
  97.         return self.__entries
  98.  
  99.     @property
  100.     def maxscores(self):
  101.         return self.__maxscores
  102.  
  103.     @property
  104.     def verbose(self):
  105.         return self.__verbose
  106.  
  107.     def add_score(self, score, name):
  108.         """
  109.        add a new entry to the highscore list
  110.        """
  111.         idx = 0
  112.         for row in self.__data:
  113.             if score <= int(row[0]):
  114.                 idx = idx + 1
  115.                 continue
  116.             break
  117.  
  118.         if self.__verbose:
  119.             print('HighScoreCSV#add_score: >>>>>idx', ':', idx)
  120.  
  121.         if idx < self.__maxscores:
  122.             row = [score, name]
  123.             now = datetime.now()
  124.             dt_string = now.strftime("%Y-%m-%dT%H:%M:%S%Z")
  125.             row.append(dt_string)
  126.             self.__data.insert(idx, row)
  127.             if self.__verbose:
  128.                 print("HighScoreCSV#add_score: >>>>>row added at idx:", idx)
  129.             self.__entries = self.__entries + 1
  130.             if len(self.__data) > self.__maxscores:
  131.                 if self.__verbose:
  132.                     print("HighScoreCSV#add_score: >>>>>truncate highscore list")
  133.                 self.__data = self.__data[:self.__maxscores]
  134.                 self.__entries = self.__entries - 1
  135.             if self.__verbose:
  136.                 print("HighScoreCSV#add_score: dump highscore data:")
  137.                 print(self.__data)
  138.             return True
  139.  
  140.         if self.__verbose:
  141.             print("HighScoreCSV#add_score: no row added")
  142.         return False
  143.  
  144.     def print_scores(self):
  145.         """
  146.        print the content of the highscore list
  147.        """
  148.         for row in self.__data:
  149.             print(str(row[0]) + ',' + row[1] + ',' + row[2])
  150.  
  151.     def save(self, new_csv_file=None):
  152.         """
  153.        save the the highscore list
  154.        """
  155.         store_file = None
  156.         if isinstance(new_csv_file, str):
  157.             store_file = new_csv_file
  158.         else:
  159.             store_file = self.__csv_file
  160.  
  161.         if store_file is None:
  162.             if self.__verbose:
  163.                 print("HighScoreCSV#save: store file name not available")
  164.             return False
  165.  
  166.         try:
  167.             with open(store_file, 'w') as csvfile:
  168.                 csvwriter = csv.writer(csvfile, dialect='unix', quoting=csv.QUOTE_MINIMAL)
  169.                 csvwriter.writerow(self.__fieldNames)
  170.                 for row in self.__data:
  171.                     csvwriter.writerow(row)
  172.         except Exception as e:
  173.             print("HighScoreCSV#save: ERROR:", e)
  174.             return False
  175.         return True
  176.  
  177.  
  178. if __name__ == '__main__':
  179.     hs = HighScoreCSV("./highscore.csv")
  180.     # hs = HighScoreCSV("./highscore.csv", verbose=True)
  181.     print('csv_file        ', ':', hs.csv_file)
  182.     print('verbose         ', ':', hs.verbose)
  183.     print('maxscores       ', ':', hs.maxscores)
  184.     print('entries         ', ':', hs.entries)
  185.     print('properly loaded ', ':', hs.is_properly_loaded)
  186.     print("")
  187.     hs.add_score(1, "Player1")
  188.     print('entries   ', ':', hs.entries)
  189.     hs.add_score(1, "Player2")
  190.     print('entries   ', ':', hs.entries)
  191.     hs.add_score(1, "Player3")
  192.     print('entries   ', ':', hs.entries)
  193.     hs.add_score(1, "Player4")
  194.     print('entries   ', ':', hs.entries)
  195.     hs.add_score(1, "Player5")
  196.     print('entries   ', ':', hs.entries)
  197.     hs.add_score(1, "Player6")
  198.     print('entries   ', ':', hs.entries)
  199.     hs.add_score(1, "Player7")
  200.     print('entries   ', ':', hs.entries)
  201.     hs.add_score(1, "Player8")
  202.     print('entries   ', ':', hs.entries)
  203.     hs.add_score(1, "Player9")
  204.     print('entries   ', ':', hs.entries)
  205.     hs.add_score(1, "Player10")
  206.     print('entries   ', ':', hs.entries)
  207.     hs.add_score(1, "Player11")
  208.     print('entries   ', ':', hs.entries)
  209.     hs.add_score(1, "Player12")
  210.     print('entries   ', ':', hs.entries)
  211.     hs.add_score(1, "Player13")
  212.     print('entries   ', ':', hs.entries)
  213.     hs.add_score(1, "Player14")
  214.     print('entries   ', ':', hs.entries)
  215.     hs.add_score(3, "Player15")
  216.     print('entries   ', ':', hs.entries)
  217.     print("----------")
  218.     print("Highscore list:")
  219.     hs.print_scores()
  220.     print("----------")
  221.     hs.save()
  222.     # hs.save(new_csv_file='highscore2.csv')
Advertisement
Add Comment
Please, Sign In to add comment