diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml
new file mode 100644
index 0000000..8bf3a6d
--- /dev/null
+++ b/.idea/sqldialects.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/__pycache__/board.cpython-310.pyc b/__pycache__/board.cpython-310.pyc
deleted file mode 100644
index 1af7b95..0000000
Binary files a/__pycache__/board.cpython-310.pyc and /dev/null differ
diff --git a/__pycache__/board.cpython-311.pyc b/__pycache__/board.cpython-311.pyc
deleted file mode 100644
index ed8c53d..0000000
Binary files a/__pycache__/board.cpython-311.pyc and /dev/null differ
diff --git a/__pycache__/board.cpython-39.pyc b/__pycache__/board.cpython-39.pyc
deleted file mode 100644
index 6b40ac5..0000000
Binary files a/__pycache__/board.cpython-39.pyc and /dev/null differ
diff --git a/__pycache__/main.cpython-310.pyc b/__pycache__/main.cpython-310.pyc
index b588b35..0f07ea1 100644
Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ
diff --git a/__pycache__/websocket_test.cpython-310.pyc b/__pycache__/websocket_test.cpython-310.pyc
new file mode 100644
index 0000000..00302d7
Binary files /dev/null and b/__pycache__/websocket_test.cpython-310.pyc differ
diff --git a/board.py b/board.py
deleted file mode 100644
index 3102275..0000000
--- a/board.py
+++ /dev/null
@@ -1,174 +0,0 @@
-import random
-
-
-# Global variables
-
-
-def dice_roll(player):
- first_dice = random.randint(1, 6)
- second_dice = random.randint(1, 6)
- total_dice = first_dice + second_dice
- # if first_dice == second_dice:
- # print(f'{player.username} rolled doubles of {first_dice}!') # Change player name
- # print(f'{player.username} rolled {total_dice}', end='\n\n') # Change player name
- return total_dice
-
-
-# models board:
-# testVar = 20
-
-moves = {
- "Roll dice": "r",
- "Build a house": "h",
- "Build a hotel": "f",
- "View assets owned": "v",
- "Sell property": "s",
- "End turn": "x"
-}
-
-BOARD_TILES_NUMBER = 32
-# BOARD_TILES = {"Start/GO",
-# "Goa",
-# "Income Tax",
-# "Pondicherry",
-# "Secunderabad Station",
-# "Rishikesh",
-# "Nainital",
-# "Gulmarg",
-# "Visiting Jail/Jail",
-# "Udaipur",
-# "Raipur",
-# "Darjeeling",
-# "Chennai Central Station",
-# "Vijayawada",
-# "Wayanad",
-# "Mysore",
-# "Free Parking",
-# "Gangtok",
-# "Ahmedabad",
-# "Lucknow",
-# "Chatrapathi Shivaji Terminal Station",
-# "Jaipur",
-# "Bhopal",
-# "Kochi",
-# "GO TO JAIL",
-# "Bangalore",
-# "Hyderabad",
-# "Kolkata",
-# "Howrah Station",
-# "Delhi",
-# "Luxury Tax",
-# "Mumbai"}
-
-BOARD_TILES = {0: 'Start/GO', 1: 'Goa', 2: 'Income Tax', 3: 'Pondicherry', 4: 'Railway1: Secundarabad Station',
- 5: 'Rishikesh', 6: 'Nainital', 7: 'Gulmarg', 8: 'Visiting Jail', 9: 'Udaipur', 10: 'Raipur',
- 11: 'Darjeeling', 12: 'Railway2: Chennai Central Station', 13: 'Vijayawada', 14: 'Waynad', 15: 'Mysore',
- 16: 'Free Parking', 17: 'Gangtok', 18: 'Ahmedabad', 19: 'Lucknow',
- 20: 'Railway3: Chatrapathi Shivaji Terminal Station', 21: 'Jaipur', 22: 'Bhopal', 23: 'Kochi',
- 24: 'GO TO JAIL', 25: 'Bangalore', 26: 'Hyderabad', 27: 'Kolkata', 28: 'Railway4: Howrah Station',
- 29: 'Delhi', 30: 'Luxury Tax', 31: 'Mumbai'}
-
-# Dictionary looking ass
-# {key : value}
-# {tile_name : description, color, price, mortage_value, [rent with 0 houses, rent with 1 house, rent with 2 houses, rent with hotel], house_building_cost, hotel_building_cost, owned}
-
-BOARD_TILES_INFO = {
- "Start/GO": ["Collect $200 salary as you pass GO", None, None, None, [0, 0, 0, 0], None, None, None],
- "Goa": ["This beautiful coastal state is known for its beaches, nightlife and Portuguese architecture.", "brown",
- 60, 30, [2, 10, 30, 90], 50, 50, False],
- "Income Tax": ["Pay 10% of your total worth or $200, whichever is lesser.", None, None, None, [0, 0, 0, 0], None,
- None, None],
- "Pondicherry": ["This Union Territory is known for its French architecture and quaint cafes.", "brown", 60, 30,
- [4, 20, 60, 180], 50, 50, False],
- "Railway1: Secundarabad Station": ["This railway station connects Hyderabad to various parts of the country.",
- "black", 200, 100, [25, 50, 100, 200], None, None, False],
- "Rishikesh": [
- "This holy city is known for its beautiful temples and as a hub for adventure sports like river rafting.",
- "light blue", 100, 50, [6, 30, 90, 270], 50, 50, False],
- "Nainital": ["This hill station is known for its scenic beauty and is a popular tourist destination.", "light blue",
- 100, 50, [6, 30, 90, 270], 50, 50, False],
- "Gulmarg": ["This ski resort in Jammu & Kashmir is known for its picturesque landscapes and winter sports.",
- "light blue", 120, 60, [8, 40, 100, 300], 50, 50, False],
- "Visiting Jail": ["Just visiting", None, None, None, [0, 0, 0, 0], None, None, False],
- "Udaipur": ["This city in Rajasthan is known for its beautiful lakes, palaces and museums.", "pink", 140, 70,
- [10, 50, 150, 450], 100, 100, False],
- "Raipur": ["This city in Chhattisgarh is known for its rich cultural heritage and is a commercial hub.", "pink",
- 140, 70, [10, 50, 150, 450], 100, 100, False],
- "Darjeeling": [
- "This hill station in West Bengal is known for its tea plantations and scenic views of the Himalayas.", "pink",
- 160, 80, [12, 60, 180, 500], 100, 100, False],
- "Railway2: Chennai Central Station": [
- "This railway station is one of the busiest in the country and connects Chennai to various parts of India.",
- "black", 200, 100, [25, 50, 100, 200], None, None, False],
- "Vijayawada": ["This city in Andhra Pradesh is known for its rich history, cultural heritage and scenic beauty.",
- "orange", 180, 90, [14, 70, 200, 550], 100, 100, False],
- "Waynad": [
- " A scenic hill station located in the Western Ghats of Kerala known for its lush green forests, misty valleys, and wildlife.",
- "Orange", 180, 90, [14, 70, 200, 550], 100, 100, False],
- "Mysore": [
- "A city in the state of Karnataka known for its rich cultural heritage, palaces, and vibrant festivals such as Dasara.",
- "Orange", 200, 100, [16, 80, 220, 600], 100, 100, False],
- "Free Parking": ["A space on the board where players can park for free without any penalty.", "N/A", None, None,
- [0, 0, 0, 0], 0, 0, None],
- "Gangtok": [
- "The capital city of Sikkim known for its panoramic views of the Himalayas, Buddhist monasteries, and adventurous activities such as trekking and river rafting.",
- "Red", 220, 110, [18, 90, 250, 700], 150, 150, False],
- "Ahmedabad": [
- "A city in the state of Gujarat known for its rich history, cultural heritage, and the Sabarmati Ashram, the former residence of Mahatma Gandhi.",
- "Red", 220, 110, [18, 90, 250, 700], 150, 150, False],
- "Lucknow": [
- "A city in the state of Uttar Pradesh known for its Nawabi culture, cuisine, and the grandiose Bara Imambara and Chhota Imambara.",
- "Red", 240, 120, [20, 100, 300, 750], 150, 150, False],
- "Railway3: Chatrapathi Shivaji Terminal Station": [
- "A railway station in Mumbai, Maharashtra known for its impressive Victorian Gothic architecture and being one of the busiest railway stations in India.",
- "Railway", 200, 100, [25, 50, 100, 200], None, None, False],
- "Jaipur": ["The capital city of Rajasthan known for its grandiose palaces, forts, and colorful markets.", "Yellow",
- 260, 130, [22, 110, 330, 800], 150, 150, False],
- "Bhopal": ["The capital city of Madhya Pradesh known for its beautiful lakes, national parks, and museums.",
- "Yellow", 260, 130, [22, 110, 330, 800], 150, 150, False],
- "Kochi": [
- "A city in the state of Kerala known for its backwaters, beaches, and historic landmarks such as the Mattancherry Palace and Jewish Synagogue.",
- "Yellow", 280, 140, [24, 120, 360, 850], 150, 150, False],
- "GO TO JAIL": ["A space on the board that represents being sent to jail if a player lands on it.", "N/A", None,
- None, [0, 0, 0, 0], 0, 0, None],
- "Bangalore": [
- "The capital city of Karnataka known for its technology parks, nightlife, and beautiful parks such as the Lalbagh Botanical Garden.",
- "Green", 300, 150, [26, 130, 390, 900], 200, 200, False],
- "Hyderabad": [
- " The capital city of Telangana known for its rich history, cuisine, and the famous Charminar monument.",
- "Green", 300, 150, [26, 130, 390, 900], 200, 200, False],
- "Kolkata": [
- " The capital city of West Bengal known for its colonial architecture, literary culture, and delicious street food.",
- "Green", 320, 160, [28, 150, 450, 1000], 200, 200, False],
- "Railway4: Howrah Station": [
- "A railway station in Kolkata, West Bengal known for being one of the largest and busiest railway stations in India.",
- "Railway", 200, 100, [25, 50, 100, 200], None, None, False],
- "Delhi": [
- "The capital city of India known for its history, culture, and landmarks such as the Red Fort, Qutub Minar, and India Gate.",
- "Dark Blue", 350, 175, [35, 175, 500, 1100], 200, 200, False],
- "Luxury Tax": [" A space on the board where players must pay a luxury tax.", "N/A", None, None, [0, 0, 0, 0], 0, 0,
- None],
- "Mumbai": [
- "The financial capital of India known for its vibrant culture, Bollywood film industry, and landmarks such as the Gateway of India and Marine Drive.",
- "Dark Blue", 400, 200, [50, 200, 600, 1400], 200, 200, False]
-}
-
-
-# Moves list, change this to display on the web page
-def display_moves():
- # Display player stats(name, cash in hand, rounds played, position)
- print('-------------Moves-------------')
-
- print("{:<30}{}".format('Roll dice', 'r'))
- print("{:<30}{}".format('Build a house', 'h'))
- print("{:<30}{}".format('Build a hotel', 'f'))
- print("{:<30}{}".format('View assets owned', 'v'))
- print("{:<30}{}".format('Sell property', 's'))
- print("{:<30}{}".format('End turn', 'x'), end='\n\n\n')
-
-# display_moves()
-
-# print(BOARD_TILES_INFO['Start/GO'])
-# for i in BOARD_TILES_INFO:
-# print(i)
-# print(BOARD_TILES_INFO[i])
diff --git a/database/Dao.py b/database/Dao.py
index d1a6cd1..a1f7ba3 100644
--- a/database/Dao.py
+++ b/database/Dao.py
@@ -2,7 +2,6 @@
from pprint import pprint
import mysql.connector as conn
-import board
from database.DaoConstants import DaoConstants
from models.tile import Tile
class Dao:
@@ -11,14 +10,14 @@ def __init__(self):
None
# Display with condition FIX: make a single select_query with if else single or multiple to execute fetchOne or fetchAll
- def select_query(self,query, values):
+ def select_query(self, query, values):
try:
self.db = conn.connect(host=DaoConstants.HOST,
user=DaoConstants.USER,
passwd=DaoConstants.PASSWD,
database=DaoConstants.DATABASE)
select_cursor = self.db.cursor()
- print(query)
+ # print(query)
if(len(values)>1):
select_cursor.execute(query, (values[0],values[1]))
@@ -45,7 +44,7 @@ def select_all_query(self,query,istile):
user=DaoConstants.USER,
passwd=DaoConstants.PASSWD,
database=DaoConstants.DATABASE)
- print(query)
+ # print(query)
select_all_cursor = self.db.cursor()
select_all_cursor.execute(query)
rows = select_all_cursor.fetchall()
@@ -73,11 +72,11 @@ def insertion_query(self,query, values):
user=DaoConstants.USER,
passwd=DaoConstants.PASSWD,
database=DaoConstants.DATABASE)
- print(query)
+ # print(query)
insertion_cursor = self.db.cursor()
if(len(values)>1):
print(values[0],values[1])
- formatted_query = query % (values[0],values[1])
+ formatted_query = query % values
print(formatted_query)
insertion_cursor.execute(formatted_query)
else:
diff --git a/database/DaoConstants.py b/database/DaoConstants.py
index ad6053c..67815e8 100644
--- a/database/DaoConstants.py
+++ b/database/DaoConstants.py
@@ -1,24 +1,36 @@
class DaoConstants:
- #Always list the columns u wanna fetch do not use * in any case
- GET_PLAYERS_IN_ROOM = 'select room_id, player_id, player_balance, player_prop_id, player_position, player_round from player where room_id = %s; '
- ADD_PLAYER_IN_ROOM=''
- CREATE_ROOM=''
- #Always list the columns u wanna fetch do not use * in any case
- BUY_PROPERTY=''#room id player id in player table
- UPDATE_MONEY=''#room id player id player table
- UPDATE_WINNER_FOR_ROOM=''#update winner with user id in room table
- SELECT_LOGS_BY_ROOM_ID='select log_value where room_id= %s'
- # Might remove this
- GET_USERNAME_FROM_PLAYER = 'SELECT u.username FROM user u JOIN player p ON u.user_id = p.player_id WHERE p.room_id = %s;'
- GET_PROPERTY_LIST='select pl.property_id,pl.property_name,pl.property_description,pl.property_cost,pl.property_rent,pl.property_house_cost,pl.property_hotel_cost,pl.is_property_special from property_list pl;'
- GET_PROPERTY_OWNER='select p.room_id, p.player_id, u.username,p.player_balance, p.player_position, p.player_round from player p join user u on p.player_id=u.user_id where p.player_id= (select plpr.player_id from player_property plpr where plpr.property_id=%s and plpr.room_id=%s); '
- INSERT_LOG="INSERT INTO logs (log_value, room_id) VALUES ('%s', %s);"
- #move them to a .env file and add it in gitignore
- HOST='143.42.112.230'
- USER='gokulprathin'
- PASSWD='vIn9e:fW*ic^Y=_'
- DATABASE='default_db'
+ # Always list the columns u wanna fetch do not use * in any case
+ GET_PLAYERS_IN_ROOM = 'select room_id, player_id, player_balance, player_prop_id, player_position, player_round from player where room_id = %s; '
+ ADD_PLAYER_IN_ROOM = 'INSERT INTO TABLE player (room_id, player_id, player_balance, player_position, player_round) VALUES (%s, %s, 1500, 0, 0)' # This should have game_round = 0, position = 0, balance = 1500 and there is no need for assets in the player table. Write the query accordingly
+ DISPLAY_WIN_LOSS = "SELECT u.username, CONCAT('W = ', COALESCE(wins, 0), ', L = ', COALESCE(losses, 0)) AS win_loss FROM user u " \
+ "LEFT JOIN (SELECT room_player, SUM(IF(room_winner = room_player, 1, 0)) AS wins, SUM(IF(room_winner != room_player, 1, 0)) AS losses FROM room " \
+ "GROUP BY room_player) wl ON u.user_id = wl.room_player ORDER BY u.username;)" # should display number of wins and losses(total games - wins) of all playeres
+ CREATE_ROOM = 'INSERT INTO TABLE user (room_player, room_status) VALUES (%s, %s)' # should pass room_player(player_id basically) and 'ACTIVE' in place of the params. room id is supposed to be auto_increment, if it throws an error it means that the table wasnt created properly
+ JOIN_ROOM = 'INSERT INTO TABLE user (room_id, room_player, room_status) VALUES (%s, %s, %s)' # should pass room_player(player_id basically) and 'ACTIVE' in place of the params.
+ CREATE_USER = 'INSERT INTO TABLE user (username, email, pass) VALUES(%s, %s, %s)'
+ FETCH_USER = 'SELECT username from TABLE user where user_id = %s' # pretty sure this is wrong, but idk what is needed here
+ # GET_PLAYER_DETAILS = 'select u.username, p.player_position'
+ GET_PROPERTY_OWNED = 'SELECT property_id from player_property where room_id = %s and player_id = %s'
- def __init__(self) -> None:
- pass
-
\ No newline at end of file
+ # Always list the columns u wanna fetch do not use * in any case
+
+ GET_PROPERTY_FROM_PLAYER_OWNED = 'SELECT pl.property_name FROM player_property pp JOIN property_list pl ON pp.property_id = pl.property_id WHERE pp.room_id = %s AND pp.player_id = %s;'
+ BUY_PROPERTY = 'INSERT INTO player_property VALUES (%s, %s, %s);' # room id player id in player table
+ SELL_PROPERTY = 'DELETE FROM player_property WHERE room_id = %s AND player_id = %s AND property_id = %s'
+ UPDATE_MONEY = 'UPDATE player set player_balance = %s where room_id = %s and player_id = %s' # room id player id player table
+ UPDATE_EVERYTHING = 'UPDATE player set player_balance = %s, player_position = %s, player_round = %s where room_id = %s and player_id = %s'
+ UPDATE_WINNER_FOR_ROOM = 'UPDATE room set room_status = %s, room_winner = %s where room_id = %s' # update winner with user id and set status to inactive in room table
+ SELECT_LOGS_BY_ROOM_ID = 'select log_value where room_id= %s'
+ # Might remove this
+ GET_USERNAME_FROM_PLAYER = 'SELECT u.username FROM user u JOIN player p ON u.user_id = p.player_id WHERE p.room_id = %s;'
+ GET_PROPERTY_LIST = 'select pl.property_id,pl.property_name,pl.property_description,pl.property_cost,pl.property_rent,pl.property_house_cost,pl.property_hotel_cost,pl.is_property_special from property_list pl;'
+ GET_PROPERTY_OWNER = 'select p.room_id, p.player_id, u.username,p.player_balance, p.player_position, p.player_round from player p join user u on p.player_id=u.user_id where p.player_id= (select plpr.player_id from player_property plpr where plpr.property_id=%s and plpr.room_id=%s); '
+ INSERT_LOG = "INSERT INTO logs (log_value, room_id) VALUES ('%s', %s);"
+ # move them to a .env file and add it in gitignore
+ HOST = '143.42.112.230'
+ USER = 'gokulprathin'
+ PASSWD = 'vIn9e:fW*ic^Y=_'
+ DATABASE = 'default_db'
+
+ def __init__(self) -> None:
+ pass
diff --git a/database/__pycache__/Dao.cpython-310.pyc b/database/__pycache__/Dao.cpython-310.pyc
new file mode 100644
index 0000000..2ae2a39
Binary files /dev/null and b/database/__pycache__/Dao.cpython-310.pyc differ
diff --git a/database/__pycache__/Dao.cpython-39.pyc b/database/__pycache__/Dao.cpython-39.pyc
new file mode 100644
index 0000000..af8be7d
Binary files /dev/null and b/database/__pycache__/Dao.cpython-39.pyc differ
diff --git a/database/__pycache__/DaoConstants.cpython-310.pyc b/database/__pycache__/DaoConstants.cpython-310.pyc
new file mode 100644
index 0000000..1fc3279
Binary files /dev/null and b/database/__pycache__/DaoConstants.cpython-310.pyc differ
diff --git a/database/__pycache__/DaoConstants.cpython-39.pyc b/database/__pycache__/DaoConstants.cpython-39.pyc
new file mode 100644
index 0000000..711cb9e
Binary files /dev/null and b/database/__pycache__/DaoConstants.cpython-39.pyc differ
diff --git a/game_driver.py b/game_driver.py
index e3bb3e1..55b3cd2 100644
--- a/game_driver.py
+++ b/game_driver.py
@@ -1,8 +1,7 @@
import board
-from board import display_moves, dice_roll
-from utils.driver import game_over
+from utils.driver import game_over, dice_roll, moves_list
from models import player
-import database.db_connect
+import database.Dao
# Statically instantiating three players
# player1 = player.Player('Ali', 0, 0, 1500, ['Goa', 'Pondicherry', 'Rishikesh', 'Nainital', 'Gulmarg', 'Udaipur', 'Raipur', 'Darjeeling', 'Vijayawada', 'Waynad'], False, False)
@@ -79,7 +78,7 @@ def game_start():
print(f'Cash - {player.balance}\t Rounds played - {player.game_round}\t Player position - {player.position}')
print('----------------------------------------------------------------')
- display_moves()
+ moves_list()
turn_ended = False
has_rolled = False
diff --git a/main.py b/main.py
index 8c8ce36..391b18d 100644
--- a/main.py
+++ b/main.py
@@ -1,18 +1,25 @@
# FastAPI import statements
-from fastapi import FastAPI, Request
+from fastapi import FastAPI, Request, WebSocket
from pydantic import BaseModel
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
#from move import router as MoveRouter
from fastapi.templating import Jinja2Templates
-from database.Dao import Dao
-from database.DaoConstants import DaoConstants
+from starlette.websockets import WebSocketDisconnect
+
+from database.Dao import Dao
+from database.DaoConstants import DaoConstants
+import http.client
+import ssl
+import uvicorn
# Game Logic import statements
-from utils.driver import process_move
+from service.monopoly_Instance import monopoly_Instance
+
app = FastAPI()
-app.include_router(MoveRouter, tags=["moves"], prefix="/game")
+
+# app.include_router(MoveRouter, tags=["moves"], prefix="/game")
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="static")
@@ -21,13 +28,40 @@
class Move(BaseModel):
move: str
+@app.get('/')
+async def read_main(request: Request):
+ return templates.TemplateResponse("index.html", {"request": request})
+
+
+
+# @app.post("/submit_move")
+# async def submit_move(move: Move):
+# # Process the move using your existing Monopoly game logic
+# # Replace this function with your actual game logic
+# message = f'Player entered {move.move}'
+# a = game_start(move)
+# while a is not None:
+#
+# return message
+
+@app.websocket("/submit_move")
+async def websocket_endpoint(websocket: WebSocket, move: Move):
+ await websocket.accept()
+ # room.add_player(websocket)
+ # await room.broadcast(f"Player joined the room: {websocket.client.host}")
+ try:
+ while True:
+ message = await websocket.receive_text()
+ print(message)
+ await print(message)
+ # await room.broadcast(message)
+ except Exception as e:
+ print('Error is ', e)
+ # room.remove_player(websocket)
+ # await room.broadcast(f"Player left the room: {websocket.client.host}")
+
+# @app.get()
-@app.post("/submit_move")
-async def submit_move(move: Move):
- # Process the move using your existing Monopoly game logic
- # Replace this function with your actual game logic
- result = process_move(move.move)
- return {"message": result}
@app.get("/getLogs", response_class=JSONResponse)
async def get_logs(request: Request, room_id: int):
@@ -40,5 +74,14 @@ async def get_logs(request: Request, room_id: int):
except Exception as e:
return f"An exception occurred: {str(e)}"
+# if __name__ == "__main__":
+# context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
+# context.load_cert_chain(certfile="./tls/ca-cert.pem", keyfile="./tls/ca-key.pem")
+# uvicorn.run(app, host="0.0.0.0", port=8443, ssl_context=context)
+
# How to replace stuff in the output area
# content = content.replace('', f'')
+
+if __name__ == "__main__":
+ uvicorn.run("main:app", host="0.0.0.0", port=8443, reload=True, ssl_keyfile="./tls/ca-key.pem", ssl_certfile="./tls/ca-cert.pem")
+
diff --git a/models/__pycache__/player.cpython-310.pyc b/models/__pycache__/player.cpython-310.pyc
new file mode 100644
index 0000000..9571a9e
Binary files /dev/null and b/models/__pycache__/player.cpython-310.pyc differ
diff --git a/models/__pycache__/player.cpython-39.pyc b/models/__pycache__/player.cpython-39.pyc
index c7a1cb8..1be46fe 100644
Binary files a/models/__pycache__/player.cpython-39.pyc and b/models/__pycache__/player.cpython-39.pyc differ
diff --git a/models/__pycache__/tile.cpython-310.pyc b/models/__pycache__/tile.cpython-310.pyc
new file mode 100644
index 0000000..f69f3e8
Binary files /dev/null and b/models/__pycache__/tile.cpython-310.pyc differ
diff --git a/models/__pycache__/tile.cpython-39.pyc b/models/__pycache__/tile.cpython-39.pyc
new file mode 100644
index 0000000..8da2db7
Binary files /dev/null and b/models/__pycache__/tile.cpython-39.pyc differ
diff --git a/models/player.py b/models/player.py
index a6fb750..0760b08 100644
--- a/models/player.py
+++ b/models/player.py
@@ -1,15 +1,15 @@
from typing import List, Any
import mysql.connector
-import board
+# Add an insert query at the end of all of these functions before something is being returned
class Player:
- def __init__(self, room_id, player_id, username,money,position,game_round):
+ def __init__(self, room_id, player_id, username, money, position, game_round):
self.room_id = room_id
self.player_id = player_id
self.username = username
- self.position =position
+ self.position = position
self.game_round = game_round
self.balance = money
self.assets_owned = []
@@ -22,10 +22,7 @@ def player_moves(self, dice_value):
self.add_balance(200)
self.game_round += 1
# print(player.position)
- print(f'You are now at {board.BOARD_TILES[self.position]}')
- print(
- f'Description - {board.BOARD_TILES_INFO[board.BOARD_TILES[self.position]][0]}',
- end='\n\n\n')
+ return self.position
def display_player_details(self):
print(f'Name - {self.username}')
@@ -34,20 +31,25 @@ def display_player_details(self):
print(f'Assets owned - {self.assets_owned}')
def buy_tile(self, tile):
- self.assets_owned.append(tile)
- price = board.BOARD_TILES_INFO[tile][2]
+ # Adding name of the tile to the list of assets owned
+ self.assets_owned.append(tile.tile_name)
+ price = tile.cost
self.balance = self.balance - price
+ print(f'{tile.tile_name} bought!')
+
def sell_tile(self, tile):
- self.assets_owned.remove(tile)
- price = board.BOARD_TILES_INFO[tile][2]
+ # Removing name of the tile from list of assets owned
+ price = tile.cost / 2
self.balance = self.balance + price
print(f'Property Sold! New Balance - {self.balance}')
+ self.assets_owned.remove(tile.tile_name)
+ return tile.tile_id
def build_house(self, tile):
if tile in self.assets_owned:
- self.balance -= board.BOARD_TILES_INFO[tile][5]
- print(f'House built on {tile}')
+ self.balance -= tile.house_cost
+ print(f'House built on {tile.tile_name}')
else:
print('Asset is not owned!')
return False
@@ -55,16 +57,16 @@ def build_house(self, tile):
def build_hotel(self, tile):
if tile in self.assets_owned:
- self.balance -= board.BOARD_TILES_INFO[tile][6]
- print(f'Hotel built on {tile}')
+ self.balance -= tile.hotel_cost
+ print(f'Hotel built on {tile.tile_name}')
else:
print('Asset is not owned!')
return False
pass
def charge_rent(self, tile):
- rent = board.BOARD_TILES_INFO[board.BOARD_TILES[tile]][4][0]
- print(rent)
+ rent = tile.rent
+ # print(rent)
self.balance -= rent
return rent
@@ -75,7 +77,7 @@ def reduce_balance(self, reduced_amount):
self.balance -= reduced_amount
def check_balance(self, tile):
- if self.balance > board.BOARD_TILES_INFO[board.BOARD_TILES[tile]][2]:
+ if self.balance > tile.cost:
return True
else:
return False
@@ -85,7 +87,7 @@ def go_to_jail(self):
print('Sent to Jail!', end='\n\n')
self.game_round += 2
- def printPlayer(self):
+ def print_player(self):
print(vars(self))
diff --git a/server.py b/server.py
new file mode 100644
index 0000000..36f3b97
--- /dev/null
+++ b/server.py
@@ -0,0 +1,10 @@
+import uvicorn
+
+if __name__ == '__main__':
+ uvicorn.run("main:app",
+ host="0.0.0.0",
+ port=8432,
+ reload=True,
+ ssl_certfile="./tls/ca-cert.pem",
+ ssl_keyfile="./tls/ca-key.pem"
+ )
\ No newline at end of file
diff --git a/service/__pycache__/monopoly_Instance.cpython-310.pyc b/service/__pycache__/monopoly_Instance.cpython-310.pyc
new file mode 100644
index 0000000..1b26896
Binary files /dev/null and b/service/__pycache__/monopoly_Instance.cpython-310.pyc differ
diff --git a/service/__pycache__/monopoly_Instance.cpython-39.pyc b/service/__pycache__/monopoly_Instance.cpython-39.pyc
new file mode 100644
index 0000000..e0a1cbc
Binary files /dev/null and b/service/__pycache__/monopoly_Instance.cpython-39.pyc differ
diff --git a/service/__pycache__/room.cpython-39.pyc b/service/__pycache__/room.cpython-39.pyc
new file mode 100644
index 0000000..8c15849
Binary files /dev/null and b/service/__pycache__/room.cpython-39.pyc differ
diff --git a/service/monopoly_Instance.py b/service/monopoly_Instance.py
index 8a7a751..963dbad 100644
--- a/service/monopoly_Instance.py
+++ b/service/monopoly_Instance.py
@@ -1,21 +1,20 @@
-import board
-from board import display_moves, dice_roll
-#from utils.driver import game_over
-from models.player import Player
+from utils.driver import dice_roll, moves_list
+from models.player import Player
import database.Dao as databaseObj
import database.DaoConstants as DaoConst
from utils.loging import log
+from utils.driver import get_moves
class monopoly_Instance:
def __init__(self, roomID, player_list):
- self.db=databaseObj.Dao()
- self.daoConst=DaoConst.DaoConstants()
- self.player_list=player_list
- self.is_game_over= False
- self.tiles= self.db.select_all_query(self.daoConst.GET_PROPERTY_LIST,True)
- self.logger=log()
-
- def special_cards(self,tile, player):
+ self.db = databaseObj.Dao()
+ self.daoConst = DaoConst.DaoConstants()
+ self.player_list = player_list
+ self.is_game_over = False
+ self.tiles = self.db.select_all_query(self.daoConst.GET_PROPERTY_LIST, True)
+ self.logger = log()
+
+ def special_cards(self, tile, player):
if tile == 'Start/GO':
player.add_balance(200)
print('Collected $200!')
@@ -28,6 +27,8 @@ def special_cards(self,tile, player):
elif tile == 'GO TO JAIL':
player.go_to_jail()
+ message = 'Sent to jail. Skipping two rounds...'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
elif tile == 'Income Tax':
player.reduce_balance(200)
@@ -44,6 +45,7 @@ def game_winner(self):
highest_balance = player.balance
winner = player
#Write a dao stuff for updating winner for the room
+ # something like update table room set winner = (subquery of the guy that won idk)
return winner
@@ -54,113 +56,164 @@ def game_start(self):
correct_move= True
turn_ended = False
for player in self.player_list:
+ # while player.move == None:
+ # player.move = driver
# Displays player details
message= "%s's turn" % player.username
self.logger.log_info(message)
- self.db.insertion_query(self.daoConst.INSERT_LOG, (message.replace("'","''") , player.room_id))
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message.replace("'","''"), player.room_id))
+
+ message = 'Cash - %s \t Rounds played - %s \t Player position - %s' % (player.balance, player.game_round, player.position)
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
print(f'Cash - {player.balance}\t Rounds played - {player.game_round}\t Player position - {player.position}')
print('----------------------------------------------------------------')
- display_moves()
+ moves_list()
turn_ended = False
has_rolled = False
# Move validation
while not turn_ended:
- game_input = input('Enter your choice: ') # insert in log and display.
+ # Need to do some input
+ game_input = input('Enter your choice: ')
+ # game_input = self.moves
+
+ message = 'Enter your choice - %s' % game_input
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
# game_input = await request.body()
# Roll dice
if game_input.casefold() == 'r':
if not has_rolled:
has_rolled = True
- player.player_moves(dice_roll(player)) #diceroll rolls 2 dices for a player and moves them
-
+ player.player_moves(dice_roll(player))
current_tile=self.tiles[player.position]
-
+
+ print(f'{player.username} landed on {current_tile.tile_name} - {current_tile.description}')
+
+ message = '%s landed on %s - %s' % (player.username, current_tile.tile_name, current_tile.description)
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
asset_owned = False # assign this by
#Execute to get the tile_owner
tileInput=[current_tile.tile_id,player.room_id]
#tileOWNERInput
- tileOWNERInput=self.db.select_query( self.daoConst.GET_PROPERTY_OWNER,tileInput)
- print('This is tile owner',tileOWNERInput)
+ tileOWNERInput=self.db.select_query(self.daoConst.GET_PROPERTY_OWNER,tileInput)
+ # print('This is tile owner',tileOWNERInput)
tile_owner=None
- if tileOWNERInput :
+ if tileOWNERInput:
tile_owner = Player(room_id=tileOWNERInput[0][0], player_id=tileOWNERInput[0][1], username=tileOWNERInput[0][2], money=tileOWNERInput[0][3], position=tileOWNERInput[0][4], game_round=tileOWNERInput[0][5])
-
- if current_tile.cost != None :
+
+ if current_tile.cost != None:
if tile_owner is None:
print('The current tile owner is None')
- #BUYs LOGIC
+ # Nobody owns the tile, player can buy
+ # Need to do some input
is_buy = input(f'Buy {current_tile.tile_name}? [Y/N]')
+ message = 'Buy %s? [Y/N] - %s' % (current_tile.tile_name, is_buy)
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
if is_buy.casefold() == 'y':
# Check for balance
if player.check_balance(current_tile):
player.buy_tile(current_tile)
+ self.db.insertion_query(self.daoConst.BUY_PROPERTY,
+ (player.room_id, player.player_id, current_tile.tile_id))
+ # insert message that says tile bought
+ # message = '%s bought for %s' % (current_tile.tile_name,current_tile.cost)
else:
- print("insufficient Funds !!")
+ print("Insufficient Funds!!")
+ message = 'Insufficient Funds!!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
elif tile_owner.player_id != player.player_id:
- print('The current tile cost is: ',tile_owner.player_id )
# Deduct from current player
- rent = player.charge_rent(player.position)
+ rent = player.charge_rent(current_tile)
+
print(f'{tile_owner.username} charges you {rent} as rent')
- tile_owner.add_balance(rent)# insert updated money in DB
+ message = '%s charges you %s as rent' % (tile_owner.username, rent)
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
+ tile_owner.add_balance(rent) # insert updated money in DB
asset_owned = True # create entry in player_property
- break
+ break
else:
-
+
print('Player is on his own tile')
+ message = 'Player is on his own tile'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
#asset_owned = True
- break
- else :
- print('SPECIAL CARD!!!' ,vars(current_tile))
+ break
+
+ else:
+ # print('SPECIAL CARD!!!' ,vars(current_tile))
# Insert non-buyable logic special card
self.special_cards(current_tile, player)
else:
print('You have already rolled the dice')# insert in log and display.
+ message = 'You have already rolled the dice'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
continue
-
+
# The house and hotel are designed in such a way that only if you step on the tile, you can build them
- # Build a house
+ # If you build a house on a special card or a railway, it will throw an error
elif game_input.casefold() == 'h':
# Insert house logic here
- current_tile = board.BOARD_TILES[player.position]
- house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
+ current_tile = self.tiles[player.position]
+ house_cost = current_tile.house_cost
+
+ if house_cost is None:
+ print('House cannot be built on a special card or railway')
- if player.balance > house_cost:
+ elif player.balance > house_cost:
player.build_house(current_tile)
+ message = 'House built!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
else:
print('Insufficient Funds!')
+ message = 'Insufficient Funds!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
# Build a hotel
elif game_input.casefold() == 'f':
# Insert hotel logic here
- current_tile = board.BOARD_TILES[player.position]
- house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
+ current_tile = self.tiles[player.position]
+ hotel_cost = current_tile.hotel_cost
- if player.balance > house_cost:
+ if player.balance > hotel_cost:
player.build_house(current_tile)
+ message = 'Hotel built!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
else:
print('Insufficient Funds!')
+ message = 'Insufficient Funds!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
# View assets owned
elif game_input.casefold() == 'v':
if not bool(player.assets_owned):
print('No assets owned!')
+ message = 'No assets owned!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
else:
print('----------Assets Owned----------')
+ message = '----------Assets Owned----------'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
for assets in player.assets_owned:
print(f'{assets}')
+ message = '%s' % assets
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
print(end='\n\n')
# Sell property
@@ -169,26 +222,51 @@ def game_start(self):
if player.assets_owned:
[print(i, end=', ') for i in player.assets_owned]
print(end='\n\n')
- sell_property = int(input(f'Enter 0 - {len(player.assets_owned)-1}: '))
- player.sell_tile(player.assets_owned[sell_property])
+ sell_input = int(input(f'Enter 0 - {len(player.assets_owned)}: ')) - 1
+ message = f'Enter 0 - {len(player.assets_owned) - 1}'
+ # Need to do some input here
+
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+ message = '%s' % player.assets_owned[sell_input]
+ selling_property_id = self.db.select_query(self.daoConst.GET_PROPERTY_OWNED, (message, ))
+ current_tile = self.tiles[selling_property_id[0][0]]
+ sell_property = player.sell_tile(current_tile)
+ self.db.insertion_query(self.daoConst.SELL_PROPERTY, (player.room_id, player.player_id, sell_property))
print(end='\n\n')
+
else:
print('No assets owned!')
+ message = 'No assets owned!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
# End turn
elif game_input.casefold() == 'x':
if has_rolled:
turn_ended = True
print(f'{player.username}\'s turn ended!', end='\n\n')
+ message = '%s turn ended!' % player.username
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
else:
print("You need to first roll the dice!")
+ message = 'You need to first roll the dice!'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
# Incorrect input
else:
print('Error! Incorrect Input')
+ message = 'Error! Incorrect Input'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
+ # Update player details in the table at the end of every round
+ self.db.insertion_query(self.daoConst.UPDATE_EVERYTHING, (player.balance, player.position, player.game_round, player.room_id, player.player_id))
- # Game over condition
+ message = 'Round end! Player details updated'
+ self.db.insertion_query(self.daoConst.INSERT_LOG, (message, player.room_id))
+
+
+ # Game over condition
self.is_game_over = self.game_over(player)
if(self.is_game_over):
self.game_winner(self)
@@ -196,17 +274,20 @@ def game_start(self):
# Displays game stats at the end
- def getGameStats(self):
+ # Need to display what name of the player, number of wins, number of losses and
+ def game_end_player_details(self):
for player in self.player_list:
- player.display_player_details()
- print('------------------------', end='\n')
+ pass
+
+ # Display logs of the game?
#Check if 15 rounds are reached
- def game_over(self,player):
+ def game_over(self, player):
if player.game_round == 15 or player.balance <= 0:
print('Game Over!')
+ # Insert some logic and DB query that makes room inactive and updates the winner of the room
return True
-
else:
return False
+
diff --git a/service/room.py b/service/room.py
index af2d3da..9b086e6 100644
--- a/service/room.py
+++ b/service/room.py
@@ -7,10 +7,13 @@
class room:
def __init__(self) -> None:
self.dbRoom=databaseObj.Dao()
- self.daoConstRoom=DaoConstRoom.DaoConstants()
- self.roomID=1 # need to make this from website input
+ self.daoConstRoom=DaoConstRoom.DaoConstants()
+ self.roomID = 1
+ # self.roomID = room_id
+ # self.roomID=self.dbRoom.insertion_query(self.daoConstRoom.JOIN_ROOM,(room_id, 'ACTIVE')) # need to make this from website input
#insert logic to wait for players joining this
- #as a player joins insert in player table
+ #as a player joins insert in player table
+
'''
as a player joins insert into room and player table with all values;
@@ -21,6 +24,7 @@ def play(self):
usernames = self.dbRoom.select_query( self.daoConstRoom.GET_USERNAME_FROM_PLAYER, (self.roomID,))
print(usernames)
player_details=[]
+ player_property_details = []
while True:
if (len(player_details)>=4):
@@ -30,17 +34,22 @@ def play(self):
print('Waiting for players to join..........')
time.sleep(5)
player_details= self.dbRoom.select_query( self.daoConstRoom.GET_PLAYERS_IN_ROOM, (self.roomID,))
-
+
#print('Printing list:',player_details[0].printPlayer())
player_list=[]
for i in range(len(player_details)):
# Modify this insert to fetch position
- player_list.append(player.Player(room_id=player_details[i][0], player_id= player_details[i][1],username= usernames[i][0],
- money=player_details[i][2],game_round=player_details[i][5],position= player_details[i][4]))
- print('Printing list:',player_list[0].printPlayer())
- m=monopoly.monopoly_Instance(roomID=1,player_list=player_list) # need to get roomid over here from web
+ # player_property_details.append(self.dbRoom.select_query(self.daoConstRoom.GET_PROPERTY_FROM_PLAYER_OWNED,
+ # (player_details[i][0],
+ # player_details[i][1])))
+
+ # print('this do be', player_property_details)
+ player_list.append(player.Player(room_id=player_details[i][0], player_id=player_details[i][1], username=usernames[i][0],
+ money=player_details[i][2], game_round=player_details[i][5], position=player_details[i][4], ))
+ print('Printing list:', player_list[0].print_player())
+
+ m=monopoly.monopoly_Instance(roomID=1, player_list=player_list) # need to get roomid over here from web
m.game_start()
-
- m.getGameStats()
+ m.game_end_player_details()
\ No newline at end of file
diff --git a/start.py b/start.py
index 9ce8d51..39823a9 100644
--- a/start.py
+++ b/start.py
@@ -1,4 +1,7 @@
import service.room as startRoom
+from database.Dao import Dao, DaoConstants
+# new_room = Dao.insertion_query(DaoConstants.CREATE_ROOM, (1, 'ACTIVE'))
+# room = startRoom.room(new_room)
room=startRoom.room()
room.play()
diff --git a/static/script.js b/static/script.js
index 6a44471..b4815c5 100644
--- a/static/script.js
+++ b/static/script.js
@@ -9,19 +9,11 @@ document.getElementById("submit").addEventListener("click", async () => {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ move }),
- })
+ });
const result = await response.json();
- if (move === "x") {
- outputBox.value += "\n" + result.message;
- setTimeout(() => {
- outputBox.value = "";
- }, 2000); // Clear after 3 seconds
- } else {
- outputBox.value += "\n" + JSON.stringify(result);
- }
- // inputBox.value = "";
+ outputBox.value += "\n" + result.message.move;
+ move.value = "";
}
-
});
diff --git a/tls/ca-cert.pem b/tls/ca-cert.pem
new file mode 100644
index 0000000..d04d8e1
--- /dev/null
+++ b/tls/ca-cert.pem
@@ -0,0 +1,36 @@
+-----BEGIN CERTIFICATE-----
+MIIGMTCCBBmgAwIBAgIUOKAn3C0fzownq2dkGu6SZi2P7WIwDQYJKoZIhvcNAQEL
+BQAwgacxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAh2aXJnaW5pYTEQMA4GA1UEBwwH
+ZmFpcmZheDEXMBUGA1UECgwOc2VjdXJlc29mdHdhcmUxFzAVBgNVBAsMDnNlY3Vy
+ZXNvZnR3YXJlMR0wGwYDVQQDDBQqLnNlY3VyZXNvZnR3YXJlLmNvbTEiMCAGCSqG
+SIb3DQEJARYTc2VjdXJlc29mdHdhcmVAdGVzdDAeFw0yMzA0MDcwMDI3NTVaFw0y
+NDA0MDYwMDI3NTVaMIGnMQswCQYDVQQGEwJVUzERMA8GA1UECAwIdmlyZ2luaWEx
+EDAOBgNVBAcMB2ZhaXJmYXgxFzAVBgNVBAoMDnNlY3VyZXNvZnR3YXJlMRcwFQYD
+VQQLDA5z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pe749TysTTHuTUIBQKko+rFK8q8RIuavtLhn
+kjTikWHoLLD7zWeit8c2UPydDRfuMr3AMpwlhfR0qzgXqrn2phB+Elv6R5UaqNP9
+abCpyecW3BeN0PF46C8doszj7Hmt9la3P8pt2AH3EENdlhY657LCxgKVC+ugZUBZ
+rTBkGJqDcXOexHtfdtPWpdYrr6gPLcmWTiauL1j/0ddkM0a56FP/axPn+GcLvyOh
+0v5Cln1TeiuK+4ekK8O07ySCY1Vcp7G4cynSCoiVi37M7xU6HLmMznYtzXfddpBB
+hJ9f9ohtonCx4BaUER1zxfEbdhY/ZaYAsAGo7UB/GGOHLP3ndxXcy4u3R6OmcdWA
+415RozuW/Vd0ztJpfsZUMWF6tu3DV/1YdUWm45JBDFrK8X+FiEAVGxOUJQ13OQZg
+AigegZsvbnZBnECg8uxSnUpRR4w7ebm8i1riU+JCVkm3HRhu583AUaZWR+ksdcxN
+MOJ7gwkHz0Ugzj8TAh5kwWPLS0SBwAtGi2BHSQ4J36QalflTjJLrmkPM/t3oCJHS
+5K5uZan9ROlVf94UkzNPFnnqPHUN7yEL3DclP7uyPHwTaNyqCo952OMYvgv21upN
+JmvY+vI=
+-----END CERTIFICATE-----
diff --git a/tls/ca-key.pem b/tls/ca-key.pem
new file mode 100644
index 0000000..642e33e
--- /dev/null
+++ b/tls/ca-key.pem
@@ -0,0 +1,54 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIIJnDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQI6lpV7o7Go1sCAggA
+MAwGCCqGSIb3DQIJBQAwFAYIKoZIhvcNAwcECDNarEgkKn2eBIIJSI4W8dMfVFyL
+02/ZKyQyytKKxRm0QdgtzZx96nrSNLu/Hp+7cEMEun+mrugB5fJTaRGYapOqdgWd
+nC6sV8HYOZqezGhXcUdHhT3vPXfs/yBXeBT+ZEbBkUCf+GyJQvivCbF8ut/xbdbP
+8aJg3UTOwHfryrCJiL9I9m4xqHy9cxm6j6ie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Putc4+RT0TxHsYWwG8aYZ+D0MsyU7NlAsH1uq8rrCzOhsZ2AfTXGQQieF
+YwqxXsoyUZ5/Ck1ucJHf5nn6dojZd8cmKCPS7a3QBJsuTCy2/Ae1RyTBJRIV/FKV
+1u87nJVB8Pl6NEeDGRH8O1SdCtoBxUV5XSEEMmNb1NLGmaQ1Ht7wfHXw1cXizPJ9
+W7QIoxYtEXhPSqAz8HG7MrSyrHAI+KifYwX+8EjqKAWz2udhNKP6sLYZBzmdmA9t
+wGGLiSGthYuphBt3HBN+oNJP1WkMAXvacei4zcXY5afXzRX9sFpCX80bFTqFdHgo
+SIX4umtFlfwdpBV6v1x36hP9amX+V9eGfXibtwnsfP6SikPFQwtvJXUwoM3IVmEK
+gjPWlZlHDSaH7aGx+8t1mVWl8VgAO0IwnvwSdWDdHjKETyTHjMC/eO8gmjYx2Wt0
+8SLlUMrCloU4h/0HbPhSeeNGX6XAUYlULDObYdQFDEcqCbOgYQFEEalCw8/NQNyl
+mg3fWZJfTYJA9HUwfSwQ2L6/y9M0umCj9pSb/QRDvOuW7VBlsZAPUTjjbVbqPXss
+GSDd5fqxR/dHc6wVU+rvIsrwPKAaP0C9FyPMDKJpkppnImIONiyokm4g1N9TMR1e
+FHepy08Dbj+KkBh6qPdRj9oEUXlwUZ988gRBlbfM5vAGSCjtO3rZS2PTbBFnb/us
+9E3XALeyqMzmWQujPQZ/oxh2cLoHsWCvD9VOt6X+HuSxzbHvTtlHZQMj/J7eDvUW
+66mGc2rKpsTEiFIMtkpcJwy8ImheStKoGHTVvWo1MBmrB6gtoccu0dT2wFkvXIvM
+4HNHGwkzeLGuEdl2Yf+Lx2m081Jv+nhRuIwYjJVVtPo9BMTiIsWudlgFwQUngw0u
+IHLWF++4phn7yEq9jXEo5w==
+-----END ENCRYPTED PRIVATE KEY-----
diff --git a/utils/__pycache__/driver.cpython-310.pyc b/utils/__pycache__/driver.cpython-310.pyc
index c8a5cfc..be658f4 100644
Binary files a/utils/__pycache__/driver.cpython-310.pyc and b/utils/__pycache__/driver.cpython-310.pyc differ
diff --git a/utils/__pycache__/driver.cpython-39.pyc b/utils/__pycache__/driver.cpython-39.pyc
index 9ee48ac..921145e 100644
Binary files a/utils/__pycache__/driver.cpython-39.pyc and b/utils/__pycache__/driver.cpython-39.pyc differ
diff --git a/utils/__pycache__/loging.cpython-310.pyc b/utils/__pycache__/loging.cpython-310.pyc
new file mode 100644
index 0000000..4a3fbc6
Binary files /dev/null and b/utils/__pycache__/loging.cpython-310.pyc differ
diff --git a/utils/__pycache__/loging.cpython-39.pyc b/utils/__pycache__/loging.cpython-39.pyc
new file mode 100644
index 0000000..fe31f08
Binary files /dev/null and b/utils/__pycache__/loging.cpython-39.pyc differ
diff --git a/utils/driver.py b/utils/driver.py
index 6a7979f..9402b12 100644
--- a/utils/driver.py
+++ b/utils/driver.py
@@ -1,21 +1,21 @@
-import board
+import random
from models import player
import database.Dao
-players_query = 'select room_id, player_id from player where room_id = %s'
-players_params = (1,)
-
-usernames_query = 'SELECT u.username FROM user u JOIN player p ON u.user_id = p.player_id WHERE p.room_id = %s;'
-
-player_list = []
-get_players = database.db_connect
-usernames = get_players.select_query(usernames_query, players_params)
-value = get_players.select_query(players_query, players_params)
-
-
-# player_list is being populated,
-for i in range(len(value)):
- player_list.append(player.Player(value[i][0], value[i][1], usernames[i][0]))
+# players_query = 'select room_id, player_id from player where room_id = %s'
+# players_params = (1,)
+#
+# usernames_query = 'SELECT u.username FROM user u JOIN player p ON u.user_id = p.player_id WHERE p.room_id = %s;'
+#
+# player_list = []
+# get_players = database.db_connect
+# usernames = get_players.select_query(usernames_query, players_params)
+# value = get_players.select_query(players_query, players_params)
+#
+#
+# # player_list is being populated,
+# for i in range(len(value)):
+# player_list.append(player.Player(value[i][0], value[i][1], usernames[i][0]))
# In case wanna know if the players are working or not, go ahead and uncomment this
@@ -28,106 +28,106 @@
# messages = []
-def display_moves(current_player):
- # messages = []
-
- print(f'{current_player.username}\'s turn ')
- print(f'Cash - {current_player.balance}\t Rounds played - {current_player.game_round}\t Player position - {current_player.position}')
- print('----------------------------------------------------------------')
-
- for key, value in board.moves.items():
- print("{:<30}{}".format(key, value))
- print('\n')
- return '\n'.join(messages)
-
-
-def process_move(move: str) -> str:
- global is_game_over
- global messages
-
- while not is_game_over:
- for current_player in player_list:
- messages = []
- has_rolled = False
-
- if move.casefold() == 'r':
- if has_rolled:
- print('You have already rolled the dice')
- else:
- has_rolled = True
- print(f"{current_player.username} chooses {move}!")
-
- # Roll dice
- roll_value = board.dice_roll(current_player)
- current_player.player_moves(roll_value)
- # print(f'{player1.username} rolled {roll_value}')
-
- current_tile = board.BOARD_TILES[current_player.position]
-
- print(f'{current_player.username} rolled {roll_value} and lands on {current_tile}')
-
- elif move.casefold() == 'h':
-
- current_tile = board.BOARD_TILES[player1.position]
- house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
-
- if current_player.balance > house_cost:
- current_player.build_house(current_tile)
- else:
- print('Insufficient Funds!')
-
-
- # Build a hotel
- elif move.casefold() == 'f':
- # Insert hotel logic here
- current_tile = board.BOARD_TILES[current_player.position]
- house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
-
- if current_player.balance > house_cost:
- current_player.build_house(current_tile)
- else:
- print('Insufficient Funds!\n\n')
-
-
- # View assets owned
- elif move.casefold() == 'v':
- if not bool(current_player.assets_owned):
- print('No assets owned!')
-
- else:
- print('----------Assets Owned----------')
- for assets in current_player.assets_owned:
- print(f'{assets}')
- print('\n\n')
-
-
- # Sell property
- elif move.casefold() == 's':
- # Insert sell property logic here
- if current_player.assets_owned:
- [print(i) for i in current_player.assets_owned]
- print('\n\n')
- sell_property = int(input(f'Enter 0 - {len(player1.assets_owned) - 1}: '))
- current_player.sell_tile(current_player.assets_owned[sell_property])
- print('\n\n')
- else:
- print('No assets owned!\n')
-
- # End turn
- elif move.casefold() == 'x':
- if has_rolled:
- turn_ended = True
- print(f'{current_player.username}\'s turn ended!\n\n')
-
- else:
- print("You need to first roll the dice!\n\n")
-
- else:
- print("You need to first roll the dice!\n\n")
-
- is_game_over = board.game_over(current_player)
- # Append the move chosen by the player
- return '\n'.join(messages)
+# def display_moves(current_player):
+# # messages = []
+#
+# print(f'{current_player.username}\'s turn ')
+# print(f'Cash - {current_player.balance}\t Rounds played - {current_player.game_round}\t Player position - {current_player.position}')
+# print('----------------------------------------------------------------')
+#
+# for key, value in board.moves.items():
+# print("{:<30}{}".format(key, value))
+# print('\n')
+# return '\n'.join(messages)
+
+
+# def process_move(move: str) -> str:
+# global is_game_over
+# global messages
+#
+# while not is_game_over:
+# for current_player in player_list:
+# messages = []
+# has_rolled = False
+#
+# if move.casefold() == 'r':
+# if has_rolled:
+# print('You have already rolled the dice')
+# else:
+# has_rolled = True
+# print(f"{current_player.username} chooses {move}!")
+#
+# # Roll dice
+# roll_value = dice_roll(current_player)
+# current_player.player_moves(roll_value)
+# # print(f'{player1.username} rolled {roll_value}')
+#
+# current_tile = board.BOARD_TILES[current_player.position]
+#
+# print(f'{current_player.username} rolled {roll_value} and lands on {current_tile}')
+#
+# elif move.casefold() == 'h':
+#
+# current_tile = board.BOARD_TILES[player1.position]
+# house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
+#
+# if current_player.balance > house_cost:
+# current_player.build_house(current_tile)
+# else:
+# print('Insufficient Funds!')
+#
+#
+# # Build a hotel
+# elif move.casefold() == 'f':
+# # Insert hotel logic here
+# current_tile = board.BOARD_TILES[current_player.position]
+# house_cost = board.BOARD_TILES_INFO[current_tile][4][1]
+#
+# if current_player.balance > house_cost:
+# current_player.build_house(current_tile)
+# else:
+# print('Insufficient Funds!\n\n')
+#
+#
+# # View assets owned
+# elif move.casefold() == 'v':
+# if not bool(current_player.assets_owned):
+# print('No assets owned!')
+#
+# else:
+# print('----------Assets Owned----------')
+# for assets in current_player.assets_owned:
+# print(f'{assets}')
+# print('\n\n')
+#
+#
+# # Sell property
+# elif move.casefold() == 's':
+# # Insert sell property logic here
+# if current_player.assets_owned:
+# [print(i) for i in current_player.assets_owned]
+# print('\n\n')
+# sell_property = int(input(f'Enter 0 - {len(player1.assets_owned) - 1}: '))
+# current_player.sell_tile(current_player.assets_owned[sell_property])
+# print('\n\n')
+# else:
+# print('No assets owned!\n')
+#
+# # End turn
+# elif move.casefold() == 'x':
+# if has_rolled:
+# turn_ended = True
+# print(f'{current_player.username}\'s turn ended!\n\n')
+#
+# else:
+# print("You need to first roll the dice!\n\n")
+#
+# else:
+# print("You need to first roll the dice!\n\n")
+#
+# is_game_over = board.game_over(current_player)
+# # Append the move chosen by the player
+# return '\n'.join(messages)
def game_over(player):
@@ -139,3 +139,26 @@ def game_over(player):
return False
+def dice_roll(player):
+ first_dice = random.randint(1, 6)
+ second_dice = random.randint(1, 6)
+ total_dice = first_dice + second_dice
+ # if first_dice == second_dice:
+ # print(f'{player.username} rolled doubles of {first_dice}!') # Change player name
+ # print(f'{player.username} rolled {total_dice}', end='\n\n') # Change player name
+ return total_dice
+
+
+def moves_list():
+ # Display player stats(name, cash in hand, rounds played, position)
+ print('-------------Moves-------------')
+
+ print("{:<30}{}".format('Roll dice', 'r'))
+ print("{:<30}{}".format('Build a house', 'h'))
+ print("{:<30}{}".format('Build a hotel', 'f'))
+ print("{:<30}{}".format('View assets owned', 'v'))
+ print("{:<30}{}".format('Sell property', 's'))
+ print("{:<30}{}".format('End turn', 'x'), end='\n\n\n')
+
+def get_moves():
+ pass
diff --git a/utils/loging.py b/utils/loging.py
index 1f89a78..664e07b 100644
--- a/utils/loging.py
+++ b/utils/loging.py
@@ -1,50 +1,41 @@
import logging
import sqlite3
+
class log:
def __init__(self):
self.logger = logging.getLogger(__name__)
self.console_handler = logging.StreamHandler()
self.log_format = '%(asctime)s - %(levelname)s - %(message)s'
- self.formatter=logging.Formatter(self.log_format)
+ self.formatter = logging.Formatter(self.log_format)
self.console_handler.setFormatter(self.formatter)
self.logger.addHandler(self.console_handler)
-
-
-
-
-
- def log_info(self,message,inp=None):
- print('in logger info with var ',inp)
- self.console_handler.setLevel(logging.INFO)
+ def log_info(self, message, inp=None):
+ # print('in logger info with var ',inp)
+ self.console_handler.setLevel(logging.INFO)
self.logger.setLevel(logging.INFO)
- if(inp):
- self.logger.info(message,inp)
+ if (inp):
+ self.logger.info(message, inp)
else:
- self.logger.info(message)
-
-
+ self.logger.info(message)
- def log_debug(self,message,inp=None):
- self.console_handler.setLevel(logging.DEBUG)
+ def log_debug(self, message, inp=None):
+ self.console_handler.setLevel(logging.DEBUG)
self.logger.setLevel(logging.DEBUG)
logging.Formatter(self.log_format)
self.logger.addHandler(self.console_handler)
- if(inp):
- self.logger.debug(message,inp)
+ if (inp):
+ self.logger.debug(message, inp)
else:
- self.logger.debug(message)
-
+ self.logger.debug(message)
- def log_error(self,message,inp=None):
- self.console_handler.setLevel(logging.ERROR)
+ def log_error(self, message, inp=None):
+ self.console_handler.setLevel(logging.ERROR)
self.logger.setLevel(logging.ERROR)
logging.Formatter(self.log_format)
- if(inp):
- self.logger.error(message,inp)
+ if (inp):
+ self.logger.error(message, inp)
else:
- self.logger.error(message)
-
-
+ self.logger.error(message)
diff --git a/websocket_test.py b/websocket_test.py
new file mode 100644
index 0000000..e123368
--- /dev/null
+++ b/websocket_test.py
@@ -0,0 +1,71 @@
+from fastapi import FastAPI, WebSocket
+from fastapi.responses import HTMLResponse
+from typing import List
+
+app = FastAPI()
+
+# List to store active WebSocket connections
+active_connections: List[WebSocket] = []
+
+html = """
+
+
+
+ Chat
+
+
+ WebSocket Chat
+
+
+
+
+
+"""
+
+
+@app.get("/")
+async def get():
+ return HTMLResponse(html)
+
+
+@app.websocket("/ws")
+async def websocket_endpoint(websocket: WebSocket):
+ await websocket.accept()
+ active_connections.append(websocket) # Add the new connection to the list
+
+ try:
+ while True:
+ data = await websocket.receive_text()
+ # cash and all
+ # broadcast
+ # do your input
+ # Everything goes in here
+ # a = game_start(data)
+ await broadcast_message(data) # Broadcast the message to all clients
+ except Exception as e:
+ active_connections.remove(websocket) # Remove the disconnected client
+ print('Error is ', e)
+
+
+async def broadcast_message(message: str):
+ for connection in active_connections:
+ await connection.send_text(f"Message text was: {message}")