Skip to content

Add autopep8 lint action #2

Add autopep8 lint action

Add autopep8 lint action #2

Triggered via push October 22, 2024 21:43
Status Failure
Total duration 29s
Artifacts

pylint.yml

on: push
Matrix: build
Fit to window
Zoom out
Zoom in

Annotations

154 errors and 2 warnings
battleship.py#L3
import random import os + class Ship(): """ Patrol
battleship.py#L28
║»║¤║«║ ╚═╩═╩═╝ """ + def __init__(self, x: int, y: int, name: str) -> None: self.x = x self.y = y if name == "patrol": self.icon = "╔═╗╚═╝" - self.size = (3,2) + self.size = (3, 2) self.name = "Patrol Boat" self.health = 1 elif name == "submarine": self.icon = "╔══╦╗╚══╩╝" - self.size = (5,2) + self.size = (5, 2) self.name = "Submarine" self.health = 3 elif name == "destroyer": self.icon = "╔═╦╩╗╣ ╠╣╠╚═╩╦╝" - self.size = (5,3) + self.size = (5, 3) self.name = "Destroyer" self.health = 3 elif name == "battleship": self.icon = "╔╩╩╩╩╗╣╬╬╬╬╠╚╦╦╦╦╝" - self.size = (6,3) + self.size = (6, 3) self.name = "Battleship" self.health = 4 elif name == "carrier": self.icon = "╔═╦═╦═╗║»║¤║«║╚═╩═╩═╝" - self.size = (7,3) + self.size = (7, 3) self.name = "Aircraft Carrier" self.health = 5 - else: + else: print("Invalid ship name.") def in_bounds(self, x, y) -> bool: return x + self.size[0] <= ss.cols and y + self.size[1] <= ss.rows and x >= 2 and y >= 1 - + def __str__(self) -> str: return self.name - + + class BattleshipGame(): """ Battleship Game
battleship.py#L72
Version: 1.0.0 https://en.wikipedia.org/wiki/Battleship_(game) """ + def __init__(self) -> None: self.board = self.generate_water_and_coords() self.players = 1 self.player_names = [] self.ships = [[] * self.players] self.changed_coords = [] - self.gamestate = 'placing ships' # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + self.gamestate = 'placing ships' def generate_water_and_coords(self) -> str: texture = "" texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK for x in range(0, ss.cols, 3): - texture += f"{x} " if x < 10 else f"{x} " + texture += f"{x} " if x < 10 else f"{x} " texture += "\n" for y in range(1, ss.rows): texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK - texture += (str(y) + (" " if y < 10 else "") if y % 2 == 0 else " ") + texture += (str(y) + (" " if y < 10 else "") if y % + 2 == 0 else " ") texture += f"{s.COLORS.backLIGHTBLUE}{s.COLORS.BLUE}" for _ in range(ss.cols-2): texture += random.choices( ["░", "▒", "▓"], - weights=[1, 2, 7], # Adjust weights to create larger pools of dark textures + # Adjust weights to create larger pools of dark textures + weights=[1, 2, 7], k=1 )[0] texture += "\n" self.board = texture + s.COLORS.RESET return self.board - def print_ship(self, sh: Ship, playerNum = 0) -> str: + def print_ship(self, sh: Ship, playerNum=0) -> str: text = s.COLORS.playerColors[playerNum] for i in range(sh.size[1]): text += f"{s.set_cursor_str(sh.x+1,sh.y+i+1)}{sh.icon[i*sh.size[0]:(i+1)*sh.size[0]]}\n"
battleship.py#L108
def print_explosion(self, x: int, y: int) -> str: text = "" - text += s.set_cursor_str(x,y) + random.choice([s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice( + [s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) return text def print_miss(self, x: int, y: int) -> str: text = s.COLORS.LIGHTGRAY - text += s.set_cursor_str(x,y) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice(["░", "▒", "▓"]) return text - def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: + def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: """ ...fill in comment x and y params should be top left corner of terminal.
battleship.py#L132
if 0 < i < 4: # Custom text wrapping p += s.set_cursor_str(27, 5+i) + message[(i-1)*26:(i-1)*26+26] - return p + return p def get_valid_int(self, prompt): while True:
battleship.py#L141
value = int(input(prompt)) return value except ValueError: - self.popup("Invalid input. Please enter a valid integer.", s.COLORS.RED) + self.popup( + "Invalid input. Please enter a valid integer.", s.COLORS.RED) s.set_cursor(0, ss.INPUTLINE) def is_overlapping(self, x: int, y: int, size: tuple, player_num: int) -> Ship: for sh in self.ships[player_num]: if (x < sh.x + sh.size[0] and x + size[0] > sh.x and - y < sh.y + sh.size[1] and y + size[1] > sh.y): + y < sh.y + sh.size[1] and y + size[1] > sh.y): return sh return None - def place_ships(self, current_board:str, player_num:int = 0) -> str: + def place_ships(self, current_board: str, player_num: int = 0) -> str: return_board = current_board s.set_cursor(0, ss.INPUTLINE) - ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), - Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] + ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), + Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] self.ships[player_num].clear() return_board = self.get_ship_board(player_num) for ship in ships_to_place: - while ship.x == -1 : + while ship.x == -1: x = self.get_valid_int(f"Enter x-coordinate for your {ship}: ") y = self.get_valid_int(f"Enter y-coordinate for your {ship}: ") - + if ship.in_bounds(x, y): if self.is_overlapping(x, y, ship.size, player_num) == None: ship.x = x
battleship.py#L173
else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-ship.size[0]}. Max y is {ss.rows-ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) + return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - + done = input("Does this look good? n for no, anything else for yes.") if done == 'n': while done != 'y': - move = self.get_valid_int(f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") + move = self.get_valid_int( + f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") if 0 <= move < len(self.ships[player_num]): self.ships[player_num].pop(move) return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - ship_names = ['patrol', 'submarine', 'destroyer', 'battleship', 'carrier'] + ship_names = ['patrol', 'submarine', + 'destroyer', 'battleship', 'carrier'] new_ship = Ship(-1, -1, ship_names[move]) while new_ship.x == -1: - x = self.get_valid_int(f"Enter x-coordinate for your {new_ship}: ") - y = self.get_valid_int(f"Enter y-coordinate for your {new_ship}: ") - + x = self.get_valid_int( + f"Enter x-coordinate for your {new_ship}: ") + y = self.get_valid_int( + f"Enter y-coordinate for your {new_ship}: ") + if new_ship.in_bounds(x, y): if self.is_overlapping(x, y, new_ship.size, player_num) == None: new_ship.x = x
battleship.py#L199
return self.popup(f"Error! This ship is on another ship. Recall this ship size is {new_ship.size}", s.COLORS.RED) else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-new_ship.size[0]}. Max y is {ss.rows-new_ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) - done = input("Does this look good? y for yes, anything else for no.") + return_board = self.get_ship_board(player_num) + done = input( + "Does this look good? y for yes, anything else for no.") return return_board - def get_ship_board(self, player_num:int) -> str: + def get_ship_board(self, player_num: int) -> str: # os.system("cls") current_board = self.board for ship in self.ships[player_num]:
battleship.py#L212
return current_board def attack(self): - while(len(self.ships) > 0): # not correct final logic, temporary + while (len(self.ships) > 0): # not correct final logic, temporary s.set_cursor(0, ss.INPUTLINE) x = self.get_valid_int("Enter x-coordinate for your attack: ") if x < 2 or x > 74: - self.popup("Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) continue y = self.get_valid_int("Enter y-coordinate for your attack: ") if y < 1 or y > 19: - self.popup("Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) continue - if (x,y) in self.changed_coords: - self.popup("Error! This coordinate has already been attacked.", s.COLORS.RED) + if (x, y) in self.changed_coords: + self.popup( + "Error! This coordinate has already been attacked.", s.COLORS.RED) continue - else: - self.changed_coords.append((x,y)) + else: + self.changed_coords.append((x, y)) for player_ship_list in self.ships: for ship in player_ship_list: - if self.is_overlapping(x, y, (1,1)) == ship: - self.popup(f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) + if self.is_overlapping(x, y, (1, 1)) == ship: + self.popup( + f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) self.board += self.print_explosion(x+1, y+1) ship.health -= 1 if ship.health == 0: player_ship_list.remove(ship) for i in range(ship.size[0]): for j in range(ship.size[1]): - self.board += self.print_explosion(ship.x+i+1, ship.y+j+1) - self.popup(f"You sunk the {ship.name}!", s.COLORS.dispBLUE) + self.board += self.print_explosion( + ship.x+i+1, ship.y+j+1) + self.popup( + f"You sunk the {ship.name}!", s.COLORS.dispBLUE) break else: self.popup("Miss!.", s.COLORS.RED)
battleship.py#L246
s.set_cursor(0, ss.INPUTLINE) input("Press enter to continue.") print(self.get_board()) - + + def start_game() -> BattleshipGame: ships = BattleshipGame() return ships + if __name__ == "__main__": os.system("cls")
battleship.py#L263
# def unittest1(): # ships.p1ships = [Ship(3,10,"patrol"), Ship(12,2,"submarine"), Ship(33,5,"destroyer"), Ship(50,7,"battleship"), Ship(15,9,"carrier")] - # unittest1() - - # ships.attack() + # unittest1() + + # ships.attack()
modules.py#L4
from socket import socket as Socket import networking as net + def calculator() -> str: """A simple calculator module that can perform basic arithmetic operations.""" - #Uses recursion to calculate. + # Uses recursion to calculate. def calculate(equation: str) -> float: for i in range(0, len(equation)-1): - if(equation[i] == '+'): + if (equation[i] == '+'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) + calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '-'): - #Checks for unary operator '-' - if(i == 0): + if (equation[i] == '-'): + # Checks for unary operator '-' + if (i == 0): eqLeft = "0" else: eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) - calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '*'): + if (equation[i] == '*'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) * calculate(eqRight) for i in range(0, len(equation)-1): - if(equation[i] == '/'): + if (equation[i] == '/'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft)/calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '%'): + if (equation[i] == '%'): eqLeft = equation[:i] eqRight = equation[(i+1):] - return calculate(eqLeft)%calculate(eqRight) - + return calculate(eqLeft) % calculate(eqRight) + for i in range(0, len(equation)-1): - if(equation[i] == '^'): + if (equation[i] == '^'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) ** calculate(eqRight) - + return float(equation) - response = '\nCALCULATOR TERMINAL\n' + response = '\nCALCULATOR TERMINAL\n' digit_result = 0 print("\r", end='') equation = input(s.COLORS.GREEN) - if(equation == "e"): + if (equation == "e"): return equation - - #Trims unnecessary spaces and pads operators with spaces + + # 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] == '-'): + + # 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. + # 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' + 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 + + wrappedResponse += responseEQ[(75*lineNumber) :(75*(lineNumber + 1)) + numOverflowingChar] + '\n' + # response += wrappedResponse print(s.COLORS.RESET, end='') return wrappedResponse + def list_properties() -> str: """ Temporary function to list all properties on the board by calling the property list stored in ascii.txt. Can be reworked to add color and better formatting. - + Parameters: None Returns: None """ ret_val = "" props = s.get_graphics().get('properties').split('\n') for prop in props: - if prop == '': - ret_val += ' '.center(75) + '\n' + if prop == '': + ret_val += ' '.center(75) + '\n' continue first_word = prop.split()[0] color = getattr(s.COLORS, first_word.upper(), s.COLORS.RESET) centered_prop = prop.center(75) - ret_val +=color+ centered_prop + s.COLORS.RESET + '\n' + ret_val += color + centered_prop + s.COLORS.RESET + '\n' return ret_val + def trade(): pass + def mortgage(): pass + def roll(): pass + def gamble(): pass + def attack(): pass + def stocks(): pass + def battleship(server: Socket, gamestate: str) -> str: net.send_message(server, 'battleship') + fishing_game_obj = fishing_game() + + def fishing(gamestate: str) -> tuple[str, str]: """ Fishing module handler for player.py. Returns tuple of [visual data, gamestate] both as strings.
modules.py#L142
stdIn = fishing_game_obj.get_input() if stdIn == 'e': return '', 'e' - return fishing_game_obj.results(), 'e' + return fishing_game_obj.results(), 'e' case 'e': - return '', 'start' + return '', 'start' + def kill() -> str: return s.get_graphics()['skull'] + def disable() -> str: - result = ('X ' * round(ss.cols/2+0.5) + '\n' + - (' X' * round(ss.cols/2+0.5)) + '\n' - ) * (ss.rows//2) + result = ('X ' * round(ss.cols/2+0.5) + '\n' + + (' X' * round(ss.cols/2+0.5)) + '\n' + ) * (ss.rows//2) return result + def make_board(board_pieces) -> list[str]: board = [''] * 35
modules.py#L163
if board_pieces[i*80+j] != '\n': board[i] += (board_pieces[i*80+j]) return board -
properties.py#L1
import style as s from style import COLORS + class Property: """
properties.py#L24
rentHotel = 0 mortgage = 0 - def __init__(self, num_players:int, name:str, owner:int, position:tuple, color:COLORS, purchasePrice:int, housePrice:int, rent:int, rent1H:int, rent2H:int, rent3H:int, rent4H:int, rentHotel:int,mortgage:int) -> None: + def __init__(self, num_players: int, name: str, owner: int, position: tuple, color: COLORS, purchasePrice: int, housePrice: int, rent: int, rent1H: int, rent2H: int, rent3H: int, rent4H: int, rentHotel: int, mortgage: int) -> None: self.players = list(range(num_players)) self.name = name self.owner = owner
properties.py#L41
self.rent4H = rent4H self.rentHotel = rentHotel self.mortgage = mortgage - + def getPrice(self) -> int: if self.purchasePrice == 0: return -1
properties.py#L172
"Electric Company": (150, 4, 10, -1, -1, 75), "Water Works": (150, 4, 10, -1, -1, 75) } - """ + """
monopoly.py#L1
-# Monopoly game is played on Banker's terminal. +# Monopoly game is played on Banker's terminal. +from datetime import datetime import style as s from style import COLORS import random
monopoly.py#L10
from player_class import Player import screenspace as ss + def refresh_board(): """ Refresh the gameboard\n """ print(COLORS.RESET + "\033[0;0H", end="") print(gameboard) - for i in range(40): + for i in range(40): # This loop paints the properties on the board with respective color schemes color = board.locations[i].color backcolor = board.locations[i].color.replace("38", "48") - print(COLORS.backBLACK + color + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) - - if(board.locations[i].owner != -1): # If owned + print(COLORS.backBLACK + color + + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) + + if (board.locations[i].owner != -1): # If owned print(end=COLORS.RESET) color = f"\033[38;5;{board.locations[i].owner+1}m" - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") - - if(board.locations[i].owner == -3): # If community chest + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") + + if (board.locations[i].owner == -3): # If community chest print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.COMMUNITY + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.COMMUNITY + "▀" * 6) - - if(board.locations[i].owner == -4): # If chance + print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + + COLORS.COMMUNITY + "█" * 6) + print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + + COLORS.COMMUNITY + "▀" * 6) + + if (board.locations[i].owner == -4): # If chance print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) - - if(board.locations[i].houses > 0): # If there are houses + print( + f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) + print( + f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) + + if (board.locations[i].houses > 0): # If there are houses print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + COLORS.GREEN + "▀" * (board.locations[i].houses)) - - if(board.locations[i].houses == 5): # If there is a hotel + print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + + COLORS.GREEN + "▀" * (board.locations[i].houses)) + + if (board.locations[i].houses == 5): # If there is a hotel print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") - - if(board.locations[i].owner == -2): # If mortgaged + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") + + if (board.locations[i].owner == -2): # If mortgaged print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + COLORS.backLIGHTGRAY + "M") + print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + + COLORS.backLIGHTGRAY + "M") print(end=COLORS.RESET) for i in range(num_players): color = COLORS.playerColors[i] token = "◙" - print(color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") - + print( + color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") + print(end=COLORS.RESET) + def print_commands(): """
monopoly.py#L67
for j in range(len(commandsinfo[i])): print(f"\033[{34+i};79H" + commandsinfo[i][:j], end="") + history = [] + + def update_history(message: str): """ Update the history\n
monopoly.py#L75
Split the text into multiple lines (multiple entries to history variable)\n """ if "[38;5" in message: - if(((40 - (len(message) - 9)) * 2) == 0): - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) + if (((40 - (len(message) - 9)) * 2) == 0): + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) else: - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) else: if len(message) > 40: while len(message) > 40:
monopoly.py#L86
message = message[40:] history.append(message + " " * (40 - len(message))) if len(history) > 31: - while(len(history) > 31): + while (len(history) > 31): history.pop(0) refresh_h_and_s() + status = [] + + def update_status(p: Player, update: str, status: list = status): """ Update the status\n """ # Property status update (list all properties of player) status.clear() - if(update == "properties"): + if (update == "properties"): color = COLORS.playerColors[p.order] status.append(color + f"{p.name} has properties: " + COLORS.RESET) for i in range(len(p.properties)): - status.append(f"{p.properties[i]}: {board.locations[p.properties[i]].name}") - if(update == "deed"): + status.append( + f"{p.properties[i]}: {board.locations[p.properties[i]].name}") + if (update == "deed"): propertyid = input("What property to view? Enter property #") try: location = board.locations[int(propertyid)] - if location.owner > -1: # if the location is owned + 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"Player{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 + if (location.rent != 0): # if location could be owned and is not a utility or railroad status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") status.append(f"Price Per House: {location.housePrice}")
monopoly.py#L121
status.append(f"Rent w 4 houses: {location.rent4H}") status.append(f"Rent w hotel: {location.rentHotel}") status.append(f"Mortgage Value: {location.mortgage}") - elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility + elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") - status.append(f"Rent (or mltplr) with 1 owned: {location.rent1H}") - status.append(f"Rent (or mltplr) with 2 owned: {location.rent2H}") - status.append(f"Rent with 3 locations owned: {location.rent3H}") - status.append(f"Rent with 4 locations owned: {location.rent4H}") + status.append( + f"Rent (or mltplr) with 1 owned: {location.rent1H}") + status.append( + f"Rent (or mltplr) with 2 owned: {location.rent2H}") + status.append( + f"Rent with 3 locations owned: {location.rent3H}") + status.append( + f"Rent with 4 locations owned: {location.rent4H}") status.append(f"Mortgage Value: {location.mortgage}") else: raise ValueError
monopoly.py#L135
print(f"Invalid input. Please enter a # for a property.") refresh_h_and_s() + border = s.get_graphics().get('history and status') border = border.split("\n") + + def refresh_h_and_s(): """ Refresh the history, status, and leaderboard\n
monopoly.py#L144
# Refresh history for i in range(len(border)): print(f"\033[{i};79H", end="") - if(len(history) - i<= 0): + if (len(history) - i <= 0): for j in range(len(border[i])): print(border[i][j], end="") for i in range(len(history)): - print(f"\033[{i+4};81H" + history[i] if i < len(history) else "", end=COLORS.RESET) - + print(f"\033[{i+4};81H" + history[i] if i < + len(history) else "", end=COLORS.RESET) + # Refresh status for i in range(len(status)): print(f"\033[{i+4};122H" + status[i] if i < len(status) else "")
monopoly.py#L158
# Refresh leaderboard sorted_players = sorted(players, key=lambda x: x.cash, reverse=True) for i in range(len(sorted_players)): - if(sorted_players[i].order != -1): + if (sorted_players[i].order != -1): color = COLORS.playerColors[sorted_players[i].order] - print(color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + print( + color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + def buy_logic(): CL = players[turn].location choice = input("\033[37;0Hb to buy, enter to continue?") - if(board.locations[CL].purchasePrice != 0): + if (board.locations[CL].purchasePrice != 0): price = board.locations[CL].purchasePrice - if(players[turn].cash > price and choice == 'b'): + if (players[turn].cash > price and choice == 'b'): players[turn].buy(CL, board) board.locations[CL].owner = turn - update_history(f"{players[turn].name} bought {board.locations[CL].name} for ${price}") + update_history( + f"{players[turn].name} bought {board.locations[CL].name} for ${price}") else: - update_history(f"{players[turn].name} did not buy {board.locations[CL].name}") + update_history( + f"{players[turn].name} did not buy {board.locations[CL].name}") + def housing_logic(p: Player): update_status(p, "properties") - propertyid = input("What property do you want to build on? Enter property # or 'e' to exit."+ + propertyid = input("What property do you want to build on? Enter property # or 'e' to exit." + "\033[40;0H" + " " * 78+"\033[41;0H" + " " * 78+"\033[40;0H") flag = True exit = False - try: + try: if propertyid == 'e': exit = True else: - propertyid = int(propertyid) - except ValueError: ###AHHHHHHHH clean me please - print(f"\033[42;0" + COLORS.RED + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) + propertyid = int(propertyid) + except ValueError: # AHHHHHHHH clean me please + print(f"\033[42;0" + COLORS.RED + + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) flag = False if flag and not exit: if not propertyid in p.properties: print("You do not own this property!") - else: + else: family = board.locations[propertyid].color if family == COLORS.CYAN or family == COLORS.LIGHTBLACK or board.locations[propertyid].name.startswith("Electric"): print("This property cannot be improved.") flag = False - if flag: - for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): # check only a few properties around for efficiency + if flag: + # check only a few properties around for efficiency + for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): if board.locations[i].color == family: if not i in p.properties: print("You do not own a monopoly on these properties!")
monopoly.py#L214
elif 30 < propertyid < 40: cost = 200 max = 5 - board.locations[propertyid].houses - houses = input(f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") + houses = input( + f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") try: houses = int(houses) - if(0 <= houses <= max): + if (0 <= houses <= max): p.cash -= cost * houses - update_history(f"{p} bought {houses} houses on {board.locations[propertyid].name}!") + update_history( + f"{p} bought {houses} houses on {board.locations[propertyid].name}!") board.locations[propertyid].houses += houses refresh_board() else:
monopoly.py#L229
if not exit: housing_logic(p) + def mortgage_logic(): - input("\033[37;0HWhat property to mortgage?") - -from datetime import datetime + input("\033[37;0HWhat property to mortgage?") + + def log_error(error_message: str) -> None: """ Log error message to errorlog.txt\n
monopoly.py#L241
current_datetime = datetime.now() formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S') f.write(f"{formatted_datetime}\n{error_message}\n") + ss.make_fullscreen()
monopoly.py#L260
board = Board(num_players) decks = Cards() -import style as s gameboard = s.get_graphics().get('gameboard') os.system('cls' if os.name == 'nt' else 'clear') print(COLORS.WHITE + "\033[0;0H", end="") print(gameboard) + def unittest(): players[1].buy(1, board)
monopoly.py#L277
players[3].buy(12, board) players[3].buy(28, board) + unittest() -#wipes the bottom of the screen where the player does all of their input +# wipes the bottom of the screen where the player does all of their input + + def bottom_screen_wipe(): print("\033[36;0H" + " " * 76) print("\033[37;0H" + " " * 76)
monopoly.py#L290
print("\033[43;0H" + " " * 76) print("\033[44;0H" + " " * 76) -#Rolls the dice and returns them for the player as a tuple +# Rolls the dice and returns them for the player as a tuple + + def roll(): die1 = random.randint(1, 6) die2 = random.randint(1, 6) - return(die1,die2) -#The function that handles the players -#second and third correspond to if its the players second or third consecutive turn, they are bools + return (die1, die2) +# The function that handles the players +# second and third correspond to if its the players second or third consecutive turn, they are bools + + def player_roll(num_rolls): print_commands() bottom_screen_wipe() - if(players[turn].order != -1): # If player is not bankrupt + if (players[turn].order != -1): # If player is not bankrupt player_color = COLORS.playerColors[turn] update_history(player_color + f"{players[turn].name}'s turn") print_commands()
monopoly.py#L310
update_history(f"Player {turn} rolled {dice[0]} and {dice[1]}") if dice[0] == dice[1]: - if num_rolls == 1: + if num_rolls == 1: update_history(f"{players[turn]} rolled doubles! Roll again.") elif num_rolls == 2: - update_history(f"{players[turn]} rolled doubles!(X2) Roll again.") + 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} rolled doubles three times\n in a row!") update_history(f"Player {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 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"Player {players[turn].order} 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}") + update_history( + f"{players[turn].name} landed on {board.locations[players[turn].location].name}") refresh_board() done_moving_around = False card = ""
monopoly.py#L335
done_moving_around = True if board.locations[players[turn].location].owner < 0: match board.locations[players[turn].location].owner: - case -1: #unowned + case - 1: # unowned buy_logic() - case -2: #mortgaged + case - 2: # mortgaged pass - case -3: #community chest + case - 3: # community chest old_loc = players[turn].location - card = decks.draw_community_chest(players[turn], board, players) + card = decks.draw_community_chest( + players[turn], board, players) 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") - case -4: #chance + update_history( + f"{players[turn].name} drew a Community Chest card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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].name} drew a Chance card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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 + case - 5: # income tax players[turn].pay(200) - update_history(f"{players[turn].name} paid income tax ($200)") - case -6: # jail + update_history( + f"{players[turn].name} paid income tax ($200)") + case - 6: # jail pass - case -7: # go to jail + case - 7: # go to jail players[turn].jail = True board.update_location(players[turn], -1) - case -8: # free parking + case - 8: # free parking pass - case -9: # luxury tax + case - 9: # luxury tax players[turn].pay(100) - update_history(f"{players[turn].name} paid luxury tax ($100)") - case -10: # go + update_history( + f"{players[turn].name} paid luxury tax ($100)") + case - 10: # go pass elif board.locations[players[turn].location].owner != players[turn].order: # Pay another player rent
monopoly.py#L384
rent = 10 * (dice[0] + dice[1]) players[turn].pay(rent) players[board.locations[cl].owner].receive(rent) - update_history(f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") + update_history( + f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") refresh_board() - #checks if player rolled a double, and has them roll again if they did. + # checks if player rolled a double, and has them roll again if they did. if dice[0] == dice[1] and players[turn].jail == False: - num_rolls +=1 + num_rolls += 1 player_roll(num_rolls) -while(True): + +while (True): # First time the player who's turn it is rolls their dice - #if they roll a double the function calls itself and updates its their number of consecutive rolls + # if they roll a double the function calls itself and updates its their number of consecutive rolls player_roll(num_rolls=1) - if(players[turn].cash > 0): - choice = input("\033[38;0He to end turn, p to manage properties, d to view a deed?") - while(choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen + if (players[turn].cash > 0): + choice = input( + "\033[38;0He to end turn, p to manage properties, d to view a deed?") + while (choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen if choice == "e": pass elif choice == "p":
monopoly.py#L406
update_status(players[turn], "deed") else: print("Invalid option!") - choice = input("\033[38;0H'e' to end turn, p to manage properties, ?") + 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.") - option = input("\033[38;0HResolve debts before ending turn.").lower().strip() - if(option == "b"): # Declare bankruptcy + update_history( + f"Player {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.") players[turn].order = -1 - elif(option == "m"): # Mortgage properties + elif (option == "m"): # Mortgage properties pass - elif(option == "s"): # Sell houses/hotels + elif (option == "s"): # Sell houses/hotels housing_logic() # TODO! For now, just declare bankruptcy. Player should NOT, by default, be able to by pressing "enter"
monopoly.py#L430
# Wipe the bottom of the screen (input area) bottom_screen_wipe() - if(bankrupts == num_players - 1): + if (bankrupts == num_players - 1): break - turn = (turn + 1)%num_players + turn = (turn + 1) % num_players for index, player in enumerate(players): if player.order != -1: color = COLORS.playerColors[index] update_history(color + f"Player {index} wins!") break -print("\033[40;0H", end="") +print("\033[40;0H", end="")
banker.py#L2
import threading import os import style as s -import screenspace as ss +import screenspace as ss import battleship import networking as net import gamemanager as gm
banker.py#L18
global timer timer = 0 + class Client: def __init__(self, socket: socket.socket, name: str, money: int, properties: list):
banker.py#L57
server_socket.listen() s.print_w_dots("Waiting for clients...") - + # TEMP VARIABLE: Players should be hardcoded to 4 for printing/playing purposes # Alternatively, make game work for N players...? num_players = 1
banker.py#L71
if len(clients) != num_players: client_socket, addr = server_socket.accept() print(f"Got a connection from {addr}") - client_handler = threading.Thread(target=handshake, args=(client_socket,handshakes)) + client_handler = threading.Thread( + target=handshake, args=(client_socket, handshakes)) client_handler.start() - else: + else: game_full = True # # Give program a moment to evaluate handshakes # for h in handshakes:
banker.py#L87
s.print_w_dots("") return server_socket + def start_receiver(): """ This function handles all client-to-server requests (not the other way around). Function binds an independent receiving socket at the same IP address, one port above. For example, if the opened port was 3131, the receiver will open on 3132. - + Parameters: None Returns: None """ global player_data, timer, port - s.print_w_dots('[RECEIVER] Receiver started!') - # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. + s.print_w_dots('[RECEIVER] Receiver started!') + # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. with socket.socket() as server: host = socket.gethostname() ip_address = socket.gethostbyname(host) - server.bind((ip_address,int(port+1))) + server.bind((ip_address, int(port+1))) server.listen() - s.print_w_dots('[RECEIVER] Receiver accepting connections at {}'.format(port+1)) + s.print_w_dots( + '[RECEIVER] Receiver accepting connections at {}'.format(port+1)) to_read = [server] # add server to list of readable sockets. connected_clients = {} while True: # check for a connection to the server or data ready from clients. # readers will be empty on timeout. - readers,_,_ = select.select(to_read,[],[],0.1) + readers, _, _ = select.select(to_read, [], [], 0.1) for reader in readers: if reader is server: - player,address = reader.accept() + player, address = reader.accept() # Client(player, 'Player', starting_cash, []) s.print_w_dots('Player connected from: ' + address[0]) - connected_clients[player] = address # store address of client in dict - to_read.append(player) # add client to list of readable sockets + # store address of client in dict + connected_clients[player] = address + # add client to list of readable sockets + to_read.append(player) else: data = reader.recv(1024) handle_data(data, reader) - - if not data: # No data indicates disconnect + + if not data: # No data indicates disconnect s.print_w_dots(f'Player at {address[0]} disconnected.') - to_read.remove(reader) # remove from monitoring - del connected_clients[reader] # remove from dict as well - if(len(connected_clients) == 0): - s.print_w_dots('[RECEIVER] All connections dropped. Receiver stopped.') + to_read.remove(reader) # remove from monitoring + # remove from dict as well + del connected_clients[reader] + if (len(connected_clients) == 0): + s.print_w_dots( + '[RECEIVER] All connections dropped. Receiver stopped.') return - print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ',flush=True,end=f'\r{s.COLORS.RESET}') + print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ', + flush=True, end=f'\r{s.COLORS.RESET}') timer += 1
banker.py#L142
gm.add_game(gm.Game('Battleship', [None] * 2, 'board', 'other_data')) gm.add_game(gm.Game('Battleship', [-1] * 3, 'board', 'other_data')) + def handle_data(data: bytes, client: socket.socket) -> str: """ Handles all data received from player sockets. - + Parameters: data (str) Data received from player sockets. - + Returns: str representing the response to the player's data. """
banker.py#L166
if gm.game_exists('Battleship') == False: s.print_w_dots('No active games to join.') number_of_players = 1 - s.print_w_dots(f'Creating new Battleship with {number_of_players} players.') + s.print_w_dots( + f'Creating new Battleship with {number_of_players} players.') battleship_game = battleship.start_game() - gm.add_game(gm.Game('Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) + gm.add_game(gm.Game( + 'Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) s.print_w_dots('Game created.') gm.get_game_by_id(0).other_data.player_names.append(client_name) s.print_w_dots(f'Player {client_name} joined game.') - + elif gm.player_in_game('Battleship', client_name) == True: with open('errorlog.txt', 'a') as f: f.write(f'Player {client_name} already in game.Line178\n') if len(gm.get_game_by_name('Battleship')) > 1: - print('\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') - net.send_message(client, gm.display_games(name='Battleship', player_name=client_name)) - - else: # should only appear if player is in multiple games + print( + '\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') + net.send_message(client, gm.display_games( + name='Battleship', player_name=client_name)) + + else: # should only appear if player is in multiple games net.send_message(client, gm.display_games()) # battleship_board = + battleship_game.popup("Players: " + str(gm.get_game_by_id(0).other_data.player_names))
banker.py#L189
# net.send_message(client, battleship_board) # s.print_w_dots(f'Gameboard sent to player {client}') + def handshake(client_socket: socket.socket, handshakes: list): """ As players connect, they attempt to handshake the server, this function handles that and only starts the game once 4 handshakes have been successfully resolved. - + Parameters: client_socket (socket.socket) Server sender socket which players connect to at game initialization.
banker.py#L206
if message == "Connected!": handshakes[len(clients)] = True clients.append(Client(client_socket, 'Player 1', 2000, [])) - clients[len(clients)-1].name = input(f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") + clients[len(clients)-1].name = input( + f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") # If the player doesn't enter a name, assign a default name. # Also blacklist other illegal names here that would break the game. if clients[len(clients)-1].name == "" or clients[len(clients)-1].name == "PAD ME PLEASE!": - clients[len(clients)-1].name = f"Player {len(clients)}" - else: + clients[len(clients)-1].name = f"Player {len(clients)}" + else: handshakes[len(clients)] = False + def get_client_by_socket(socket: socket.socket) -> Client: """ Returns the client object associated with the given socket. - + Parameters: socket (socket.socket) The socket of the client. - + Returns: Client object associated with the given socket. """
banker.py#L232
if client.socket.getpeername()[0] == socket.getpeername()[0]: return client + def set_gamerules() -> None: """ Configure all gamerule variables according to Banker user input. Repeats until successful. - + Parameters: None Returns: None """ global bank_cash, starting_cash try: - bank_cash = int(input("Enter the amount of money the bank starts with: ")) - starting_cash = int(input("Enter the amount of money each player starts with: ")) + bank_cash = int( + input("Enter the amount of money the bank starts with: ")) + starting_cash = int( + input("Enter the amount of money each player starts with: ")) except: print("Failed to set gamerules. Try again.") input() set_gamerules() + if __name__ == "__main__": os.system("cls")
banker.py#L257
start_receiver() # print(f"Found {players}, each at: ") # for player in player_data: - # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) + # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) # print(s.Style.RESET_ALL) # set_gamerules()
player.py#L19
calculator_history_queue = [] calculator_history_current_capacity = 15 + def get_graphics(): """Grab text from ascii.txt and split into dictionary""" global text_dict text_dict = s.get_graphics() + def initialize(): """ Initialize client receiver and sender network sockets, attempts to connect to a Banker by looping, then handshakes banker.
battleship.py#L3
import random import os + class Ship(): """ Patrol
battleship.py#L28
║»║¤║«║ ╚═╩═╩═╝ """ + def __init__(self, x: int, y: int, name: str) -> None: self.x = x self.y = y if name == "patrol": self.icon = "╔═╗╚═╝" - self.size = (3,2) + self.size = (3, 2) self.name = "Patrol Boat" self.health = 1 elif name == "submarine": self.icon = "╔══╦╗╚══╩╝" - self.size = (5,2) + self.size = (5, 2) self.name = "Submarine" self.health = 3 elif name == "destroyer": self.icon = "╔═╦╩╗╣ ╠╣╠╚═╩╦╝" - self.size = (5,3) + self.size = (5, 3) self.name = "Destroyer" self.health = 3 elif name == "battleship": self.icon = "╔╩╩╩╩╗╣╬╬╬╬╠╚╦╦╦╦╝" - self.size = (6,3) + self.size = (6, 3) self.name = "Battleship" self.health = 4 elif name == "carrier": self.icon = "╔═╦═╦═╗║»║¤║«║╚═╩═╩═╝" - self.size = (7,3) + self.size = (7, 3) self.name = "Aircraft Carrier" self.health = 5 - else: + else: print("Invalid ship name.") def in_bounds(self, x, y) -> bool: return x + self.size[0] <= ss.cols and y + self.size[1] <= ss.rows and x >= 2 and y >= 1 - + def __str__(self) -> str: return self.name - + + class BattleshipGame(): """ Battleship Game
battleship.py#L72
Version: 1.0.0 https://en.wikipedia.org/wiki/Battleship_(game) """ + def __init__(self) -> None: self.board = self.generate_water_and_coords() self.players = 1 self.player_names = [] self.ships = [[] * self.players] self.changed_coords = [] - self.gamestate = 'placing ships' # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + self.gamestate = 'placing ships' def generate_water_and_coords(self) -> str: texture = "" texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK for x in range(0, ss.cols, 3): - texture += f"{x} " if x < 10 else f"{x} " + texture += f"{x} " if x < 10 else f"{x} " texture += "\n" for y in range(1, ss.rows): texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK - texture += (str(y) + (" " if y < 10 else "") if y % 2 == 0 else " ") + texture += (str(y) + (" " if y < 10 else "") if y % + 2 == 0 else " ") texture += f"{s.COLORS.backLIGHTBLUE}{s.COLORS.BLUE}" for _ in range(ss.cols-2): texture += random.choices( ["░", "▒", "▓"], - weights=[1, 2, 7], # Adjust weights to create larger pools of dark textures + # Adjust weights to create larger pools of dark textures + weights=[1, 2, 7], k=1 )[0] texture += "\n" self.board = texture + s.COLORS.RESET return self.board - def print_ship(self, sh: Ship, playerNum = 0) -> str: + def print_ship(self, sh: Ship, playerNum=0) -> str: text = s.COLORS.playerColors[playerNum] for i in range(sh.size[1]): text += f"{s.set_cursor_str(sh.x+1,sh.y+i+1)}{sh.icon[i*sh.size[0]:(i+1)*sh.size[0]]}\n"
battleship.py#L108
def print_explosion(self, x: int, y: int) -> str: text = "" - text += s.set_cursor_str(x,y) + random.choice([s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice( + [s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) return text def print_miss(self, x: int, y: int) -> str: text = s.COLORS.LIGHTGRAY - text += s.set_cursor_str(x,y) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice(["░", "▒", "▓"]) return text - def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: + def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: """ ...fill in comment x and y params should be top left corner of terminal.
battleship.py#L132
if 0 < i < 4: # Custom text wrapping p += s.set_cursor_str(27, 5+i) + message[(i-1)*26:(i-1)*26+26] - return p + return p def get_valid_int(self, prompt): while True:
battleship.py#L141
value = int(input(prompt)) return value except ValueError: - self.popup("Invalid input. Please enter a valid integer.", s.COLORS.RED) + self.popup( + "Invalid input. Please enter a valid integer.", s.COLORS.RED) s.set_cursor(0, ss.INPUTLINE) def is_overlapping(self, x: int, y: int, size: tuple, player_num: int) -> Ship: for sh in self.ships[player_num]: if (x < sh.x + sh.size[0] and x + size[0] > sh.x and - y < sh.y + sh.size[1] and y + size[1] > sh.y): + y < sh.y + sh.size[1] and y + size[1] > sh.y): return sh return None - def place_ships(self, current_board:str, player_num:int = 0) -> str: + def place_ships(self, current_board: str, player_num: int = 0) -> str: return_board = current_board s.set_cursor(0, ss.INPUTLINE) - ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), - Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] + ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), + Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] self.ships[player_num].clear() return_board = self.get_ship_board(player_num) for ship in ships_to_place: - while ship.x == -1 : + while ship.x == -1: x = self.get_valid_int(f"Enter x-coordinate for your {ship}: ") y = self.get_valid_int(f"Enter y-coordinate for your {ship}: ") - + if ship.in_bounds(x, y): if self.is_overlapping(x, y, ship.size, player_num) == None: ship.x = x
battleship.py#L173
else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-ship.size[0]}. Max y is {ss.rows-ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) + return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - + done = input("Does this look good? n for no, anything else for yes.") if done == 'n': while done != 'y': - move = self.get_valid_int(f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") + move = self.get_valid_int( + f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") if 0 <= move < len(self.ships[player_num]): self.ships[player_num].pop(move) return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - ship_names = ['patrol', 'submarine', 'destroyer', 'battleship', 'carrier'] + ship_names = ['patrol', 'submarine', + 'destroyer', 'battleship', 'carrier'] new_ship = Ship(-1, -1, ship_names[move]) while new_ship.x == -1: - x = self.get_valid_int(f"Enter x-coordinate for your {new_ship}: ") - y = self.get_valid_int(f"Enter y-coordinate for your {new_ship}: ") - + x = self.get_valid_int( + f"Enter x-coordinate for your {new_ship}: ") + y = self.get_valid_int( + f"Enter y-coordinate for your {new_ship}: ") + if new_ship.in_bounds(x, y): if self.is_overlapping(x, y, new_ship.size, player_num) == None: new_ship.x = x
battleship.py#L199
return self.popup(f"Error! This ship is on another ship. Recall this ship size is {new_ship.size}", s.COLORS.RED) else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-new_ship.size[0]}. Max y is {ss.rows-new_ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) - done = input("Does this look good? y for yes, anything else for no.") + return_board = self.get_ship_board(player_num) + done = input( + "Does this look good? y for yes, anything else for no.") return return_board - def get_ship_board(self, player_num:int) -> str: + def get_ship_board(self, player_num: int) -> str: # os.system("cls") current_board = self.board for ship in self.ships[player_num]:
battleship.py#L212
return current_board def attack(self): - while(len(self.ships) > 0): # not correct final logic, temporary + while (len(self.ships) > 0): # not correct final logic, temporary s.set_cursor(0, ss.INPUTLINE) x = self.get_valid_int("Enter x-coordinate for your attack: ") if x < 2 or x > 74: - self.popup("Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) continue y = self.get_valid_int("Enter y-coordinate for your attack: ") if y < 1 or y > 19: - self.popup("Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) continue - if (x,y) in self.changed_coords: - self.popup("Error! This coordinate has already been attacked.", s.COLORS.RED) + if (x, y) in self.changed_coords: + self.popup( + "Error! This coordinate has already been attacked.", s.COLORS.RED) continue - else: - self.changed_coords.append((x,y)) + else: + self.changed_coords.append((x, y)) for player_ship_list in self.ships: for ship in player_ship_list: - if self.is_overlapping(x, y, (1,1)) == ship: - self.popup(f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) + if self.is_overlapping(x, y, (1, 1)) == ship: + self.popup( + f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) self.board += self.print_explosion(x+1, y+1) ship.health -= 1 if ship.health == 0: player_ship_list.remove(ship) for i in range(ship.size[0]): for j in range(ship.size[1]): - self.board += self.print_explosion(ship.x+i+1, ship.y+j+1) - self.popup(f"You sunk the {ship.name}!", s.COLORS.dispBLUE) + self.board += self.print_explosion( + ship.x+i+1, ship.y+j+1) + self.popup( + f"You sunk the {ship.name}!", s.COLORS.dispBLUE) break else: self.popup("Miss!.", s.COLORS.RED)
battleship.py#L246
s.set_cursor(0, ss.INPUTLINE) input("Press enter to continue.") print(self.get_board()) - + + def start_game() -> BattleshipGame: ships = BattleshipGame() return ships + if __name__ == "__main__": os.system("cls")
battleship.py#L263
# def unittest1(): # ships.p1ships = [Ship(3,10,"patrol"), Ship(12,2,"submarine"), Ship(33,5,"destroyer"), Ship(50,7,"battleship"), Ship(15,9,"carrier")] - # unittest1() - - # ships.attack() + # unittest1() + + # ships.attack()
modules.py#L4
from socket import socket as Socket import networking as net + def calculator() -> str: """A simple calculator module that can perform basic arithmetic operations.""" - #Uses recursion to calculate. + # Uses recursion to calculate. def calculate(equation: str) -> float: for i in range(0, len(equation)-1): - if(equation[i] == '+'): + if (equation[i] == '+'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) + calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '-'): - #Checks for unary operator '-' - if(i == 0): + if (equation[i] == '-'): + # Checks for unary operator '-' + if (i == 0): eqLeft = "0" else: eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) - calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '*'): + if (equation[i] == '*'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) * calculate(eqRight) for i in range(0, len(equation)-1): - if(equation[i] == '/'): + if (equation[i] == '/'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft)/calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '%'): + if (equation[i] == '%'): eqLeft = equation[:i] eqRight = equation[(i+1):] - return calculate(eqLeft)%calculate(eqRight) - + return calculate(eqLeft) % calculate(eqRight) + for i in range(0, len(equation)-1): - if(equation[i] == '^'): + if (equation[i] == '^'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) ** calculate(eqRight) - + return float(equation) - response = '\nCALCULATOR TERMINAL\n' + response = '\nCALCULATOR TERMINAL\n' digit_result = 0 print("\r", end='') equation = input(s.COLORS.GREEN) - if(equation == "e"): + if (equation == "e"): return equation - - #Trims unnecessary spaces and pads operators with spaces + + # 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] == '-'): + + # 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. + # 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' + 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 + + wrappedResponse += responseEQ[(75*lineNumber) :(75*(lineNumber + 1)) + numOverflowingChar] + '\n' + # response += wrappedResponse print(s.COLORS.RESET, end='') return wrappedResponse + def list_properties() -> str: """ Temporary function to list all properties on the board by calling the property list stored in ascii.txt. Can be reworked to add color and better formatting. - + Parameters: None Returns: None """ ret_val = "" props = s.get_graphics().get('properties').split('\n') for prop in props: - if prop == '': - ret_val += ' '.center(75) + '\n' + if prop == '': + ret_val += ' '.center(75) + '\n' continue first_word = prop.split()[0] color = getattr(s.COLORS, first_word.upper(), s.COLORS.RESET) centered_prop = prop.center(75) - ret_val +=color+ centered_prop + s.COLORS.RESET + '\n' + ret_val += color + centered_prop + s.COLORS.RESET + '\n' return ret_val + def trade(): pass + def mortgage(): pass + def roll(): pass + def gamble(): pass + def attack(): pass + def stocks(): pass + def battleship(server: Socket, gamestate: str) -> str: net.send_message(server, 'battleship') + fishing_game_obj = fishing_game() + + def fishing(gamestate: str) -> tuple[str, str]: """ Fishing module handler for player.py. Returns tuple of [visual data, gamestate] both as strings.
modules.py#L142
stdIn = fishing_game_obj.get_input() if stdIn == 'e': return '', 'e' - return fishing_game_obj.results(), 'e' + return fishing_game_obj.results(), 'e' case 'e': - return '', 'start' + return '', 'start' + def kill() -> str: return s.get_graphics()['skull'] + def disable() -> str: - result = ('X ' * round(ss.cols/2+0.5) + '\n' + - (' X' * round(ss.cols/2+0.5)) + '\n' - ) * (ss.rows//2) + result = ('X ' * round(ss.cols/2+0.5) + '\n' + + (' X' * round(ss.cols/2+0.5)) + '\n' + ) * (ss.rows//2) return result + def make_board(board_pieces) -> list[str]: board = [''] * 35
modules.py#L163
if board_pieces[i*80+j] != '\n': board[i] += (board_pieces[i*80+j]) return board -
properties.py#L1
import style as s from style import COLORS + class Property: """
properties.py#L24
rentHotel = 0 mortgage = 0 - def __init__(self, num_players:int, name:str, owner:int, position:tuple, color:COLORS, purchasePrice:int, housePrice:int, rent:int, rent1H:int, rent2H:int, rent3H:int, rent4H:int, rentHotel:int,mortgage:int) -> None: + def __init__(self, num_players: int, name: str, owner: int, position: tuple, color: COLORS, purchasePrice: int, housePrice: int, rent: int, rent1H: int, rent2H: int, rent3H: int, rent4H: int, rentHotel: int, mortgage: int) -> None: self.players = list(range(num_players)) self.name = name self.owner = owner
properties.py#L41
self.rent4H = rent4H self.rentHotel = rentHotel self.mortgage = mortgage - + def getPrice(self) -> int: if self.purchasePrice == 0: return -1
properties.py#L172
"Electric Company": (150, 4, 10, -1, -1, 75), "Water Works": (150, 4, 10, -1, -1, 75) } - """ + """
monopoly.py#L1
-# Monopoly game is played on Banker's terminal. +# Monopoly game is played on Banker's terminal. +from datetime import datetime import style as s from style import COLORS import random
monopoly.py#L10
from player_class import Player import screenspace as ss + def refresh_board(): """ Refresh the gameboard\n """ print(COLORS.RESET + "\033[0;0H", end="") print(gameboard) - for i in range(40): + for i in range(40): # This loop paints the properties on the board with respective color schemes color = board.locations[i].color backcolor = board.locations[i].color.replace("38", "48") - print(COLORS.backBLACK + color + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) - - if(board.locations[i].owner != -1): # If owned + print(COLORS.backBLACK + color + + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) + + if (board.locations[i].owner != -1): # If owned print(end=COLORS.RESET) color = f"\033[38;5;{board.locations[i].owner+1}m" - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") - - if(board.locations[i].owner == -3): # If community chest + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") + + if (board.locations[i].owner == -3): # If community chest print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.COMMUNITY + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.COMMUNITY + "▀" * 6) - - if(board.locations[i].owner == -4): # If chance + print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + + COLORS.COMMUNITY + "█" * 6) + print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + + COLORS.COMMUNITY + "▀" * 6) + + if (board.locations[i].owner == -4): # If chance print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) - - if(board.locations[i].houses > 0): # If there are houses + print( + f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) + print( + f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) + + if (board.locations[i].houses > 0): # If there are houses print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + COLORS.GREEN + "▀" * (board.locations[i].houses)) - - if(board.locations[i].houses == 5): # If there is a hotel + print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + + COLORS.GREEN + "▀" * (board.locations[i].houses)) + + if (board.locations[i].houses == 5): # If there is a hotel print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") - - if(board.locations[i].owner == -2): # If mortgaged + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") + + if (board.locations[i].owner == -2): # If mortgaged print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + COLORS.backLIGHTGRAY + "M") + print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + + COLORS.backLIGHTGRAY + "M") print(end=COLORS.RESET) for i in range(num_players): color = COLORS.playerColors[i] token = "◙" - print(color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") - + print( + color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") + print(end=COLORS.RESET) + def print_commands(): """
monopoly.py#L67
for j in range(len(commandsinfo[i])): print(f"\033[{34+i};79H" + commandsinfo[i][:j], end="") + history = [] + + def update_history(message: str): """ Update the history\n
monopoly.py#L75
Split the text into multiple lines (multiple entries to history variable)\n """ if "[38;5" in message: - if(((40 - (len(message) - 9)) * 2) == 0): - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) + if (((40 - (len(message) - 9)) * 2) == 0): + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) else: - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) else: if len(message) > 40: while len(message) > 40:
monopoly.py#L86
message = message[40:] history.append(message + " " * (40 - len(message))) if len(history) > 31: - while(len(history) > 31): + while (len(history) > 31): history.pop(0) refresh_h_and_s() + status = [] + + def update_status(p: Player, update: str, status: list = status): """ Update the status\n """ # Property status update (list all properties of player) status.clear() - if(update == "properties"): + if (update == "properties"): color = COLORS.playerColors[p.order] status.append(color + f"{p.name} has properties: " + COLORS.RESET) for i in range(len(p.properties)): - status.append(f"{p.properties[i]}: {board.locations[p.properties[i]].name}") - if(update == "deed"): + status.append( + f"{p.properties[i]}: {board.locations[p.properties[i]].name}") + if (update == "deed"): propertyid = input("What property to view? Enter property #") try: location = board.locations[int(propertyid)] - if location.owner > -1: # if the location is owned + 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"Player{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 + if (location.rent != 0): # if location could be owned and is not a utility or railroad status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") status.append(f"Price Per House: {location.housePrice}")
monopoly.py#L121
status.append(f"Rent w 4 houses: {location.rent4H}") status.append(f"Rent w hotel: {location.rentHotel}") status.append(f"Mortgage Value: {location.mortgage}") - elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility + elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") - status.append(f"Rent (or mltplr) with 1 owned: {location.rent1H}") - status.append(f"Rent (or mltplr) with 2 owned: {location.rent2H}") - status.append(f"Rent with 3 locations owned: {location.rent3H}") - status.append(f"Rent with 4 locations owned: {location.rent4H}") + status.append( + f"Rent (or mltplr) with 1 owned: {location.rent1H}") + status.append( + f"Rent (or mltplr) with 2 owned: {location.rent2H}") + status.append( + f"Rent with 3 locations owned: {location.rent3H}") + status.append( + f"Rent with 4 locations owned: {location.rent4H}") status.append(f"Mortgage Value: {location.mortgage}") else: raise ValueError
monopoly.py#L135
print(f"Invalid input. Please enter a # for a property.") refresh_h_and_s() + border = s.get_graphics().get('history and status') border = border.split("\n") + + def refresh_h_and_s(): """ Refresh the history, status, and leaderboard\n
monopoly.py#L144
# Refresh history for i in range(len(border)): print(f"\033[{i};79H", end="") - if(len(history) - i<= 0): + if (len(history) - i <= 0): for j in range(len(border[i])): print(border[i][j], end="") for i in range(len(history)): - print(f"\033[{i+4};81H" + history[i] if i < len(history) else "", end=COLORS.RESET) - + print(f"\033[{i+4};81H" + history[i] if i < + len(history) else "", end=COLORS.RESET) + # Refresh status for i in range(len(status)): print(f"\033[{i+4};122H" + status[i] if i < len(status) else "")
monopoly.py#L158
# Refresh leaderboard sorted_players = sorted(players, key=lambda x: x.cash, reverse=True) for i in range(len(sorted_players)): - if(sorted_players[i].order != -1): + if (sorted_players[i].order != -1): color = COLORS.playerColors[sorted_players[i].order] - print(color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + print( + color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + def buy_logic(): CL = players[turn].location choice = input("\033[37;0Hb to buy, enter to continue?") - if(board.locations[CL].purchasePrice != 0): + if (board.locations[CL].purchasePrice != 0): price = board.locations[CL].purchasePrice - if(players[turn].cash > price and choice == 'b'): + if (players[turn].cash > price and choice == 'b'): players[turn].buy(CL, board) board.locations[CL].owner = turn - update_history(f"{players[turn].name} bought {board.locations[CL].name} for ${price}") + update_history( + f"{players[turn].name} bought {board.locations[CL].name} for ${price}") else: - update_history(f"{players[turn].name} did not buy {board.locations[CL].name}") + update_history( + f"{players[turn].name} did not buy {board.locations[CL].name}") + def housing_logic(p: Player): update_status(p, "properties") - propertyid = input("What property do you want to build on? Enter property # or 'e' to exit."+ + propertyid = input("What property do you want to build on? Enter property # or 'e' to exit." + "\033[40;0H" + " " * 78+"\033[41;0H" + " " * 78+"\033[40;0H") flag = True exit = False - try: + try: if propertyid == 'e': exit = True else: - propertyid = int(propertyid) - except ValueError: ###AHHHHHHHH clean me please - print(f"\033[42;0" + COLORS.RED + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) + propertyid = int(propertyid) + except ValueError: # AHHHHHHHH clean me please + print(f"\033[42;0" + COLORS.RED + + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) flag = False if flag and not exit: if not propertyid in p.properties: print("You do not own this property!") - else: + else: family = board.locations[propertyid].color if family == COLORS.CYAN or family == COLORS.LIGHTBLACK or board.locations[propertyid].name.startswith("Electric"): print("This property cannot be improved.") flag = False - if flag: - for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): # check only a few properties around for efficiency + if flag: + # check only a few properties around for efficiency + for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): if board.locations[i].color == family: if not i in p.properties: print("You do not own a monopoly on these properties!")
monopoly.py#L214
elif 30 < propertyid < 40: cost = 200 max = 5 - board.locations[propertyid].houses - houses = input(f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") + houses = input( + f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") try: houses = int(houses) - if(0 <= houses <= max): + if (0 <= houses <= max): p.cash -= cost * houses - update_history(f"{p} bought {houses} houses on {board.locations[propertyid].name}!") + update_history( + f"{p} bought {houses} houses on {board.locations[propertyid].name}!") board.locations[propertyid].houses += houses refresh_board() else:
monopoly.py#L229
if not exit: housing_logic(p) + def mortgage_logic(): - input("\033[37;0HWhat property to mortgage?") - -from datetime import datetime + input("\033[37;0HWhat property to mortgage?") + + def log_error(error_message: str) -> None: """ Log error message to errorlog.txt\n
monopoly.py#L241
current_datetime = datetime.now() formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S') f.write(f"{formatted_datetime}\n{error_message}\n") + ss.make_fullscreen()
monopoly.py#L260
board = Board(num_players) decks = Cards() -import style as s gameboard = s.get_graphics().get('gameboard') os.system('cls' if os.name == 'nt' else 'clear') print(COLORS.WHITE + "\033[0;0H", end="") print(gameboard) + def unittest(): players[1].buy(1, board)
monopoly.py#L277
players[3].buy(12, board) players[3].buy(28, board) + unittest() -#wipes the bottom of the screen where the player does all of their input +# wipes the bottom of the screen where the player does all of their input + + def bottom_screen_wipe(): print("\033[36;0H" + " " * 76) print("\033[37;0H" + " " * 76)
monopoly.py#L290
print("\033[43;0H" + " " * 76) print("\033[44;0H" + " " * 76) -#Rolls the dice and returns them for the player as a tuple +# Rolls the dice and returns them for the player as a tuple + + def roll(): die1 = random.randint(1, 6) die2 = random.randint(1, 6) - return(die1,die2) -#The function that handles the players -#second and third correspond to if its the players second or third consecutive turn, they are bools + return (die1, die2) +# The function that handles the players +# second and third correspond to if its the players second or third consecutive turn, they are bools + + def player_roll(num_rolls): print_commands() bottom_screen_wipe() - if(players[turn].order != -1): # If player is not bankrupt + if (players[turn].order != -1): # If player is not bankrupt player_color = COLORS.playerColors[turn] update_history(player_color + f"{players[turn].name}'s turn") print_commands()
monopoly.py#L310
update_history(f"Player {turn} rolled {dice[0]} and {dice[1]}") if dice[0] == dice[1]: - if num_rolls == 1: + if num_rolls == 1: update_history(f"{players[turn]} rolled doubles! Roll again.") elif num_rolls == 2: - update_history(f"{players[turn]} rolled doubles!(X2) Roll again.") + 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} rolled doubles three times\n in a row!") update_history(f"Player {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 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"Player {players[turn].order} 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}") + update_history( + f"{players[turn].name} landed on {board.locations[players[turn].location].name}") refresh_board() done_moving_around = False card = ""
monopoly.py#L335
done_moving_around = True if board.locations[players[turn].location].owner < 0: match board.locations[players[turn].location].owner: - case -1: #unowned + case - 1: # unowned buy_logic() - case -2: #mortgaged + case - 2: # mortgaged pass - case -3: #community chest + case - 3: # community chest old_loc = players[turn].location - card = decks.draw_community_chest(players[turn], board, players) + card = decks.draw_community_chest( + players[turn], board, players) 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") - case -4: #chance + update_history( + f"{players[turn].name} drew a Community Chest card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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].name} drew a Chance card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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 + case - 5: # income tax players[turn].pay(200) - update_history(f"{players[turn].name} paid income tax ($200)") - case -6: # jail + update_history( + f"{players[turn].name} paid income tax ($200)") + case - 6: # jail pass - case -7: # go to jail + case - 7: # go to jail players[turn].jail = True board.update_location(players[turn], -1) - case -8: # free parking + case - 8: # free parking pass - case -9: # luxury tax + case - 9: # luxury tax players[turn].pay(100) - update_history(f"{players[turn].name} paid luxury tax ($100)") - case -10: # go + update_history( + f"{players[turn].name} paid luxury tax ($100)") + case - 10: # go pass elif board.locations[players[turn].location].owner != players[turn].order: # Pay another player rent
monopoly.py#L384
rent = 10 * (dice[0] + dice[1]) players[turn].pay(rent) players[board.locations[cl].owner].receive(rent) - update_history(f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") + update_history( + f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") refresh_board() - #checks if player rolled a double, and has them roll again if they did. + # checks if player rolled a double, and has them roll again if they did. if dice[0] == dice[1] and players[turn].jail == False: - num_rolls +=1 + num_rolls += 1 player_roll(num_rolls) -while(True): + +while (True): # First time the player who's turn it is rolls their dice - #if they roll a double the function calls itself and updates its their number of consecutive rolls + # if they roll a double the function calls itself and updates its their number of consecutive rolls player_roll(num_rolls=1) - if(players[turn].cash > 0): - choice = input("\033[38;0He to end turn, p to manage properties, d to view a deed?") - while(choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen + if (players[turn].cash > 0): + choice = input( + "\033[38;0He to end turn, p to manage properties, d to view a deed?") + while (choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen if choice == "e": pass elif choice == "p":
monopoly.py#L406
update_status(players[turn], "deed") else: print("Invalid option!") - choice = input("\033[38;0H'e' to end turn, p to manage properties, ?") + 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.") - option = input("\033[38;0HResolve debts before ending turn.").lower().strip() - if(option == "b"): # Declare bankruptcy + update_history( + f"Player {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.") players[turn].order = -1 - elif(option == "m"): # Mortgage properties + elif (option == "m"): # Mortgage properties pass - elif(option == "s"): # Sell houses/hotels + elif (option == "s"): # Sell houses/hotels housing_logic() # TODO! For now, just declare bankruptcy. Player should NOT, by default, be able to by pressing "enter"
monopoly.py#L430
# Wipe the bottom of the screen (input area) bottom_screen_wipe() - if(bankrupts == num_players - 1): + if (bankrupts == num_players - 1): break - turn = (turn + 1)%num_players + turn = (turn + 1) % num_players for index, player in enumerate(players): if player.order != -1: color = COLORS.playerColors[index] update_history(color + f"Player {index} wins!") break -print("\033[40;0H", end="") +print("\033[40;0H", end="")
banker.py#L2
import threading import os import style as s -import screenspace as ss +import screenspace as ss import battleship import networking as net import gamemanager as gm
banker.py#L18
global timer timer = 0 + class Client: def __init__(self, socket: socket.socket, name: str, money: int, properties: list):
banker.py#L57
server_socket.listen() s.print_w_dots("Waiting for clients...") - + # TEMP VARIABLE: Players should be hardcoded to 4 for printing/playing purposes # Alternatively, make game work for N players...? num_players = 1
banker.py#L71
if len(clients) != num_players: client_socket, addr = server_socket.accept() print(f"Got a connection from {addr}") - client_handler = threading.Thread(target=handshake, args=(client_socket,handshakes)) + client_handler = threading.Thread( + target=handshake, args=(client_socket, handshakes)) client_handler.start() - else: + else: game_full = True # # Give program a moment to evaluate handshakes # for h in handshakes:
banker.py#L87
s.print_w_dots("") return server_socket + def start_receiver(): """ This function handles all client-to-server requests (not the other way around). Function binds an independent receiving socket at the same IP address, one port above. For example, if the opened port was 3131, the receiver will open on 3132. - + Parameters: None Returns: None """ global player_data, timer, port - s.print_w_dots('[RECEIVER] Receiver started!') - # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. + s.print_w_dots('[RECEIVER] Receiver started!') + # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. with socket.socket() as server: host = socket.gethostname() ip_address = socket.gethostbyname(host) - server.bind((ip_address,int(port+1))) + server.bind((ip_address, int(port+1))) server.listen() - s.print_w_dots('[RECEIVER] Receiver accepting connections at {}'.format(port+1)) + s.print_w_dots( + '[RECEIVER] Receiver accepting connections at {}'.format(port+1)) to_read = [server] # add server to list of readable sockets. connected_clients = {} while True: # check for a connection to the server or data ready from clients. # readers will be empty on timeout. - readers,_,_ = select.select(to_read,[],[],0.1) + readers, _, _ = select.select(to_read, [], [], 0.1) for reader in readers: if reader is server: - player,address = reader.accept() + player, address = reader.accept() # Client(player, 'Player', starting_cash, []) s.print_w_dots('Player connected from: ' + address[0]) - connected_clients[player] = address # store address of client in dict - to_read.append(player) # add client to list of readable sockets + # store address of client in dict + connected_clients[player] = address + # add client to list of readable sockets + to_read.append(player) else: data = reader.recv(1024) handle_data(data, reader) - - if not data: # No data indicates disconnect + + if not data: # No data indicates disconnect s.print_w_dots(f'Player at {address[0]} disconnected.') - to_read.remove(reader) # remove from monitoring - del connected_clients[reader] # remove from dict as well - if(len(connected_clients) == 0): - s.print_w_dots('[RECEIVER] All connections dropped. Receiver stopped.') + to_read.remove(reader) # remove from monitoring + # remove from dict as well + del connected_clients[reader] + if (len(connected_clients) == 0): + s.print_w_dots( + '[RECEIVER] All connections dropped. Receiver stopped.') return - print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ',flush=True,end=f'\r{s.COLORS.RESET}') + print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ', + flush=True, end=f'\r{s.COLORS.RESET}') timer += 1
banker.py#L142
gm.add_game(gm.Game('Battleship', [None] * 2, 'board', 'other_data')) gm.add_game(gm.Game('Battleship', [-1] * 3, 'board', 'other_data')) + def handle_data(data: bytes, client: socket.socket) -> str: """ Handles all data received from player sockets. - + Parameters: data (str) Data received from player sockets. - + Returns: str representing the response to the player's data. """
banker.py#L166
if gm.game_exists('Battleship') == False: s.print_w_dots('No active games to join.') number_of_players = 1 - s.print_w_dots(f'Creating new Battleship with {number_of_players} players.') + s.print_w_dots( + f'Creating new Battleship with {number_of_players} players.') battleship_game = battleship.start_game() - gm.add_game(gm.Game('Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) + gm.add_game(gm.Game( + 'Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) s.print_w_dots('Game created.') gm.get_game_by_id(0).other_data.player_names.append(client_name) s.print_w_dots(f'Player {client_name} joined game.') - + elif gm.player_in_game('Battleship', client_name) == True: with open('errorlog.txt', 'a') as f: f.write(f'Player {client_name} already in game.Line178\n') if len(gm.get_game_by_name('Battleship')) > 1: - print('\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') - net.send_message(client, gm.display_games(name='Battleship', player_name=client_name)) - - else: # should only appear if player is in multiple games + print( + '\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') + net.send_message(client, gm.display_games( + name='Battleship', player_name=client_name)) + + else: # should only appear if player is in multiple games net.send_message(client, gm.display_games()) # battleship_board = + battleship_game.popup("Players: " + str(gm.get_game_by_id(0).other_data.player_names))
banker.py#L189
# net.send_message(client, battleship_board) # s.print_w_dots(f'Gameboard sent to player {client}') + def handshake(client_socket: socket.socket, handshakes: list): """ As players connect, they attempt to handshake the server, this function handles that and only starts the game once 4 handshakes have been successfully resolved. - + Parameters: client_socket (socket.socket) Server sender socket which players connect to at game initialization.
banker.py#L206
if message == "Connected!": handshakes[len(clients)] = True clients.append(Client(client_socket, 'Player 1', 2000, [])) - clients[len(clients)-1].name = input(f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") + clients[len(clients)-1].name = input( + f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") # If the player doesn't enter a name, assign a default name. # Also blacklist other illegal names here that would break the game. if clients[len(clients)-1].name == "" or clients[len(clients)-1].name == "PAD ME PLEASE!": - clients[len(clients)-1].name = f"Player {len(clients)}" - else: + clients[len(clients)-1].name = f"Player {len(clients)}" + else: handshakes[len(clients)] = False + def get_client_by_socket(socket: socket.socket) -> Client: """ Returns the client object associated with the given socket. - + Parameters: socket (socket.socket) The socket of the client. - + Returns: Client object associated with the given socket. """
banker.py#L232
if client.socket.getpeername()[0] == socket.getpeername()[0]: return client + def set_gamerules() -> None: """ Configure all gamerule variables according to Banker user input. Repeats until successful. - + Parameters: None Returns: None """ global bank_cash, starting_cash try: - bank_cash = int(input("Enter the amount of money the bank starts with: ")) - starting_cash = int(input("Enter the amount of money each player starts with: ")) + bank_cash = int( + input("Enter the amount of money the bank starts with: ")) + starting_cash = int( + input("Enter the amount of money each player starts with: ")) except: print("Failed to set gamerules. Try again.") input() set_gamerules() + if __name__ == "__main__": os.system("cls")
banker.py#L257
start_receiver() # print(f"Found {players}, each at: ") # for player in player_data: - # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) + # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) # print(s.Style.RESET_ALL) # set_gamerules()
player.py#L19
calculator_history_queue = [] calculator_history_current_capacity = 15 + def get_graphics(): """Grab text from ascii.txt and split into dictionary""" global text_dict text_dict = s.get_graphics() + def initialize(): """ Initialize client receiver and sender network sockets, attempts to connect to a Banker by looping, then handshakes banker.
battleship.py#L3
import random import os + class Ship(): """ Patrol
battleship.py#L28
║»║¤║«║ ╚═╩═╩═╝ """ + def __init__(self, x: int, y: int, name: str) -> None: self.x = x self.y = y if name == "patrol": self.icon = "╔═╗╚═╝" - self.size = (3,2) + self.size = (3, 2) self.name = "Patrol Boat" self.health = 1 elif name == "submarine": self.icon = "╔══╦╗╚══╩╝" - self.size = (5,2) + self.size = (5, 2) self.name = "Submarine" self.health = 3 elif name == "destroyer": self.icon = "╔═╦╩╗╣ ╠╣╠╚═╩╦╝" - self.size = (5,3) + self.size = (5, 3) self.name = "Destroyer" self.health = 3 elif name == "battleship": self.icon = "╔╩╩╩╩╗╣╬╬╬╬╠╚╦╦╦╦╝" - self.size = (6,3) + self.size = (6, 3) self.name = "Battleship" self.health = 4 elif name == "carrier": self.icon = "╔═╦═╦═╗║»║¤║«║╚═╩═╩═╝" - self.size = (7,3) + self.size = (7, 3) self.name = "Aircraft Carrier" self.health = 5 - else: + else: print("Invalid ship name.") def in_bounds(self, x, y) -> bool: return x + self.size[0] <= ss.cols and y + self.size[1] <= ss.rows and x >= 2 and y >= 1 - + def __str__(self) -> str: return self.name - + + class BattleshipGame(): """ Battleship Game
battleship.py#L72
Version: 1.0.0 https://en.wikipedia.org/wiki/Battleship_(game) """ + def __init__(self) -> None: self.board = self.generate_water_and_coords() self.players = 1 self.player_names = [] self.ships = [[] * self.players] self.changed_coords = [] - self.gamestate = 'placing ships' # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + # other gamestates are 'p1 turn', 'p2 turn', 'p3 turn', 'p4 turn' + self.gamestate = 'placing ships' def generate_water_and_coords(self) -> str: texture = "" texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK for x in range(0, ss.cols, 3): - texture += f"{x} " if x < 10 else f"{x} " + texture += f"{x} " if x < 10 else f"{x} " texture += "\n" for y in range(1, ss.rows): texture += s.COLORS.backCOMMUNITY + s.COLORS.BLACK - texture += (str(y) + (" " if y < 10 else "") if y % 2 == 0 else " ") + texture += (str(y) + (" " if y < 10 else "") if y % + 2 == 0 else " ") texture += f"{s.COLORS.backLIGHTBLUE}{s.COLORS.BLUE}" for _ in range(ss.cols-2): texture += random.choices( ["░", "▒", "▓"], - weights=[1, 2, 7], # Adjust weights to create larger pools of dark textures + # Adjust weights to create larger pools of dark textures + weights=[1, 2, 7], k=1 )[0] texture += "\n" self.board = texture + s.COLORS.RESET return self.board - def print_ship(self, sh: Ship, playerNum = 0) -> str: + def print_ship(self, sh: Ship, playerNum=0) -> str: text = s.COLORS.playerColors[playerNum] for i in range(sh.size[1]): text += f"{s.set_cursor_str(sh.x+1,sh.y+i+1)}{sh.icon[i*sh.size[0]:(i+1)*sh.size[0]]}\n"
battleship.py#L108
def print_explosion(self, x: int, y: int) -> str: text = "" - text += s.set_cursor_str(x,y) + random.choice([s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice( + [s.COLORS.ORANGE, s.COLORS.RED]) + random.choice(["░", "▒", "▓"]) return text def print_miss(self, x: int, y: int) -> str: text = s.COLORS.LIGHTGRAY - text += s.set_cursor_str(x,y) + random.choice(["░", "▒", "▓"]) + text += s.set_cursor_str(x, y) + random.choice(["░", "▒", "▓"]) return text - def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: + def popup(self, message: str, color: str = s.COLORS.WHITE) -> str: """ ...fill in comment x and y params should be top left corner of terminal.
battleship.py#L132
if 0 < i < 4: # Custom text wrapping p += s.set_cursor_str(27, 5+i) + message[(i-1)*26:(i-1)*26+26] - return p + return p def get_valid_int(self, prompt): while True:
battleship.py#L141
value = int(input(prompt)) return value except ValueError: - self.popup("Invalid input. Please enter a valid integer.", s.COLORS.RED) + self.popup( + "Invalid input. Please enter a valid integer.", s.COLORS.RED) s.set_cursor(0, ss.INPUTLINE) def is_overlapping(self, x: int, y: int, size: tuple, player_num: int) -> Ship: for sh in self.ships[player_num]: if (x < sh.x + sh.size[0] and x + size[0] > sh.x and - y < sh.y + sh.size[1] and y + size[1] > sh.y): + y < sh.y + sh.size[1] and y + size[1] > sh.y): return sh return None - def place_ships(self, current_board:str, player_num:int = 0) -> str: + def place_ships(self, current_board: str, player_num: int = 0) -> str: return_board = current_board s.set_cursor(0, ss.INPUTLINE) - ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), - Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] + ships_to_place = [Ship(-1, -1, "patrol"), Ship(-1, -1, "submarine"), Ship(-1, -1, "destroyer"), + Ship(-1, -1, "battleship"), Ship(-1, -1, "carrier")] self.ships[player_num].clear() return_board = self.get_ship_board(player_num) for ship in ships_to_place: - while ship.x == -1 : + while ship.x == -1: x = self.get_valid_int(f"Enter x-coordinate for your {ship}: ") y = self.get_valid_int(f"Enter y-coordinate for your {ship}: ") - + if ship.in_bounds(x, y): if self.is_overlapping(x, y, ship.size, player_num) == None: ship.x = x
battleship.py#L173
else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-ship.size[0]}. Max y is {ss.rows-ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) + return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - + done = input("Does this look good? n for no, anything else for yes.") if done == 'n': while done != 'y': - move = self.get_valid_int(f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") + move = self.get_valid_int( + f"Enter a number (0-4) of a ship to remove from the list {[ship.name for ship in self.ships[player_num]]}: ") if 0 <= move < len(self.ships[player_num]): self.ships[player_num].pop(move) return_board = self.get_ship_board(player_num) s.set_cursor(0, ss.INPUTLINE) - ship_names = ['patrol', 'submarine', 'destroyer', 'battleship', 'carrier'] + ship_names = ['patrol', 'submarine', + 'destroyer', 'battleship', 'carrier'] new_ship = Ship(-1, -1, ship_names[move]) while new_ship.x == -1: - x = self.get_valid_int(f"Enter x-coordinate for your {new_ship}: ") - y = self.get_valid_int(f"Enter y-coordinate for your {new_ship}: ") - + x = self.get_valid_int( + f"Enter x-coordinate for your {new_ship}: ") + y = self.get_valid_int( + f"Enter y-coordinate for your {new_ship}: ") + if new_ship.in_bounds(x, y): if self.is_overlapping(x, y, new_ship.size, player_num) == None: new_ship.x = x
battleship.py#L199
return self.popup(f"Error! This ship is on another ship. Recall this ship size is {new_ship.size}", s.COLORS.RED) else: return self.popup(f"Error! Out of bounds. Max x is {ss.cols-new_ship.size[0]}. Max y is {ss.rows-new_ship.size[1]}", s.COLORS.RED) - return_board = self.get_ship_board(player_num) - done = input("Does this look good? y for yes, anything else for no.") + return_board = self.get_ship_board(player_num) + done = input( + "Does this look good? y for yes, anything else for no.") return return_board - def get_ship_board(self, player_num:int) -> str: + def get_ship_board(self, player_num: int) -> str: # os.system("cls") current_board = self.board for ship in self.ships[player_num]:
battleship.py#L212
return current_board def attack(self): - while(len(self.ships) > 0): # not correct final logic, temporary + while (len(self.ships) > 0): # not correct final logic, temporary s.set_cursor(0, ss.INPUTLINE) x = self.get_valid_int("Enter x-coordinate for your attack: ") if x < 2 or x > 74: - self.popup("Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (2-74) inclusive.", s.COLORS.RED) continue y = self.get_valid_int("Enter y-coordinate for your attack: ") if y < 1 or y > 19: - self.popup("Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) + self.popup( + "Error! Out of bounds. Please enter a valid coordinate (1-19) inclusive.", s.COLORS.RED) continue - if (x,y) in self.changed_coords: - self.popup("Error! This coordinate has already been attacked.", s.COLORS.RED) + if (x, y) in self.changed_coords: + self.popup( + "Error! This coordinate has already been attacked.", s.COLORS.RED) continue - else: - self.changed_coords.append((x,y)) + else: + self.changed_coords.append((x, y)) for player_ship_list in self.ships: for ship in player_ship_list: - if self.is_overlapping(x, y, (1,1)) == ship: - self.popup(f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) + if self.is_overlapping(x, y, (1, 1)) == ship: + self.popup( + f"Hit! You hit the {ship.name}!", s.COLORS.dispBLUE) self.board += self.print_explosion(x+1, y+1) ship.health -= 1 if ship.health == 0: player_ship_list.remove(ship) for i in range(ship.size[0]): for j in range(ship.size[1]): - self.board += self.print_explosion(ship.x+i+1, ship.y+j+1) - self.popup(f"You sunk the {ship.name}!", s.COLORS.dispBLUE) + self.board += self.print_explosion( + ship.x+i+1, ship.y+j+1) + self.popup( + f"You sunk the {ship.name}!", s.COLORS.dispBLUE) break else: self.popup("Miss!.", s.COLORS.RED)
battleship.py#L246
s.set_cursor(0, ss.INPUTLINE) input("Press enter to continue.") print(self.get_board()) - + + def start_game() -> BattleshipGame: ships = BattleshipGame() return ships + if __name__ == "__main__": os.system("cls")
battleship.py#L263
# def unittest1(): # ships.p1ships = [Ship(3,10,"patrol"), Ship(12,2,"submarine"), Ship(33,5,"destroyer"), Ship(50,7,"battleship"), Ship(15,9,"carrier")] - # unittest1() - - # ships.attack() + # unittest1() + + # ships.attack()
modules.py#L4
from socket import socket as Socket import networking as net + def calculator() -> str: """A simple calculator module that can perform basic arithmetic operations.""" - #Uses recursion to calculate. + # Uses recursion to calculate. def calculate(equation: str) -> float: for i in range(0, len(equation)-1): - if(equation[i] == '+'): + if (equation[i] == '+'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) + calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '-'): - #Checks for unary operator '-' - if(i == 0): + if (equation[i] == '-'): + # Checks for unary operator '-' + if (i == 0): eqLeft = "0" else: eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) - calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '*'): + if (equation[i] == '*'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) * calculate(eqRight) for i in range(0, len(equation)-1): - if(equation[i] == '/'): + if (equation[i] == '/'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft)/calculate(eqRight) - + for i in range(0, len(equation)-1): - if(equation[i] == '%'): + if (equation[i] == '%'): eqLeft = equation[:i] eqRight = equation[(i+1):] - return calculate(eqLeft)%calculate(eqRight) - + return calculate(eqLeft) % calculate(eqRight) + for i in range(0, len(equation)-1): - if(equation[i] == '^'): + if (equation[i] == '^'): eqLeft = equation[:i] eqRight = equation[(i+1):] return calculate(eqLeft) ** calculate(eqRight) - + return float(equation) - response = '\nCALCULATOR TERMINAL\n' + response = '\nCALCULATOR TERMINAL\n' digit_result = 0 print("\r", end='') equation = input(s.COLORS.GREEN) - if(equation == "e"): + if (equation == "e"): return equation - - #Trims unnecessary spaces and pads operators with spaces + + # 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] == '-'): + + # 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. + # 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' + 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 + + wrappedResponse += responseEQ[(75*lineNumber) :(75*(lineNumber + 1)) + numOverflowingChar] + '\n' + # response += wrappedResponse print(s.COLORS.RESET, end='') return wrappedResponse + def list_properties() -> str: """ Temporary function to list all properties on the board by calling the property list stored in ascii.txt. Can be reworked to add color and better formatting. - + Parameters: None Returns: None """ ret_val = "" props = s.get_graphics().get('properties').split('\n') for prop in props: - if prop == '': - ret_val += ' '.center(75) + '\n' + if prop == '': + ret_val += ' '.center(75) + '\n' continue first_word = prop.split()[0] color = getattr(s.COLORS, first_word.upper(), s.COLORS.RESET) centered_prop = prop.center(75) - ret_val +=color+ centered_prop + s.COLORS.RESET + '\n' + ret_val += color + centered_prop + s.COLORS.RESET + '\n' return ret_val + def trade(): pass + def mortgage(): pass + def roll(): pass + def gamble(): pass + def attack(): pass + def stocks(): pass + def battleship(server: Socket, gamestate: str) -> str: net.send_message(server, 'battleship') + fishing_game_obj = fishing_game() + + def fishing(gamestate: str) -> tuple[str, str]: """ Fishing module handler for player.py. Returns tuple of [visual data, gamestate] both as strings.
modules.py#L142
stdIn = fishing_game_obj.get_input() if stdIn == 'e': return '', 'e' - return fishing_game_obj.results(), 'e' + return fishing_game_obj.results(), 'e' case 'e': - return '', 'start' + return '', 'start' + def kill() -> str: return s.get_graphics()['skull'] + def disable() -> str: - result = ('X ' * round(ss.cols/2+0.5) + '\n' + - (' X' * round(ss.cols/2+0.5)) + '\n' - ) * (ss.rows//2) + result = ('X ' * round(ss.cols/2+0.5) + '\n' + + (' X' * round(ss.cols/2+0.5)) + '\n' + ) * (ss.rows//2) return result + def make_board(board_pieces) -> list[str]: board = [''] * 35
modules.py#L163
if board_pieces[i*80+j] != '\n': board[i] += (board_pieces[i*80+j]) return board -
properties.py#L1
import style as s from style import COLORS + class Property: """
properties.py#L24
rentHotel = 0 mortgage = 0 - def __init__(self, num_players:int, name:str, owner:int, position:tuple, color:COLORS, purchasePrice:int, housePrice:int, rent:int, rent1H:int, rent2H:int, rent3H:int, rent4H:int, rentHotel:int,mortgage:int) -> None: + def __init__(self, num_players: int, name: str, owner: int, position: tuple, color: COLORS, purchasePrice: int, housePrice: int, rent: int, rent1H: int, rent2H: int, rent3H: int, rent4H: int, rentHotel: int, mortgage: int) -> None: self.players = list(range(num_players)) self.name = name self.owner = owner
properties.py#L41
self.rent4H = rent4H self.rentHotel = rentHotel self.mortgage = mortgage - + def getPrice(self) -> int: if self.purchasePrice == 0: return -1
properties.py#L172
"Electric Company": (150, 4, 10, -1, -1, 75), "Water Works": (150, 4, 10, -1, -1, 75) } - """ + """
monopoly.py#L1
-# Monopoly game is played on Banker's terminal. +# Monopoly game is played on Banker's terminal. +from datetime import datetime import style as s from style import COLORS import random
monopoly.py#L10
from player_class import Player import screenspace as ss + def refresh_board(): """ Refresh the gameboard\n """ print(COLORS.RESET + "\033[0;0H", end="") print(gameboard) - for i in range(40): + for i in range(40): # This loop paints the properties on the board with respective color schemes color = board.locations[i].color backcolor = board.locations[i].color.replace("38", "48") - print(COLORS.backBLACK + color + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) - - if(board.locations[i].owner != -1): # If owned + print(COLORS.backBLACK + color + + f"\033[{board.locations[i].x};{board.locations[i].y}H{i}" + backcolor + " " * (4 + (1 if i < 10 else 0))) + + if (board.locations[i].owner != -1): # If owned print(end=COLORS.RESET) color = f"\033[38;5;{board.locations[i].owner+1}m" - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") - - if(board.locations[i].owner == -3): # If community chest + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + color + "▀") + + if (board.locations[i].owner == -3): # If community chest print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.COMMUNITY + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.COMMUNITY + "▀" * 6) - - if(board.locations[i].owner == -4): # If chance + print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + + COLORS.COMMUNITY + "█" * 6) + print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + + COLORS.COMMUNITY + "▀" * 6) + + if (board.locations[i].owner == -4): # If chance print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) - print(f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) - - if(board.locations[i].houses > 0): # If there are houses + print( + f"\033[{board.locations[i].x + 1};{board.locations[i].y}H" + COLORS.CHANCE + "█" * 6) + print( + f"\033[{board.locations[i].x + 2};{board.locations[i].y}H" + COLORS.CHANCE + "▀" * 6) + + if (board.locations[i].houses > 0): # If there are houses print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + COLORS.GREEN + "▀" * (board.locations[i].houses)) - - if(board.locations[i].houses == 5): # If there is a hotel + print(f"\033[{board.locations[i].x+2};{board.locations[i].y+1}H" + + COLORS.GREEN + "▀" * (board.locations[i].houses)) + + if (board.locations[i].houses == 5): # If there is a hotel print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") - - if(board.locations[i].owner == -2): # If mortgaged + print( + f"\033[{board.locations[i].x+2};{board.locations[i].y+5}H" + COLORS.RED + "▀") + + if (board.locations[i].owner == -2): # If mortgaged print(end=COLORS.RESET) - print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + COLORS.backLIGHTGRAY + "M") + print(f"\033[{board.locations[i].x+2};{board.locations[i].y}H" + + COLORS.backLIGHTGRAY + "M") print(end=COLORS.RESET) for i in range(num_players): color = COLORS.playerColors[i] token = "◙" - print(color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") - + print( + color + f"\033[{board.locations[players[i].location].x+1};{board.locations[players[i].location].y+1+i}H{token}") + print(end=COLORS.RESET) + def print_commands(): """
monopoly.py#L67
for j in range(len(commandsinfo[i])): print(f"\033[{34+i};79H" + commandsinfo[i][:j], end="") + history = [] + + def update_history(message: str): """ Update the history\n
monopoly.py#L75
Split the text into multiple lines (multiple entries to history variable)\n """ if "[38;5" in message: - if(((40 - (len(message) - 9)) * 2) == 0): - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) + if (((40 - (len(message) - 9)) * 2) == 0): + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((40 - (len(message) - 9)) // 2)) else: - history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) + history.append(message[:9] + "─" * ((40 - (len(message) - 9)) // + 2) + message[9:] + "─" * ((39 - (len(message) - 9)) // 2)) else: if len(message) > 40: while len(message) > 40:
monopoly.py#L86
message = message[40:] history.append(message + " " * (40 - len(message))) if len(history) > 31: - while(len(history) > 31): + while (len(history) > 31): history.pop(0) refresh_h_and_s() + status = [] + + def update_status(p: Player, update: str, status: list = status): """ Update the status\n """ # Property status update (list all properties of player) status.clear() - if(update == "properties"): + if (update == "properties"): color = COLORS.playerColors[p.order] status.append(color + f"{p.name} has properties: " + COLORS.RESET) for i in range(len(p.properties)): - status.append(f"{p.properties[i]}: {board.locations[p.properties[i]].name}") - if(update == "deed"): + status.append( + f"{p.properties[i]}: {board.locations[p.properties[i]].name}") + if (update == "deed"): propertyid = input("What property to view? Enter property #") try: location = board.locations[int(propertyid)] - if location.owner > -1: # if the location is owned + 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"Player{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 + if (location.rent != 0): # if location could be owned and is not a utility or railroad status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") status.append(f"Price Per House: {location.housePrice}")
monopoly.py#L121
status.append(f"Rent w 4 houses: {location.rent4H}") status.append(f"Rent w hotel: {location.rentHotel}") status.append(f"Mortgage Value: {location.mortgage}") - elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility + elif (location.owner >= -2 and location.rent == 0): # if is a railroad or utility status.append(f"{location.color}=== {location.name} ===") status.append(f"Purchase Price: {location.purchasePrice}") - status.append(f"Rent (or mltplr) with 1 owned: {location.rent1H}") - status.append(f"Rent (or mltplr) with 2 owned: {location.rent2H}") - status.append(f"Rent with 3 locations owned: {location.rent3H}") - status.append(f"Rent with 4 locations owned: {location.rent4H}") + status.append( + f"Rent (or mltplr) with 1 owned: {location.rent1H}") + status.append( + f"Rent (or mltplr) with 2 owned: {location.rent2H}") + status.append( + f"Rent with 3 locations owned: {location.rent3H}") + status.append( + f"Rent with 4 locations owned: {location.rent4H}") status.append(f"Mortgage Value: {location.mortgage}") else: raise ValueError
monopoly.py#L135
print(f"Invalid input. Please enter a # for a property.") refresh_h_and_s() + border = s.get_graphics().get('history and status') border = border.split("\n") + + def refresh_h_and_s(): """ Refresh the history, status, and leaderboard\n
monopoly.py#L144
# Refresh history for i in range(len(border)): print(f"\033[{i};79H", end="") - if(len(history) - i<= 0): + if (len(history) - i <= 0): for j in range(len(border[i])): print(border[i][j], end="") for i in range(len(history)): - print(f"\033[{i+4};81H" + history[i] if i < len(history) else "", end=COLORS.RESET) - + print(f"\033[{i+4};81H" + history[i] if i < + len(history) else "", end=COLORS.RESET) + # Refresh status for i in range(len(status)): print(f"\033[{i+4};122H" + status[i] if i < len(status) else "")
monopoly.py#L158
# Refresh leaderboard sorted_players = sorted(players, key=lambda x: x.cash, reverse=True) for i in range(len(sorted_players)): - if(sorted_players[i].order != -1): + if (sorted_players[i].order != -1): color = COLORS.playerColors[sorted_players[i].order] - print(color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + print( + color + f"\033[{31+i};122H{sorted_players[i].order} - ${sorted_players[i].cash}", end=COLORS.RESET) + def buy_logic(): CL = players[turn].location choice = input("\033[37;0Hb to buy, enter to continue?") - if(board.locations[CL].purchasePrice != 0): + if (board.locations[CL].purchasePrice != 0): price = board.locations[CL].purchasePrice - if(players[turn].cash > price and choice == 'b'): + if (players[turn].cash > price and choice == 'b'): players[turn].buy(CL, board) board.locations[CL].owner = turn - update_history(f"{players[turn].name} bought {board.locations[CL].name} for ${price}") + update_history( + f"{players[turn].name} bought {board.locations[CL].name} for ${price}") else: - update_history(f"{players[turn].name} did not buy {board.locations[CL].name}") + update_history( + f"{players[turn].name} did not buy {board.locations[CL].name}") + def housing_logic(p: Player): update_status(p, "properties") - propertyid = input("What property do you want to build on? Enter property # or 'e' to exit."+ + propertyid = input("What property do you want to build on? Enter property # or 'e' to exit." + "\033[40;0H" + " " * 78+"\033[41;0H" + " " * 78+"\033[40;0H") flag = True exit = False - try: + try: if propertyid == 'e': exit = True else: - propertyid = int(propertyid) - except ValueError: ###AHHHHHHHH clean me please - print(f"\033[42;0" + COLORS.RED + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) + propertyid = int(propertyid) + except ValueError: # AHHHHHHHH clean me please + print(f"\033[42;0" + COLORS.RED + + f"Invalid input, please enter a number in {p.properties}", end=COLORS.RESET) flag = False if flag and not exit: if not propertyid in p.properties: print("You do not own this property!") - else: + else: family = board.locations[propertyid].color if family == COLORS.CYAN or family == COLORS.LIGHTBLACK or board.locations[propertyid].name.startswith("Electric"): print("This property cannot be improved.") flag = False - if flag: - for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): # check only a few properties around for efficiency + if flag: + # check only a few properties around for efficiency + for i in range(propertyid-3 if propertyid > 3 else 0, propertyid+5 if propertyid < 35 else 39): if board.locations[i].color == family: if not i in p.properties: print("You do not own a monopoly on these properties!")
monopoly.py#L214
elif 30 < propertyid < 40: cost = 200 max = 5 - board.locations[propertyid].houses - houses = input(f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") + houses = input( + f"Cost of housing is ${cost}. How many houses would you like to buy? (Max {max}/min 0)") try: houses = int(houses) - if(0 <= houses <= max): + if (0 <= houses <= max): p.cash -= cost * houses - update_history(f"{p} bought {houses} houses on {board.locations[propertyid].name}!") + update_history( + f"{p} bought {houses} houses on {board.locations[propertyid].name}!") board.locations[propertyid].houses += houses refresh_board() else:
monopoly.py#L229
if not exit: housing_logic(p) + def mortgage_logic(): - input("\033[37;0HWhat property to mortgage?") - -from datetime import datetime + input("\033[37;0HWhat property to mortgage?") + + def log_error(error_message: str) -> None: """ Log error message to errorlog.txt\n
monopoly.py#L241
current_datetime = datetime.now() formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S') f.write(f"{formatted_datetime}\n{error_message}\n") + ss.make_fullscreen()
monopoly.py#L260
board = Board(num_players) decks = Cards() -import style as s gameboard = s.get_graphics().get('gameboard') os.system('cls' if os.name == 'nt' else 'clear') print(COLORS.WHITE + "\033[0;0H", end="") print(gameboard) + def unittest(): players[1].buy(1, board)
monopoly.py#L277
players[3].buy(12, board) players[3].buy(28, board) + unittest() -#wipes the bottom of the screen where the player does all of their input +# wipes the bottom of the screen where the player does all of their input + + def bottom_screen_wipe(): print("\033[36;0H" + " " * 76) print("\033[37;0H" + " " * 76)
monopoly.py#L290
print("\033[43;0H" + " " * 76) print("\033[44;0H" + " " * 76) -#Rolls the dice and returns them for the player as a tuple +# Rolls the dice and returns them for the player as a tuple + + def roll(): die1 = random.randint(1, 6) die2 = random.randint(1, 6) - return(die1,die2) -#The function that handles the players -#second and third correspond to if its the players second or third consecutive turn, they are bools + return (die1, die2) +# The function that handles the players +# second and third correspond to if its the players second or third consecutive turn, they are bools + + def player_roll(num_rolls): print_commands() bottom_screen_wipe() - if(players[turn].order != -1): # If player is not bankrupt + if (players[turn].order != -1): # If player is not bankrupt player_color = COLORS.playerColors[turn] update_history(player_color + f"{players[turn].name}'s turn") print_commands()
monopoly.py#L310
update_history(f"Player {turn} rolled {dice[0]} and {dice[1]}") if dice[0] == dice[1]: - if num_rolls == 1: + if num_rolls == 1: update_history(f"{players[turn]} rolled doubles! Roll again.") elif num_rolls == 2: - update_history(f"{players[turn]} rolled doubles!(X2) Roll again.") + 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} rolled doubles three times\n in a row!") update_history(f"Player {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 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"Player {players[turn].order} 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}") + update_history( + f"{players[turn].name} landed on {board.locations[players[turn].location].name}") refresh_board() done_moving_around = False card = ""
monopoly.py#L335
done_moving_around = True if board.locations[players[turn].location].owner < 0: match board.locations[players[turn].location].owner: - case -1: #unowned + case -1: # unowned buy_logic() - case -2: #mortgaged + case -2: # mortgaged pass - case -3: #community chest + case -3: # community chest old_loc = players[turn].location - card = decks.draw_community_chest(players[turn], board, players) + card = decks.draw_community_chest( + players[turn], board, players) 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") - case -4: #chance + update_history( + f"{players[turn].name} drew a Community Chest card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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].name} drew a Chance card! {card}") + # check if chance card made player pass go + if old_loc > new_loc and new_loc != 10 and new_loc != players[turn].location - 3: + update_history( + f"Player {players[turn].order} 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 + case -5: # income tax players[turn].pay(200) - update_history(f"{players[turn].name} paid income tax ($200)") + update_history( + f"{players[turn].name} paid income tax ($200)") case -6: # jail pass case -7: # go to jail
monopoly.py#L367
pass case -9: # luxury tax players[turn].pay(100) - update_history(f"{players[turn].name} paid luxury tax ($100)") + update_history( + f"{players[turn].name} paid luxury tax ($100)") case -10: # go pass elif board.locations[players[turn].location].owner != players[turn].order:
monopoly.py#L384
rent = 10 * (dice[0] + dice[1]) players[turn].pay(rent) players[board.locations[cl].owner].receive(rent) - update_history(f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") + update_history( + f"{players[turn].name} paid ${rent} to {players[board.locations[cl].owner].name}") refresh_board() - #checks if player rolled a double, and has them roll again if they did. + # checks if player rolled a double, and has them roll again if they did. if dice[0] == dice[1] and players[turn].jail == False: - num_rolls +=1 + num_rolls += 1 player_roll(num_rolls) -while(True): + +while (True): # First time the player who's turn it is rolls their dice - #if they roll a double the function calls itself and updates its their number of consecutive rolls + # if they roll a double the function calls itself and updates its their number of consecutive rolls player_roll(num_rolls=1) - if(players[turn].cash > 0): - choice = input("\033[38;0He to end turn, p to manage properties, d to view a deed?") - while(choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen + if (players[turn].cash > 0): + choice = input( + "\033[38;0He to end turn, p to manage properties, d to view a deed?") + while (choice != 'e'): # @todo remove soon! players should not be able to do these actions during gameboard screen if choice == "e": pass elif choice == "p":
monopoly.py#L406
update_status(players[turn], "deed") else: print("Invalid option!") - choice = input("\033[38;0H'e' to end turn, p to manage properties, ?") + 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.") - option = input("\033[38;0HResolve debts before ending turn.").lower().strip() - if(option == "b"): # Declare bankruptcy + update_history( + f"Player {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.") players[turn].order = -1 - elif(option == "m"): # Mortgage properties + elif (option == "m"): # Mortgage properties pass - elif(option == "s"): # Sell houses/hotels + elif (option == "s"): # Sell houses/hotels housing_logic() # TODO! For now, just declare bankruptcy. Player should NOT, by default, be able to by pressing "enter"
monopoly.py#L430
# Wipe the bottom of the screen (input area) bottom_screen_wipe() - if(bankrupts == num_players - 1): + if (bankrupts == num_players - 1): break - turn = (turn + 1)%num_players + turn = (turn + 1) % num_players for index, player in enumerate(players): if player.order != -1: color = COLORS.playerColors[index] update_history(color + f"Player {index} wins!") break -print("\033[40;0H", end="") +print("\033[40;0H", end="")
banker.py#L2
import threading import os import style as s -import screenspace as ss +import screenspace as ss import battleship import networking as net import gamemanager as gm
banker.py#L18
global timer timer = 0 + class Client: def __init__(self, socket: socket.socket, name: str, money: int, properties: list):
banker.py#L57
server_socket.listen() s.print_w_dots("Waiting for clients...") - + # TEMP VARIABLE: Players should be hardcoded to 4 for printing/playing purposes # Alternatively, make game work for N players...? num_players = 1
banker.py#L71
if len(clients) != num_players: client_socket, addr = server_socket.accept() print(f"Got a connection from {addr}") - client_handler = threading.Thread(target=handshake, args=(client_socket,handshakes)) + client_handler = threading.Thread( + target=handshake, args=(client_socket, handshakes)) client_handler.start() - else: + else: game_full = True # # Give program a moment to evaluate handshakes # for h in handshakes:
banker.py#L87
s.print_w_dots("") return server_socket + def start_receiver(): """ This function handles all client-to-server requests (not the other way around). Function binds an independent receiving socket at the same IP address, one port above. For example, if the opened port was 3131, the receiver will open on 3132. - + Parameters: None Returns: None """ global player_data, timer, port - s.print_w_dots('[RECEIVER] Receiver started!') - # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. + s.print_w_dots('[RECEIVER] Receiver started!') + # Credit to https://stackoverflow.com/a/43151772/19535084 for seamless server-client handling. with socket.socket() as server: host = socket.gethostname() ip_address = socket.gethostbyname(host) - server.bind((ip_address,int(port+1))) + server.bind((ip_address, int(port+1))) server.listen() - s.print_w_dots('[RECEIVER] Receiver accepting connections at {}'.format(port+1)) + s.print_w_dots( + '[RECEIVER] Receiver accepting connections at {}'.format(port+1)) to_read = [server] # add server to list of readable sockets. connected_clients = {} while True: # check for a connection to the server or data ready from clients. # readers will be empty on timeout. - readers,_,_ = select.select(to_read,[],[],0.1) + readers, _, _ = select.select(to_read, [], [], 0.1) for reader in readers: if reader is server: - player,address = reader.accept() + player, address = reader.accept() # Client(player, 'Player', starting_cash, []) s.print_w_dots('Player connected from: ' + address[0]) - connected_clients[player] = address # store address of client in dict - to_read.append(player) # add client to list of readable sockets + # store address of client in dict + connected_clients[player] = address + # add client to list of readable sockets + to_read.append(player) else: data = reader.recv(1024) handle_data(data, reader) - - if not data: # No data indicates disconnect + + if not data: # No data indicates disconnect s.print_w_dots(f'Player at {address[0]} disconnected.') - to_read.remove(reader) # remove from monitoring - del connected_clients[reader] # remove from dict as well - if(len(connected_clients) == 0): - s.print_w_dots('[RECEIVER] All connections dropped. Receiver stopped.') + to_read.remove(reader) # remove from monitoring + # remove from dict as well + del connected_clients[reader] + if (len(connected_clients) == 0): + s.print_w_dots( + '[RECEIVER] All connections dropped. Receiver stopped.') return - print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ',flush=True,end=f'\r{s.COLORS.RESET}') + print(f'{s.set_cursor_str(90, 0)}{s.COLORS.backBLUE}Time passed since last command: {timer}. ', + flush=True, end=f'\r{s.COLORS.RESET}') timer += 1
banker.py#L142
gm.add_game(gm.Game('Battleship', [None] * 2, 'board', 'other_data')) gm.add_game(gm.Game('Battleship', [-1] * 3, 'board', 'other_data')) + def handle_data(data: bytes, client: socket.socket) -> str: """ Handles all data received from player sockets. - + Parameters: data (str) Data received from player sockets. - + Returns: str representing the response to the player's data. """
banker.py#L166
if gm.game_exists('Battleship') == False: s.print_w_dots('No active games to join.') number_of_players = 1 - s.print_w_dots(f'Creating new Battleship with {number_of_players} players.') + s.print_w_dots( + f'Creating new Battleship with {number_of_players} players.') battleship_game = battleship.start_game() - gm.add_game(gm.Game('Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) + gm.add_game(gm.Game( + 'Battleship', [-1] * number_of_players, battleship_game.board, battleship_game)) s.print_w_dots('Game created.') gm.get_game_by_id(0).other_data.player_names.append(client_name) s.print_w_dots(f'Player {client_name} joined game.') - + elif gm.player_in_game('Battleship', client_name) == True: with open('errorlog.txt', 'a') as f: f.write(f'Player {client_name} already in game.Line178\n') if len(gm.get_game_by_name('Battleship')) > 1: - print('\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') - net.send_message(client, gm.display_games(name='Battleship', player_name=client_name)) - - else: # should only appear if player is in multiple games + print( + '\n\n\nPlayer is in multiple games, need to select a specific game to rejoin.') + net.send_message(client, gm.display_games( + name='Battleship', player_name=client_name)) + + else: # should only appear if player is in multiple games net.send_message(client, gm.display_games()) # battleship_board = + battleship_game.popup("Players: " + str(gm.get_game_by_id(0).other_data.player_names))
banker.py#L189
# net.send_message(client, battleship_board) # s.print_w_dots(f'Gameboard sent to player {client}') + def handshake(client_socket: socket.socket, handshakes: list): """ As players connect, they attempt to handshake the server, this function handles that and only starts the game once 4 handshakes have been successfully resolved. - + Parameters: client_socket (socket.socket) Server sender socket which players connect to at game initialization.
banker.py#L206
if message == "Connected!": handshakes[len(clients)] = True clients.append(Client(client_socket, 'Player 1', 2000, [])) - clients[len(clients)-1].name = input(f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") + clients[len(clients)-1].name = input( + f"{s.COLORS.backGREEN}{s.set_cursor_str(70,25)}What is this player's name?{s.COLORS.RESET}\n") # If the player doesn't enter a name, assign a default name. # Also blacklist other illegal names here that would break the game. if clients[len(clients)-1].name == "" or clients[len(clients)-1].name == "PAD ME PLEASE!": - clients[len(clients)-1].name = f"Player {len(clients)}" - else: + clients[len(clients)-1].name = f"Player {len(clients)}" + else: handshakes[len(clients)] = False + def get_client_by_socket(socket: socket.socket) -> Client: """ Returns the client object associated with the given socket. - + Parameters: socket (socket.socket) The socket of the client. - + Returns: Client object associated with the given socket. """
banker.py#L232
if client.socket.getpeername()[0] == socket.getpeername()[0]: return client + def set_gamerules() -> None: """ Configure all gamerule variables according to Banker user input. Repeats until successful. - + Parameters: None Returns: None """ global bank_cash, starting_cash try: - bank_cash = int(input("Enter the amount of money the bank starts with: ")) - starting_cash = int(input("Enter the amount of money each player starts with: ")) + bank_cash = int( + input("Enter the amount of money the bank starts with: ")) + starting_cash = int( + input("Enter the amount of money each player starts with: ")) except: print("Failed to set gamerules. Try again.") input() set_gamerules() + if __name__ == "__main__": os.system("cls")
banker.py#L257
start_receiver() # print(f"Found {players}, each at: ") # for player in player_data: - # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) + # print(s.Fore.BLUE+ str(player_data[player][socket.socket])) # print(s.Style.RESET_ALL) # set_gamerules()
build (3.9)
Process completed with exit code 30.
build (3.8)
Process completed with exit code 30.
build (3.10)
The job was canceled because "_3_8" failed.
build (3.10)
The operation was canceled.
build (3.9)
The following actions use a deprecated Node.js version and will be forced to run on node20: actions/setup-python@v3, wearerequired/[email protected]. For more info: https://github.blog/changelog/2024-03-07-github-actions-all-actions-will-run-on-node20-instead-of-node16-by-default/
build (3.8)
The following actions use a deprecated Node.js version and will be forced to run on node20: actions/setup-python@v3, wearerequired/[email protected]. For more info: https://github.blog/changelog/2024-03-07-github-actions-all-actions-will-run-on-node20-instead-of-node16-by-default/