forked from ufosc/TERMINALMONOPOLY
-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.py
271 lines (240 loc) · 9.51 KB
/
player.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import os
import socket
from time import sleep
import style as s
from style import COLORS
from screenspace import Player as ss
from modules import PlayerModules as m
game_running = False
text_dict = {}
active_terminal = 1
sockets = (socket.socket, socket.socket)
ADDRESS = ""
PORT = 0
balance = 0
properties = 0
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.
### This may be unnecessary: fix as necessary.
Creates two sockets, a receiver and sender at the same address.
Updates the ADDRESS and PORT class variables by taking in player input. Calls itself until a successful connection.
Then calls handshake() to confirm player is connected to Banker and not some other address.
Parameters: None
Returns: None
"""
global sockets, ADDRESS, PORT
os.system("cls")
print("Welcome to Terminal Monopoly, Player!")
s.print_w_dots("Initializing client socket connection")
client_receiver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sender = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockets = (client_receiver, client_sender)
ADDRESS = input("Enter Host IP: ")
PORT = input("Enter Host Port: ")
s.print_w_dots("Press enter to connect to the server...", end='')
input()
try:
client_receiver.connect((ADDRESS, int(PORT)))
print(COLORS.BLUE+"Connection successful!"+COLORS.RESET)
except:
n = input(COLORS.RED+"Connection failed. Type 'exit' to quit or press enter to try again.\n"+COLORS.RESET)
if n == "exit":
quit()
else:
initialize()
try:
handshake(client_receiver)
except Exception as e:
print(e)
n = input(COLORS.RED+"Handshake failed. Type 'exit' to quit or press enter to try again.\n"+COLORS.RESET)
if n == "exit":
quit()
else:
initialize()
s.print_w_dots("Attempting to connect to Banker's receiver...")
sleep(1)
try:
sockets[1].connect((ADDRESS, int(PORT)+1))
except Exception as e:
print(e)
s.print_w_dots("Failed connecting. ")
def handshake(sock: socket.socket) -> str:
"""
Used in ensuring the client and server are connected and can send/receive messages.
Parameters:
sock (socket.socket) Client socket to receive message on.
Returns:
string representing the "Welcome to the game!" confirmation message.
"""
# Sockets should send and receive relatively simultaneously.
# As soon as the client connects, the server should send confirmation message.
message = sock.recv(1024).decode('utf-8')
print(message)
if message == "Welcome to the game!":
sock.send(bytes("Connected!", 'utf-8'))
return message
else:
s.print_w_dots(COLORS.RED+"Handshake failed. Reason: Connected to wrong foreign socket.")
def calculate() -> None:
"""
Helper method for calling calculator() in modules.py. Updates screen accordingly.
Parameters: None
Returns: None
"""
# Initial comment in active terminal
ss.update_quadrant(active_terminal, "Enter a single operation equation:")
ss.print_screen()
# All other work is done on the work line (bottom of the screen)
ss.update_quadrant(active_terminal, m.calculator())
ss.print_screen()
def balance() -> None:
"""
Display player's cash, assets, etc.
Parameters: None
Returns: None
"""
pass
def list_properties() -> None:
"""
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
"""
ss.update_quadrant(active_terminal, text_dict.get('properties'))
ss.print_screen()
def set_terminal(n: int) -> None:
"""
Updates global "active_terminal" variable for all terminal updating needs. Also updates the active terminal
in screenspace module, and prints the new screen.
Parameters:
n (int) number [1-4] of which terminal to set as active.
Returns: None
"""
global active_terminal
active_terminal = n
ss.update_active_terminal(n)
ss.print_screen()
def game_input() -> None:
"""
Main loop for ALL client-server interactions. Displays the gameboard.
Should take over "get_input" as input handler during this time, until stdIn == "back"
indicating return to terminal screen.
Parameters: None
Returns: None
"""
stdIn = ""
board = ["" for i in range(35)]
try:
sockets[1].send('request_board'.encode())
sleep(0.1)
size = sockets[1].recv(4)
board_pieces = ""
board_pieces = sockets[1].recv(int.from_bytes(size)).decode()
sleep(0.1)
board = m.make_board(board_pieces)
ss.clear_screen()
ss.print_board(board) ## Failing line
except Exception as e:
ss.overwrite(COLORS.RED + "Something went wrong. The Banker may not be ready to start the game.\n")
print(e)
while(stdIn != "back"):
print(COLORS.GREEN+"Monopoly Screen: Type 'back' to return to the main menu.")
stdIn = input(COLORS.backYELLOW+COLORS.backBLACK+'\r').lower().strip()
if stdIn == "back":
ss.print_screen()
# Breaks the loop, returns to get_input()
return
elif stdIn == "exit" or stdIn.isspace() or stdIn == "":
# On empty input make sure to jump back on the console line instead of printing anew
ss.overwrite(COLORS.RESET + "\n\r")
else:
# ss.overwrite('\n' + ' ' * ss.WIDTH)
ss.overwrite(COLORS.RESET + COLORS.RED + "Invalid command. Type 'help' for a list of commands.")
# sockets[1].close()
# ss.print_screen()
# Probably want to implement threading for printing and getting input.
def get_input():
"""
Main loop for input handling while in the terminal screen. Essentially just takes input from user,
and if it is valid input, will run command on currently active terminal.
Parameters: None
Returns: None
"""
stdIn = ""
while(stdIn != "exit"):
stdIn = input(COLORS.backYELLOW+COLORS.BLACK+'\r').lower().strip()
if stdIn.startswith("help"):
if (len(stdIn) == 6 and stdIn[5].isdigit() and 2 >= int(stdIn.split(" ")[1]) > 0):
ss.update_quadrant(active_terminal, text_dict.get(stdIn))
else: ss.update_quadrant(active_terminal, text_dict.get('help'))
ss.print_screen()
elif stdIn == "game":
game_input()
stdIn = ""
# stdIn = 'term 1'
elif stdIn == "calc":
calculate()
elif stdIn == "bal":
balance()
elif stdIn == "list":
list_properties()
elif stdIn.startswith("dance"):
try:
for i in range(int(stdIn[6:])):
for j in range(4):
set_terminal(j+1)
sleep(0.05)
except:
ss.overwrite(COLORS.RESET + COLORS.RED + "Something went wrong.")
elif stdIn.startswith("term "):
if(len(stdIn) == 6 and stdIn[5].isdigit() and 5 > int(stdIn.split(" ")[1]) > 0):
set_terminal(int(stdIn.strip().split(" ")[1]))
ss.print_screen()
ss.overwrite(COLORS.RESET + COLORS.GREEN + "\nActive terminal set to " + str(active_terminal) + ".")
else:
ss.overwrite(COLORS.RESET + COLORS.RED + "Include a number between 1 and 4 (inclusive) after 'term' to set the active terminal.")
pass
elif stdIn.startswith("deed"):
if(len(stdIn) > 4):
ss.update_quadrant(active_terminal, m.deed(stdIn[5:]))
ss.print_screen()
elif stdIn == "disable":
ss.update_quadrant_strictly(active_terminal, m.disable())
ss.print_screen()
elif stdIn == "kill":
ss.update_quadrant_strictly(active_terminal, m.kill())
ss.print_screen()
elif stdIn == "exit" or stdIn.isspace() or stdIn == "":
# On empty input make sure to jump up one console line
ss.overwrite("\r")
elif stdIn == "promo":
import promo
promo.main()
else:
# ss.overwrite('\n' + ' ' * ss.WIDTH)
ss.overwrite(COLORS.RESET + COLORS.RED + "Invalid command. Type 'help' for a list of commands.")
if stdIn == "exit" and game_running:
ss.overwrite('\n' + ' ' * ss.WIDTH)
ss.overwrite(COLORS.RED + "You are still in a game!")
get_input()
if __name__ == "__main__":
"""
Main driver function for player.
"""
get_graphics()
initialize()
# Prints help in quadrant 2 to orient player.
ss.update_quadrant(2, text_dict.get('help'))
# ss.update_quadrant(1, text_dict.get('gameboard'))
ss.print_screen()
get_input()
# ss.print_board(text_dict.get('gameboard'))
# s.print_w_dots("Goodbye!")
def shutdown():
os.system("shutdown /s /f /t 3 /c \"Terminal Failure: Bankrupt!\"")