Skip to content

Commit

Permalink
refactor: added comments, cleaned up code.
Browse files Browse the repository at this point in the history
Addressed several issues with the codebase. See
issue ufosc#62 for some of the solved details.

- banker.py
-- Most notably added a more robust unit testing
manager. The user can create custom unit tests or
choose from a list of pre-made tests, which are
now detailed as they print to the screen.
-- Moved battleship and tictactoe handling from
handle_data() to their own respective functions.
-- Added validate_name()
-- Added comments, cleaned up code.
- modules.py
-- Moved calculator module from player.py to
modules.py. Streamlined a bit.
- monopoly.py
-- Fixed printing bug where the player's name
was not being printed as player.order instead of
player.name.
- networking.py
-- Added comments, cleaned up code.
- player_class.py
-- Renamed class symbol  from Player to
MonopolyPlayer to clear up some ambiguity. This is
 reflected in cards.py, board.py, monopoly.py
- player.py
-- Added inputting player name during
initialization.
-- Added bal function to get balance from banker.
-- Moved calculator module to modules.py
-- Added comments, cleaned up code.
- screenspace.py
-- Removed print_board()
-- Added whitelist to get_valid_int()
-- Added comments, cleaned up code.
- Deleted testclient.py, testserver.py
- Updated .gitignore
  • Loading branch information
adamgulde committed Nov 15, 2024
1 parent 898510b commit 8753e87
Show file tree
Hide file tree
Showing 12 changed files with 454 additions and 490 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
testclient.py
testserver.py
errorlog.txt
error_log.txt

# From: https://github.com/github/gitignore/blob/main/Python.gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
462 changes: 288 additions & 174 deletions banker.py

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions board.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from properties import Property
from style import COLORS
from player_class import Player
from player_class import MonopolyPlayer

class Board:
"""
Expand Down Expand Up @@ -52,7 +52,7 @@ def __init__(self, num_players) -> None:
39: Property(0, "Boardwalk", -1, (29,72), COLORS.BLUE, 400, 200, 50, 200, 600, 1400, 1700, 2000, 200),
}

def update_location(self, player:Player, roll: int, new = None) -> None:
def update_location(self, player:MonopolyPlayer, roll: int, new = None) -> None:
"""
Update location with player\n
@location: int\n
Expand All @@ -78,7 +78,7 @@ def update_location(self, player:Player, roll: int, new = None) -> None:
self.locations[new].players.append(player.order)
player.location = new

def current_location(self, player:Player) -> int:
def current_location(self, player:MonopolyPlayer) -> int:
"""
Return current location\n
@player: Player object\n
Expand Down
6 changes: 3 additions & 3 deletions cards.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import style as s
import random
from board import Board
from player_class import Player
from player_class import MonopolyPlayer

class Cards:
"""
Expand All @@ -13,7 +13,7 @@ def __init__(self) -> None:
self.community_chest = s.get_graphics().get('community chest text').split("\n")
random.shuffle(self.chance)
random.shuffle(self.community_chest)
def draw_chance(self, p: Player, board: Board, players) -> str:
def draw_chance(self, p: MonopolyPlayer, board: Board, players) -> str:
"""
Draw chance card\n
"""
Expand Down Expand Up @@ -78,7 +78,7 @@ def draw_chance(self, p: Player, board: Board, players) -> str:
case 16:
p.receive(150)
return self.chance[-1]
def draw_community_chest(self, p: Player, board: Board, players) -> str:
def draw_community_chest(self, p: MonopolyPlayer, board: Board, players) -> str:
"""
Draw community chest card\n
"""
Expand Down
111 changes: 73 additions & 38 deletions modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,35 @@
import keyboard
import time

def calculator() -> str:
"""A simple calculator module that can perform basic arithmetic operations."""
calculator_history_queue = []
calculator_history_current_capacity = 15

def calculator(active_terminal) -> str:
# Helper function that contructs terminal printing.
def calculator_terminal_response(footer_option: int) -> str:
calculator_header = "\nCALCULATOR TERMINAL\nHistory:\n"
footer_options = ["Awaiting an equation...\nPress 'e' to exit the calculator terminal.",
s.COLORS.BLUE+"Type 'calc' to begin the calculator!",
s.COLORS.RED+"Equation either malformed or undefined! Try again!\nPress 'e' to exit the calculator terminal"+s.COLORS.RESET]
response = calculator_header
for i in range(len(calculator_history_queue)-1, -1, -1):
response += calculator_history_queue[i][0]
response += '\n' + footer_options[footer_option]

return response

#Helper function to update calculator history
def update_history(equation: str) -> None:
global calculator_history_current_capacity

numLines = (len(equation)//75) + 1
while(numLines > calculator_history_current_capacity):
calculator_history_current_capacity += calculator_history_queue[0][1]
calculator_history_queue.pop(0)

calculator_history_current_capacity -= numLines
calculator_history_queue.append((equation, numLines))

#Uses recursion to calculate.
def calculate(equation: str) -> float:
for i in range(0, len(equation)-1):
Expand Down Expand Up @@ -53,43 +80,51 @@ def calculate(equation: str) -> float:

return float(equation)

response = '\nCALCULATOR TERMINAL\n'
digit_result = 0
print("\r", end='')
equation = input(s.COLORS.GREEN)
if(equation == "e"):
return equation

#Trims unnecessary spaces and pads operators with spaces
equation = equation.replace(" ", "")
for op in ['+', '-', '*', '/', '%', '^']:
equation = equation.replace(op, " " + op + " ")

#Removes spaces from negative number
if(len(equation) > 1 and equation[1] == '-'):
equation = "-" + equation[3:]

try:
digit_result = calculate(equation)
except:
return "error"

responseEQ = f'{equation} = {digit_result}'

#There are 75 columns for each terminal, making any string longer than 75 characters overflow.
numOverflowingChar = len(responseEQ) - 75
lineNumber = 0
wrappedResponse = ""
while(numOverflowingChar > 0):
wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1))] + '\n'
lineNumber = lineNumber + 1
numOverflowingChar = numOverflowingChar - 75

wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1)) + numOverflowingChar] + '\n'
#response += wrappedResponse
# Initial comment in active terminal
ss.update_quadrant(active_terminal, calculator_terminal_response(0), padding=True)
# All other work is done on the work line (bottom of the screen)
while True:

response = '\nCALCULATOR TERMINAL\n'
digit_result = 0
print("\r", end='')
equation = input(s.COLORS.GREEN)
print(s.COLORS.RESET, end="")
if(equation == "e"):
ss.update_quadrant(active_terminal, calculator_terminal_response(1), padding=True)
break

#Trims unnecessary spaces and pads operators with spaces
equation = equation.replace(" ", "")
for op in ['+', '-', '*', '/', '%', '^']:
equation = equation.replace(op, " " + op + " ")
#Removes spaces from negative number
if(len(equation) > 1 and equation[1] == '-'):
equation = "-" + equation[3:]

try:
digit_result = calculate(equation)
responseEQ = f'{equation} = {digit_result}'

#There are 75 columns for each terminal, making any string longer than 75 characters overflow.
numOverflowingChar = len(responseEQ) - 75
lineNumber = 0
wrappedResponse = ""
while(numOverflowingChar > 0):
wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1))] + '\n'
lineNumber = lineNumber + 1
numOverflowingChar = numOverflowingChar - 75

wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1)) + numOverflowingChar] + '\n'
#response += wrappedResponse

player_equation = wrappedResponse

print(s.COLORS.RESET, end='')
return wrappedResponse
print(s.COLORS.RESET, end='')
update_history(player_equation)
ss.update_quadrant(active_terminal, calculator_terminal_response(0))
except:
ss.update_quadrant(active_terminal, calculator_terminal_response(2), padding=True)

def list_properties() -> str:
"""
Expand Down
42 changes: 21 additions & 21 deletions monopoly.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from properties import Property
from cards import Cards
from board import Board
from player_class import Player
from player_class import MonopolyPlayer
import screenspace as ss
import style as s

Expand Down Expand Up @@ -125,7 +125,7 @@ def update_history(message: str):
history.pop(0)
refresh_h_and_s()

def update_status(p: Player, update: str, status: list = status, mode: str = "normal", property_id: str = ""):
def update_status(p: MonopolyPlayer, update: str, status: list = status, mode: str = "normal", property_id: str = ""):
"""
Update the status\n
"""
Expand All @@ -145,7 +145,7 @@ def update_status(p: Player, update: str, status: list = status, mode: str = "no
location = board.locations[int(propertyid)]
if location.owner > -1: # if the location is owned
color = COLORS.playerColors[location.owner]
status.append(f"Current owner: " + color + f"Player{location.owner}" + COLORS.RESET)
status.append(f"Current owner: " + color + f"{players[location.owner]}" + COLORS.RESET)
status.append(f"Houses: {location.houses}")
if(location.rent != 0): # if location could be owned and is not a utility or railroad
status.append(f"{location.color}=== {location.name} ===")
Expand Down Expand Up @@ -216,7 +216,7 @@ def buy_logic(mode: str = "normal", pinput: str = ""):
else:
update_history(f"{players[turn].name} did not buy {board.locations[CL].name}")

def housing_logic(p: Player, mode: str = "normal", propertyid: str = "", num_houses: int = -1):
def housing_logic(p: MonopolyPlayer, mode: str = "normal", propertyid: str = "", num_houses: int = -1):
update_status(p, "properties")
if mode == "normal":
propertyid = input(ss.set_cursor_str(0, 39) + "What property do you want to build on? Enter property # or 'e' to exit.")
Expand Down Expand Up @@ -344,7 +344,7 @@ def player_roll(num_rolls, act: int = 0, mode: str = "normal") -> str:
input("\033[36;0HRoll dice?")
dice = roll()
bottom_screen_wipe()
update_history(f"Player {turn} rolled {dice[0]} and {dice[1]}")
update_history(f"{players[turn]} rolled {dice[0]} and {dice[1]}")

if dice[0] == dice[1]:
if num_rolls == 1:
Expand All @@ -354,15 +354,15 @@ def player_roll(num_rolls, act: int = 0, mode: str = "normal") -> str:
update_history(f"{players[turn]} rolled doubles!(X2) Roll again.")

elif num_rolls == 3:
update_history(f"Player {turn} rolled doubles three times\n in a row!")
update_history(f"Player {turn} is going to jail!")
update_history(f"{players[turn]} rolled doubles three times\n in a row!")
update_history(f"{players[turn]} is going to jail!")
players[turn].jail = True
board.update_location(players[turn], -1)
refresh_board()
#if player rolled their third double they will be in jail and their location doesn't update
if players[turn].jail == False:
if (players[turn].location + dice[0] + dice[1]) > 39: # checks if player passed go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
board.update_location(players[turn], dice[0] + dice[1])
update_history(f"{players[turn].name} landed on {board.locations[players[turn].location].name}")
refresh_board()
Expand All @@ -382,14 +382,14 @@ def player_roll(num_rolls, act: int = 0, mode: str = "normal") -> str:
new_loc = players[turn].location
update_history(f"{players[turn].name} drew a Community Chest card! {card}")
if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: #check if chance card made player pass go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
case -4: #chance
old_loc = players[turn].location
card = decks.draw_chance(players[turn], board, players)
new_loc = players[turn].location
update_history(f"{players[turn].name} drew a Chance card! {card}")
if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: #check if chance card made player pass go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
if (board.locations[players[turn].location].owner != -4):
done_moving_around = False # only case where loop is needed
case -5: #income tax
Expand Down Expand Up @@ -451,7 +451,7 @@ def process_roll(num_rolls: int, dice: tuple) -> str:
TODO add more detail here
"""
bottom_screen_wipe()
update_history(f"Player {turn} rolled {dice[0]} and {dice[1]}")
update_history(f"{players[turn]} rolled {dice[0]} and {dice[1]}")

if dice[0] == dice[1]:
if num_rolls == 1:
Expand All @@ -461,15 +461,15 @@ def process_roll(num_rolls: int, dice: tuple) -> str:
update_history(f"{players[turn]} rolled doubles!(X2) Roll again.")

elif num_rolls == 3:
update_history(f"Player {turn} rolled doubles three times\n in a row!")
update_history(f"Player {turn} is going to jail!")
update_history(f"{players[turn]} rolled doubles three times\n in a row!")
update_history(f"{players[turn]} is going to jail!")
players[turn].jail = True
board.update_location(players[turn], -1)
refresh_board()
#if player rolled their third double they will be in jail and their location doesn't update
if players[turn].jail == False:
if (players[turn].location + dice[0] + dice[1]) > 39: # checks if player passed go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
board.update_location(players[turn], dice[0] + dice[1])
update_history(f"{players[turn].name} landed on {board.locations[players[turn].location].name}")
refresh_board()
Expand Down Expand Up @@ -499,14 +499,14 @@ def evaluate_board_location(num_rolls: int, dice: tuple) -> str:
new_loc = players[turn].location
update_history(f"{players[turn].name} drew a Community Chest card! {card}")
if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: #check if chance card made player pass go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
case -4: #chance
old_loc = players[turn].location
card = decks.draw_chance(players[turn], board, players)
new_loc = players[turn].location
update_history(f"{players[turn].name} drew a Chance card! {card}")
if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: #check if chance card made player pass go
update_history(f"Player {players[turn].order} passed Go and received $200")
update_history(f"{players[turn]} passed Go and received $200")
if (board.locations[players[turn].location].owner != -4):
done_moving_around = False # only case where loop is needed
case -5: #income tax
Expand Down Expand Up @@ -565,10 +565,10 @@ def player_choice():
choice = input("\033[38;0H'e' to end turn, p to manage properties, ?")
update_history(f"{players[turn]} ended their turn.")
else:
update_history(f"Player {turn} is in debt. Resolve debts before ending turn.")
update_history(f"{players[turn]} is in debt. Resolve debts before ending turn.")
option = input("\033[38;0HResolve debts before ending turn.").lower().strip()
if(option == "b"): # Declare bankruptcy
update_history(f"Player {turn} declared bankruptcy.")
update_history(f"{players[turn]} declared bankruptcy.")
players[turn].order = -1
elif(option == "m"): # Mortgage properties
pass
Expand Down Expand Up @@ -597,7 +597,7 @@ def start_game(cash: int, num_p: int) -> str:
decks = Cards()
players = []
for i in range(num_players):
players.append(Player(CASH, i))
players.append(MonopolyPlayer(CASH, i))

add_to_output(COLORS.WHITE + "\033[0;0H")
add_to_output(gameboard)
Expand All @@ -618,7 +618,7 @@ def game_loop():
# CASH = input("Starting cash?")
# num_players = int(input("Number players?"))
for i in range(num_players):
players.append(Player(CASH, i))
players.append(MonopolyPlayer(CASH, i))

turn = 0

Expand All @@ -644,6 +644,6 @@ def game_loop():
for index, player in enumerate(players):
if player.order != -1:
color = COLORS.playerColors[index]
update_history(color + f"Player {index} wins!")
update_history(color + f"{players[index]} wins!")
break
add_to_output("\033[40;0H")
Loading

0 comments on commit 8753e87

Please sign in to comment.