Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- debug = True # only for debugging
- colors = ["RED", "YELLOW", "BLACK"]
- DB = None
- # ---------------- Data Declaration ---------------- ##
- # simple class for the cards
- class Card:
- # constructor
- def __init__(self):
- # generate a random card number and color
- self.num = random.randint(1, 10)
- self.color = colors[random.randint(0, len(colors) - 1)]
- # returns first letter of self.color + self.num e.g. R2, Y10, B6
- def get_card(self):
- return self.color[0] + str(self.num)
- def get_card_color(self):
- return self.color
- def get_card_num(self):
- return self.num
- def randomize_color(self):
- self.color = colors[random.randint(0, len(colors) - 1)]
- def randomize_number(self):
- self.num = random.randint(1, 10)
- def randomize(self):
- randomize_color()
- randomize_number()
- # simple class for the players
- class Player:
- # constructor
- def __init__(self, username="bot", total_score=0):
- # player deck
- self.deck = []
- self.score = 0
- self.total_score = total_score
- # login information
- self.username = username
- # this identifies whether the Player is a bot or not
- if self.username == "bot":
- self.is_bot = True
- # appends card to self.deck and adds the card number to self.deck_total
- def add_card(self, card):
- self.deck.append(card)
- self.score = self.score + card.get_card_num()
- # returns players score
- def get_player_score(self):
- return self.score
- # returns deck
- def get_player_deck(self):
- return self.deck
- # removes all the values in the players deck so they can play again
- def empty_player_deck(self):
- for i in len(self.deck):
- del self.deck[i]
- self.score = 0
- def is_player_bot(self):
- return self.is_bot
- def get_username(self):
- return self.username
- def get_score(self):
- return self.total_score
- # add n to the players total score and return it
- def update_score(self, n):
- self.total_score + n
- return self.total_score
- class Database():
- def __init__(self):
- # self.players will be a list that contains dictionaries
- self.players = []
- self.db_file = open("userdb.txt", "r+")
- self.db_data = self.db_file.readlines()
- self.currently_logged_in = None
- self.player_obj = None
- # reads all the logins in self.db_file and stores them as a dictionary in self.players
- def read_login_file(self):
- for i in self.db_data:
- i = i.split(',')
- name = i[0].strip()
- password = i[1].strip()
- score = i[2].strip()
- # check if the score field contains any other chracters than numbers
- for c in range(len(score)):
- if score[c].isdigit() == False:
- print("c: ", i[2][c])
- print("Fatal Error: invalid syntax in csv file")
- print("score field contains a chracter other than a number")
- print("exiting")
- exit()
- player_login = {'name': name, 'password': password, 'total_score': int(score)}
- self.players.append(player_login)
- # log the user in
- def authenticate(self, player_username, player_password):
- # check if the user is debugging
- if player_username == "debug" and debug == True:
- print("------------ Debug Mode ------------")
- self.currently_logged_in = {'name': 'debug', 'password': 'debug', 'total_score': 0}
- return True
- # if the user is not allowed to debug
- else:
- print("You cant debug")
- return False
- for i in self.players:
- if player_username == i['name']:
- print("name: ", i['name'])
- # if user authenticated. return True
- if player_password == i['password']:
- self.currently_logged_in = i
- return True
- else:
- print("password is wrong")
- else:
- print("user does not exist")
- # return False if user wasnt authenticated
- return False
- # sorts all the logins based on score
- # uses bubble sort
- def sort_data(self):
- n = len(self.players)
- # go through all the player logins
- for i in range(n):
- curr_player = self.players[n]
- next_player = self.players[n + 1]
- for i in range(n):
- pass
- # creates a player object for the currently logged in user
- def create_player_obj(self):
- self.player_obj = Player(self.currently_logged_in['name'], self.currently_logged_in['total_score'])
- return self.player_obj
- def __del__(self):
- # sort self.players
- self.sort_data()
- # close the database file
- self.db_file.close()
- game_deck = []
- players = []
- game_deck_total = 0
- # ---------------- Data Declaration ---------------- #
- # --------------- Function Defenitions --------------- #
- # checks for duplicates.
- # slow because the function uses recursion
- def clear_duplicates():
- current_card = None
- amount_of_duplicates = 0
- w = 0
- for i in range(len(game_deck)):
- # get a card
- current_card = game_deck[i]
- # if this this loop finds current_card in game_deck the card values are rerandomized
- for c in game_deck:
- # print("color of current_card: ", current_card.get_card_color(), "color of c: ", c.get_card_color()) # Debugging Only
- if current_card.get_card_color() == c.get_card_color():
- print("its the same") # Debugging Only
- # w = w + 1
- # print("W: ", w) # Debugging Only
- if current_card.get_card_num() == c.get_card_num():
- game_deck[i].randomize_number()
- amount_of_duplicates = amount_of_duplicates + 1
- else:
- print("Not the same") # Debugging Only
- print(amount_of_duplicates) # Debugging Only
- # this if statement protects the function call itself infintely
- if amount_of_duplicates != 0:
- # calls itself again one more time
- clear_duplicates()
- # this function prepares the game
- def init_game():
- global players
- # fills the games deck with cards
- global game_deck_total
- for i in range(30):
- game_deck.append(Card())
- # clear_duplicates()
- # gets the total value of each card and stores them in deck_total
- for i in game_deck:
- game_deck_total = game_deck_total + i.get_card_num()
- # prepare the players
- # create a Player object and store login information
- players.append(DB.create_player_obj())
- # create a bot Player
- players.append(Player("bot"))
- # emptys the games deck and the the players deck
- def empty_all_decks():
- # the games deck mght be empty depending on when this function was called
- if len(game_deck) != 0:
- for i in range(len(game_deck)):
- del game_deck[i]
- for i in range(len(players)):
- # the players decks might be empty depending on when this function was called
- if len(player[i].get_player_deck) != 0:
- # clear all of the players decks
- for i in range(len(player[i].get_player_deck)):
- del player[i].get_player_deck[i]
- # saves user data
- def save_data():
- print("-------------------------")
- print(" Storing Game Data")
- print("-------------------------")
- # the main game
- def main_game():
- print("--------------- Game ---------------")
- # elements are going to be erased from game_deck
- while len(game_deck) != 0:
- # since the fisrt 2 cards are going to be
- # erased we can access the elements with there index
- card0 = game_deck[0]
- card1 = game_deck[1]
- win_dictionary = {
- "REDBLACK": players[0],
- "BLACKRED": players[1],
- "YELLOWRED": players[0],
- "REDYELLOW": players[1],
- "BLACKYELLOW": players[0],
- "YELLOWBLACK": players[1]
- }
- # if the colors are the same compare the card numbers
- if card0.get_card_color() == card1.get_card_color():
- if card0.get_card_num() > card1.get_card_num():
- # prints the first letter of the color and its number e.g R8
- print("player 1 wins: ", card0.get_card(), "and: ", card1.get_card())
- players[0].add_card(card0)
- players[0].add_card(card1)
- else:
- print("player 2 wins: ", card0.get_card(), "and: ", card1.get_card())
- players[1].add_card(card0)
- players[1].add_card(card1)
- else: # winning/losing based on card color
- concard = card0.get_card_color() + card1.get_card_color() # names of the card colors contcatenated
- winner = win_dictionary.get(concard) # search the win_dictionary for that combonation of cards
- if winner == None:
- print("Fatal error exiting.")
- quit()
- # if winner.get() returns player[0] means player 1 has won
- if winner == players[0]:
- print("player 1 wins: ", card0.get_card(), "and: ", card1.get_card())
- players[0].add_card(card0)
- players[0].add_card(card1)
- # else player2 won
- else:
- print("player 2 wins: ", card0.get_card(), "and: ", card1.get_card())
- players[1].add_card(card0)
- players[1].add_card(card1)
- # remove the cards from game_deck
- # if the length of game deck is 2 remove game_deck[0] twice
- # because when you delete game_deck[1] it becomes game_deck[0]
- # if you try to delete game_deck[1] its not going to be able too because it doesnt exist.
- del game_deck[0]
- del game_deck[0]
- # print("removed two cards. game_deck size is: ", len(game_deck)) # debugging only
- # this function is used as a frontend for the user
- def main():
- global debug
- global DB
- tries = 3
- authenticated = False
- # prepare the database
- DB = Database()
- DB.read_login_file()
- # debug authenticatication
- if debug == True:
- DB.authenticate("debug", "debug")
- # normal player authentication
- else:
- # while tries is not equal to or less than 0
- while not(tries <= 0):
- # this code loops three times
- # this is where the user authenticates
- username = input("Enter your username: ")
- password = input("Enter your password: ")
- # if the user didnt authenticate
- if DB.authenticate(username, password) == False:
- tries = tries - 1
- print("you have: ", tries, " tries left")
- # if the user authenticated
- else:
- print("you have successfully authenticated")
- print("starting the game")
- authenticated = True
- # if the user failed to authenticate three times
- if authenticated == False:
- print("you have failed to login three times")
- print("exiting")
- exit
- init_game()
- main_game()
- # game is finished
- # print Player scores
- print("------------ Scores ------------")
- print(players[0].get_username(), " has a total score of: ", players[0].get_player_score())
- print(players[1].get_username(), " has a total score of: ", players[1].get_player_score())
- save_data()
- # --------------- Function Defenitions --------------- #
- # calls main if this file isnt imported in another file
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement