SHARE
TWEET

WOW

a guest Oct 14th, 2019 140 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import random
  2.  
  3. debug = True # only for debugging
  4. colors = ["RED", "YELLOW", "BLACK"]
  5. DB = None
  6.  
  7. # ---------------- Data Declaration ---------------- ##
  8. # simple class for the cards
  9. class Card:
  10.     # constructor
  11.     def __init__(self):
  12.         # generate a random card number and color
  13.         self.num = random.randint(1, 10)
  14.         self.color = colors[random.randint(0, len(colors) - 1)]
  15.  
  16.     # returns first letter of self.color + self.num e.g. R2, Y10, B6
  17.     def get_card(self):
  18.         return self.color[0] + str(self.num)
  19.  
  20.     def get_card_color(self):
  21.         return self.color
  22.  
  23.     def get_card_num(self):
  24.         return self.num
  25.  
  26.     def randomize_color(self):
  27.         self.color = colors[random.randint(0, len(colors) - 1)]
  28.  
  29.     def randomize_number(self):
  30.         self.num = random.randint(1, 10)
  31.  
  32.     def randomize(self):
  33.         randomize_color()
  34.         randomize_number()
  35.  
  36. # simple class for the players
  37. class Player:
  38.     # constructor
  39.     def __init__(self, username="bot", total_score=0):
  40.         # player deck
  41.         self.deck = []
  42.         self.score = 0
  43.         self.total_score = total_score
  44.  
  45.         # login information
  46.         self.username = username
  47.  
  48.         # this identifies whether the Player is a bot or not
  49.         if self.username == "bot":
  50.             self.is_bot = True
  51.  
  52.     # appends card to self.deck and adds the card number to self.deck_total
  53.     def add_card(self, card):
  54.         self.deck.append(card)
  55.         self.score = self.score + card.get_card_num()
  56.  
  57.     # returns players score
  58.     def get_player_score(self):
  59.         return self.score
  60.  
  61.     # returns deck
  62.     def get_player_deck(self):
  63.         return self.deck
  64.  
  65.     # removes all the values in the players deck so they can play again
  66.     def empty_player_deck(self):
  67.         for i in len(self.deck):
  68.             del self.deck[i]
  69.  
  70.         self.score = 0
  71.  
  72.     def is_player_bot(self):
  73.         return self.is_bot
  74.  
  75.     def get_username(self):
  76.         return self.username
  77.  
  78.     def get_score(self):
  79.         return self.total_score
  80.  
  81.     # add n to the players total score and return it
  82.     def update_score(self, n):
  83.         self.total_score + n
  84.         return self.total_score
  85.  
  86. class Database():
  87.     def __init__(self):
  88.         # self.players will be a list that contains dictionaries
  89.         self.players = []
  90.         self.db_file = open("userdb.txt", "r+")
  91.         self.db_data = self.db_file.readlines()
  92.         self.currently_logged_in = None
  93.         self.player_obj = None
  94.  
  95.     # reads all the logins in self.db_file and stores them as a dictionary in self.players
  96.     def read_login_file(self):
  97.         for i in self.db_data:
  98.             i = i.split(',')
  99.             name = i[0].strip()
  100.             password = i[1].strip()
  101.             score = i[2].strip()
  102.  
  103.             # check if the score field contains any other chracters than numbers
  104.             for c in range(len(score)):
  105.                 if score[c].isdigit() == False:
  106.                     print("c: ", i[2][c])
  107.                     print("Fatal Error: invalid syntax in csv file")
  108.                     print("score field contains a chracter other than a number")
  109.                     print("exiting")
  110.                     exit()
  111.  
  112.             player_login = {'name': name, 'password': password, 'total_score': int(score)}
  113.             self.players.append(player_login)
  114.  
  115.     # log the user in
  116.     def authenticate(self, player_username, player_password):
  117.  
  118.         # check if the user is debugging
  119.         if player_username == "debug" and debug == True:
  120.             print("------------ Debug Mode ------------")
  121.             self.currently_logged_in = {'name': 'debug', 'password': 'debug', 'total_score': 0}
  122.             return True
  123.  
  124.         # if the user is not allowed to debug
  125.         else:
  126.             print("You cant debug")
  127.             return False
  128.  
  129.         for i in self.players:
  130.             if player_username == i['name']:
  131.                 print("name: ", i['name'])
  132.                 #  if user authenticated. return True
  133.                 if player_password == i['password']:
  134.                     self.currently_logged_in = i
  135.                     return True
  136.  
  137.                 else:
  138.                     print("password is wrong")
  139.         else:
  140.             print("user does not exist")
  141.  
  142.         # return False if user wasnt authenticated
  143.         return False
  144.  
  145.     # sorts all the logins based on score
  146.     # uses bubble sort
  147.     def sort_data(self):
  148.         n = len(self.players)
  149.  
  150.         # go through all the player logins
  151.         for i in range(n):
  152.             curr_player = self.players[n]
  153.             next_player = self.players[n + 1]
  154.  
  155.             for i in range(n):
  156.                 pass
  157.  
  158.     # creates a player object for the currently logged in user
  159.     def create_player_obj(self):
  160.         self.player_obj = Player(self.currently_logged_in['name'], self.currently_logged_in['total_score'])
  161.         return self.player_obj
  162.  
  163.     def __del__(self):
  164.         # sort self.players
  165.         self.sort_data()
  166.  
  167.         # close the database file
  168.         self.db_file.close()
  169.  
  170. game_deck = []
  171. players = []
  172. game_deck_total = 0
  173.  
  174. # ---------------- Data Declaration ---------------- #
  175.  
  176. # --------------- Function Defenitions --------------- #
  177.  
  178. # checks for duplicates.
  179. # slow because the function uses recursion
  180. def clear_duplicates():
  181.     current_card = None
  182.     amount_of_duplicates = 0
  183.     w = 0
  184.     for i in range(len(game_deck)):
  185.         # get a card
  186.         current_card = game_deck[i]
  187.  
  188.         # if this this loop finds current_card in game_deck the card values are rerandomized
  189.         for c in game_deck:
  190.             # print("color of current_card: ", current_card.get_card_color(), "color of c: ", c.get_card_color()) # Debugging Only
  191.             if current_card.get_card_color() == c.get_card_color():
  192.                 print("its the same") # Debugging Only
  193.                 # w = w + 1
  194.                 # print("W: ", w) # Debugging Only
  195.                 if current_card.get_card_num() == c.get_card_num():
  196.                     game_deck[i].randomize_number()
  197.                     amount_of_duplicates = amount_of_duplicates + 1
  198.  
  199.             else:
  200.                 print("Not the same") # Debugging Only
  201.  
  202.         print(amount_of_duplicates) # Debugging Only
  203.  
  204.     # this if statement protects the function call itself infintely
  205.     if amount_of_duplicates != 0:
  206.         # calls itself again one more time
  207.         clear_duplicates()
  208.  
  209. # this function prepares the game
  210. def init_game():
  211.     global players
  212.     # fills the games deck with cards
  213.     global game_deck_total
  214.  
  215.     for i in range(30):
  216.         game_deck.append(Card())
  217.  
  218.     # clear_duplicates()
  219.  
  220.     # gets the total value of each card and stores them in deck_total
  221.     for i in game_deck:
  222.         game_deck_total = game_deck_total + i.get_card_num()
  223.  
  224.     # prepare the players
  225.     # create a Player object and store login information
  226.     players.append(DB.create_player_obj())
  227.  
  228.     # create a bot Player
  229.     players.append(Player("bot"))
  230.  
  231. # emptys the games deck and the the players deck
  232. def empty_all_decks():
  233.     # the games deck mght be empty depending on when this function was called
  234.     if len(game_deck) != 0:
  235.         for i in range(len(game_deck)):
  236.             del game_deck[i]
  237.  
  238.     for i in range(len(players)):
  239.         # the players decks might be empty depending on when this function was called
  240.         if len(player[i].get_player_deck) != 0:
  241.             # clear all of the players decks
  242.             for i in range(len(player[i].get_player_deck)):
  243.                 del player[i].get_player_deck[i]
  244.  
  245. # saves user data
  246. def save_data():
  247.     print("-------------------------")
  248.     print("  Storing Game Data")
  249.     print("-------------------------")
  250.  
  251.  
  252. # the main game
  253. def main_game():
  254.     print("--------------- Game ---------------")
  255.  
  256.     # elements are going to be erased from game_deck
  257.     while len(game_deck) != 0:
  258.         # since the fisrt 2 cards are going to be
  259.         # erased we can access the elements with there index
  260.         card0 = game_deck[0]
  261.         card1 = game_deck[1]
  262.         win_dictionary = {
  263.             "REDBLACK": players[0],
  264.             "BLACKRED": players[1],
  265.             "YELLOWRED": players[0],
  266.             "REDYELLOW": players[1],
  267.             "BLACKYELLOW": players[0],
  268.             "YELLOWBLACK": players[1]
  269.             }
  270.  
  271.         # if the colors are the same compare the card numbers
  272.         if card0.get_card_color() == card1.get_card_color():
  273.             if card0.get_card_num() > card1.get_card_num():
  274.                 # prints the first letter of the color and its number e.g R8
  275.                 print("player 1 wins: ", card0.get_card(), "and: ", card1.get_card())
  276.                 players[0].add_card(card0)
  277.                 players[0].add_card(card1)
  278.  
  279.             else:
  280.                 print("player 2 wins: ", card0.get_card(), "and: ", card1.get_card())
  281.                 players[1].add_card(card0)
  282.                 players[1].add_card(card1)
  283.  
  284.  
  285.         else: # winning/losing based on card color
  286.             concard = card0.get_card_color() + card1.get_card_color() # names of the card colors contcatenated
  287.             winner = win_dictionary.get(concard) # search the win_dictionary for that combonation of cards
  288.  
  289.             if winner == None:
  290.                 print("Fatal error exiting.")
  291.                 quit()
  292.  
  293.             # if winner.get() returns player[0] means player 1 has won
  294.             if winner == players[0]:
  295.                 print("player 1 wins: ", card0.get_card(), "and: ", card1.get_card())
  296.                 players[0].add_card(card0)
  297.                 players[0].add_card(card1)
  298.  
  299.             # else player2 won
  300.             else:
  301.                 print("player 2 wins: ", card0.get_card(), "and: ", card1.get_card())
  302.                 players[1].add_card(card0)
  303.                 players[1].add_card(card1)
  304.  
  305.         # remove the cards from game_deck
  306.         # if the length of game deck is 2 remove game_deck[0] twice
  307.         # because when you delete game_deck[1] it becomes game_deck[0]
  308.         # if you try to delete game_deck[1] its not going to be able too because it doesnt exist.
  309.         del game_deck[0]
  310.         del game_deck[0]
  311.         # print("removed two cards. game_deck size is: ", len(game_deck)) # debugging only
  312.  
  313. # this function is used as a frontend for the user
  314. def main():
  315.     global debug
  316.     global DB
  317.     tries = 3
  318.     authenticated = False
  319.  
  320.     # prepare the database
  321.     DB = Database()
  322.     DB.read_login_file()
  323.  
  324.     # debug authenticatication
  325.     if debug == True:
  326.         DB.authenticate("debug", "debug")
  327.  
  328.     # normal player authentication
  329.     else:
  330.         # while tries is not equal to or less than 0
  331.         while not(tries <= 0):
  332.             # this code loops three times
  333.             # this is where the user authenticates
  334.             username = input("Enter your username: ")
  335.             password = input("Enter your password: ")
  336.  
  337.             # if the user didnt authenticate
  338.             if DB.authenticate(username, password) == False:
  339.                 tries = tries - 1
  340.                 print("you have: ", tries, " tries left")
  341.  
  342.             # if the user authenticated
  343.             else:
  344.                 print("you have successfully authenticated")
  345.                 print("starting the game")
  346.                 authenticated = True
  347.  
  348.         # if the user failed to authenticate three times
  349.         if authenticated == False:
  350.             print("you have failed to login three times")
  351.             print("exiting")
  352.             exit
  353.  
  354.     init_game()
  355.     main_game()
  356.  
  357.     # game is finished
  358.     # print Player scores
  359.     print("------------ Scores ------------")
  360.     print(players[0].get_username(), " has a total score of: ", players[0].get_player_score())
  361.     print(players[1].get_username(), " has a total score of: ", players[1].get_player_score())
  362.  
  363.     save_data()
  364. # --------------- Function Defenitions --------------- #
  365.  
  366. # calls main if this file isnt imported in another file
  367. if __name__ == '__main__':
  368.     main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top