Skip to content

Commit

Permalink
Restructure directories fr
Browse files Browse the repository at this point in the history
  • Loading branch information
maryjess committed Oct 17, 2024
1 parent 9ab9ec8 commit fa8cd8e
Show file tree
Hide file tree
Showing 13 changed files with 273 additions and 0 deletions.
Binary file added 6nimmts/__pycache__/exceptions.cpython-311.pyc
Binary file not shown.
Binary file added 6nimmts/__pycache__/gameplay.cpython-311.pyc
Binary file not shown.
Binary file added 6nimmts/__pycache__/printing.cpython-311.pyc
Binary file not shown.
Binary file added 6nimmts/__pycache__/setup.cpython-311.pyc
Binary file not shown.
Binary file added 6nimmts/__pycache__/simulate.cpython-311.pyc
Binary file not shown.
Binary file added 6nimmts/__pycache__/utils.cpython-311.pyc
Binary file not shown.
21 changes: 21 additions & 0 deletions 6nimmts/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
def input_validation(validation_function):
def decorator(function):
def wrapper(*args, **kwargs):
while True:
# function() takes in args and kwargs
value = function(*args, **kwargs)
# validation_function() is the function that is used to validate the input
if validation_function(value):
return value
else:
print("Invalid input, please try again.")
return wrapper
return decorator

# Example use case, to be used in every input() calls
# @input_validation(lambda x: x.isdigit())
# def get_input(prompt):
# return input(prompt)

# Example test case for age
# age = get_input("Enter your age: ")
14 changes: 14 additions & 0 deletions 6nimmts/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class InvalidRowNumberException(Exception):
def __init__(self, message="The row number that you have inputted is not valid. Please try again."):
self.message = message
super().__init__(self.message)

class CardNotInHandException(Exception):
def __init__(self, message="The card that you have inputted is not in your hand! Please try again."):
self.message = message
super().__init__(self.message)

class CardParseError(Exception):
def __init__(self, message="The card format you've entered is invalid. Please try again."):
self.message = message
super().__init__(self.message)
15 changes: 15 additions & 0 deletions 6nimmts/gameplay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#from setup import set_up_cards, distribute_cards, set_up_decks #this is redundant

from simulate import simulate_debug, simulate

def play_game():
try:
print("Welcome to 6nimmts!")
mode = input("Which difficulty would you like to play? Please enter Easy or Normal: ")
if mode == "Debug":
simulate_debug()
else:
simulate(mode)
except KeyboardInterrupt:
print("Bye!")
exit()
4 changes: 4 additions & 0 deletions 6nimmts/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from gameplay import play_game

if __name__ == "__main__":
play_game()
7 changes: 7 additions & 0 deletions 6nimmts/printing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def print_deck(deck):
for row in deck:
print(row)

def print_players(players):
for player, hand in players.items():
print(f"Player {player}'s hand: {hand}")
155 changes: 155 additions & 0 deletions 6nimmts/simulate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
from setup import set_up_cards, distribute_cards, set_up_decks
from utils import place_card, parse_card, check_card_in_hand, ask_play_again
from printing import print_deck, print_players
from exceptions import InvalidRowNumberException, CardNotInHandException, CardParseError #exception has been imported
from random import randint

def simulate_debug():
win_condition = False
cards = []
deck = [[[13, 1], [0, 0], [0, 0], [0, 0], [0, 0]],
[[14, 1], [0, 0], [0, 0], [0, 0], [0, 0]],
[[23, 1], [0, 0], [0, 0], [0, 0], [0, 0]],
[[87, 1], [0, 0], [0, 0], [0, 0], [0, 0]]]
cards = set_up_cards(cards)
players, cards = distribute_cards(4, cards)
players[1] = [[32, 1], [96, 1], [45, 2], [23, 1], [17, 1], [56, 1], [3, 1], [85, 2], [11, 5]]

print_deck(deck)
print_players(players)

for _ in range(3):
print("Here are your cards:", players[1])
cards_to_place = []
for i in range(4):
if len(players[i + 1]) == 0:
print(f"Player {i + 1} wins! Congratulations.")
win_condition = True
break
if i == 0:
print("Your turn")
else:
print(f"Player {i + 1}'s turn")
cards = players[i+1]
if i == 0:
card = input("(Type in format, [<number>, <cattle>]): ")
try:
card = parse_card(card)
check_card_in_hand(card, cards)
except CardParseError:
card = input("The card format you've entered is invalid. Please enter the card again:")
except CardNotInHandException:
card = input("Error: The card you inputted is not in your hand! Please retype the card that you would like to place: ")
else:
cards.sort(key=lambda x:x[0])
cards.sort(key=lambda x:x[1], reverse=True)
card = cards[0]
cards_to_place.append((card, i))
if win_condition:
break
cards_to_place.sort(key=lambda x: x[0][0])
for c, p in cards_to_place:
players, deck = place_card(players, p + 1, c, deck)
print('---')
print_deck(deck)
print('---')
print("end of turn")
print_deck(deck)
if win_condition:
print("Thanks for playing!")
exit()
print('===')
print("final deck condition:")
print_deck(deck)
print("---")
print("final players condition:")
print_players(players)
print("calculating winner...")
print(determine_winners(players))
ask_play_again()

def simulate(difficulty):
#with the old code, if the user enter incorrect difficulty for the second time,
#the code will continue to set up card with incorrect difficulty
correct_input = False
difficulty = 'NA'
while correct_input == False:
if difficulty not in ['Easy', 'Normal']:
difficulty = input("The difficulty you've entered is invalid! Please either enter Easy or Normal: ")
else:
correct_input = True

win_condition = False
#do not create cards here, its better to cards=[] in setup.set_up_cards()
#do not create cards here, its better to deck=[] in setup.set_up_decks()
cards = set_up_cards(cards)
players, cards = distribute_cards(4, cards)
deck, cards = set_up_decks(cards, deck)
print_deck(deck)

for _ in range(10):
print("Here are your cards:", players[1])
cards_to_place = []
for i in range(4):
if len(players[i + 1]) == 0:
print(f"Player {i + 1} wins! Congratulations.")
win_condition = True
break
if i == 0:
print("Your turn")
else:
print(f"Player {i + 1}'s turn")
cards = players[i+1]
if i == 0:
card = input("(Type in format, [<number>, <cattle>]): ")
try:
card = parse_card(card)
check_card_in_hand(card, cards)
except CardParseError:
card = input("The card format you've entered is invalid. Please enter the card again:")
except CardNotInHandException:
card = input("Error: The card you inputted is not in your hand! Please retype the card that you would like to place: ")
else:
if difficulty == 'Easy':
card = cards[randint(0, len(cards) - 1)]
else:
cards.sort(key=lambda x:x[0])
cards.sort(key=lambda x:x[1], reverse=True)
card = cards[0]
cards_to_place.append((card, i))
if win_condition:
break
cards_to_place.sort(key=lambda x: x[0][0])
for c, p in cards_to_place:
players, deck = place_card(players, p + 1, c, deck)
print('---')
print_deck(deck)
print('---')
print("end of turn")
print_deck(deck)
if win_condition:
ask_play_again()
print('===')
print("final deck condition:")
print_deck(deck)
print("---")
print("calculating winner...")
print(determine_winners(players))
ask_play_again()

def determine_winners(players):
current_winner = None
winning_penalty = 0
for p, cards in players.items():
current_penalty = 0
for c in cards:
current_penalty += c[1]
if winning_penalty > current_penalty:
winning_penalty = current_penalty
current_winner = p

#havent consider tie
if current_winner is not None:
return f'The winner is Player {current_winner}! Congratulations.'
else:
return f'No winner could be determined.'
57 changes: 57 additions & 0 deletions 6nimmts/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
def place_card(players, player, card, deck):
num_of_rows = 4
num_of_cols = 5
empty_card = [0, 0]

if card not in players[player]:
print("Error: The card you inputted is not in your hand! Please retype the card that you would like to place: ")
return

players[player].remove(card)
to_place = card
to_place_index = 0
placed = False

for j in range(num_of_rows):
if deck[j][num_of_cols - 1] == empty_card:
if deck[j][0][0] < card[0] and deck[j][to_place_index][0] < card[0]:
to_place = card
to_place_index = j

for j in range(num_of_cols - 1):
if not placed:
if deck[to_place_index][j] == empty_card:
deck[to_place_index][j] = card
placed = True
if j == num_of_cols - 2:
for k in range(num_of_cols - 1):
deck[to_place_index][k] = empty_card
deck[to_place_index][0] = card
players[player].append(deck[to_place_index][j])

return players, deck

def parse_card(card):
card = card.strip('][').split(', ')
if len(card) != 2:
raise CardParseError("Invalid card format")
try:
card = [int(card[0]), int(card[1])]
except ValueError:
raise CardParseError("Card number or cattle count is not an integer")
return card

def check_card_in_hand(card, cards):
if card not in cards:
raise CardNotInHandException("Card not in hand")


def ask_play_again():
play_again = input("Would you like to play again? Type Yes or No: ")
if play_again == "Yes":
difficulty = input("Which difficulty you would like to play? Type Easy or Normal: ")
from simulate import simulate
simulate(difficulty)
else:
print("Thanks for playing! Hope to see you again.")
exit()

0 comments on commit fa8cd8e

Please sign in to comment.