forked from ufosc/TERMINALMONOPOLY
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules.py
294 lines (245 loc) · 12.3 KB
/
modules.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import screenspace as ss
import style as s
from modules_directory.fishing import fishing_game
from modules_directory.tictactoe import destruct_board, construct_board
from socket import socket as Socket
import networking as net
import keyboard
import time
calculator_history_queue = []
calculator_history_current_capacity = 15
def calculator(active_terminal) -> str:
# Helper function that contructs terminal printing.
def calculator_terminal_response(footer_option: int) -> str:
calculator_header = "\nCALCULATOR TERMINAL\nHistory:\n"
footer_options = ["Awaiting an equation...\nPress 'e' to exit the calculator terminal.",
s.COLORS.BLUE+"Type 'calc' to begin the calculator!",
s.COLORS.RED+"Equation either malformed or undefined! Try again!\nPress 'e' to exit the calculator terminal"+s.COLORS.RESET]
response = calculator_header
for i in range(len(calculator_history_queue)-1, -1, -1):
response += calculator_history_queue[i][0]
response += '\n' + footer_options[footer_option]
return response
#Helper function to update calculator history
def update_history(equation: str) -> None:
global calculator_history_current_capacity
numLines = (len(equation)//75) + 1
while(numLines > calculator_history_current_capacity):
calculator_history_current_capacity += calculator_history_queue[0][1]
calculator_history_queue.pop(0)
calculator_history_current_capacity -= numLines
calculator_history_queue.append((equation, numLines))
#Uses recursion to calculate.
def calculate(equation: str) -> float:
for i in range(0, len(equation)-1):
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):
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] == '*'):
eqLeft = equation[:i]
eqRight = equation[(i+1):]
return calculate(eqLeft) * calculate(eqRight)
for i in range(0, len(equation)-1):
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] == '%'):
eqLeft = equation[:i]
eqRight = equation[(i+1):]
return calculate(eqLeft)%calculate(eqRight)
for i in range(0, len(equation)-1):
if(equation[i] == '^'):
eqLeft = equation[:i]
eqRight = equation[(i+1):]
return calculate(eqLeft) ** calculate(eqRight)
return float(equation)
# Initial comment in active terminal
ss.update_quadrant(active_terminal, calculator_terminal_response(0), padding=True)
# All other work is done on the work line (bottom of the screen)
while True:
response = '\nCALCULATOR TERMINAL\n'
digit_result = 0
print("\r", end='')
equation = input(s.COLORS.GREEN)
print(s.COLORS.RESET, end="")
if(equation == "e"):
ss.update_quadrant(active_terminal, calculator_terminal_response(1), padding=True)
break
#Trims unnecessary spaces and pads operators with spaces
equation = equation.replace(" ", "")
for op in ['+', '-', '*', '/', '%', '^']:
equation = equation.replace(op, " " + op + " ")
#Removes spaces from negative number
if(len(equation) > 1 and equation[1] == '-'):
equation = "-" + equation[3:]
try:
digit_result = calculate(equation)
responseEQ = f'{equation} = {digit_result}'
#There are 75 columns for each terminal, making any string longer than 75 characters overflow.
numOverflowingChar = len(responseEQ) - 75
lineNumber = 0
wrappedResponse = ""
while(numOverflowingChar > 0):
wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1))] + '\n'
lineNumber = lineNumber + 1
numOverflowingChar = numOverflowingChar - 75
wrappedResponse += responseEQ[(75*lineNumber):(75*(lineNumber + 1)) + numOverflowingChar] + '\n'
#response += wrappedResponse
player_equation = wrappedResponse
print(s.COLORS.RESET, end='')
update_history(player_equation)
ss.update_quadrant(active_terminal, calculator_terminal_response(0))
except:
ss.update_quadrant(active_terminal, calculator_terminal_response(2), padding=True)
def list_properties() -> str:
"""
Lists all properties on the board by calling the property list stored in ascii.txt.
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'
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'
return ret_val
def trade():
pass
def mortgage():
pass
def roll():
pass
def gamble():
pass
def attack():
pass
def stocks():
pass
def ttt_handler(server: Socket, active_terminal: int):
net.send_message(server, 'ttt,getgamestate')
time.sleep(0.1)
game_data = net.receive_message(server)
game_id = None
def get_printable_board(upper_text: str, board_data: str, lower_text) -> str:
return f"{upper_text}\n{board_data}\n{lower_text}\nUse WASD to move, Enter to select, Esc to cancel."
if 'create a new' in game_data:
ss.update_quadrant(active_terminal, game_data, padding=True)
game_id = ss.get_valid_int(prompt='Enter the game id: ', min_val=-1, max_val=0)
if game_id == -1: # If creating a new game, ask who else is playing.
while True:
ss.update_quadrant(active_terminal, "1: Player 1\n2: Player 2\n3: Player 3\n4: Player 4", padding=True) # @ TODO: This is hardcoded for now, but should be dynamic
opponent = ss.get_valid_int(prompt=f"Enter the opponent's ID (1-4), not including your ID): ",
min_val=1, max_val=4)-1 # -1 for zero-indexing
net.send_message(server, f'ttt,joingame,{game_id},{opponent}')
ss.update_quadrant(active_terminal, "Attempting to join game...", padding=True)
game_data = net.receive_message(server)
if 'select a game' in game_data or (('X' in game_data and 'O' in game_data and (not '▒' in game_data)) or '▒' in game_data):
break
else:
ss.update_quadrant(active_terminal, game_data + "\nEnter to continue...", padding=True)
input()
else:
ss.update_quadrant(active_terminal, "Not creating a new game.", padding=True)
if 'select a game' in game_data:
ss.update_quadrant(active_terminal, game_data, padding=True)
game_id = ss.get_valid_int(prompt='Enter the game id: ', min_val=-1, max_val=10) # 10 is incorrect! temp for now TODO
# Send the server the game id to join. Should be validated on server side.
net.send_message(server, f'ttt,joingame,{game_id}')
# Wait for server to send back the new board
game_data = net.receive_message(server)
ss.update_quadrant(active_terminal, game_data, padding=True)
if ('X' in game_data and 'O' in game_data and (not '▒' in game_data)) or '▒' in game_data: # If the game data sent back is a board, then we can play the game
# TODO check this is going to work with player name's that have 'X' or 'O' in them, or hell, with the '▒' character
simple_board = destruct_board(game_data)
original_board = destruct_board(game_data)
x,y = 0,0
b = construct_board(simple_board)
ss.update_quadrant(active_terminal, get_printable_board("New board:", b, f"Coordinates:\n({x},{y})"))
# Only hook the keyboard after you are definitely IN a game.
ss.indicate_keyboard_hook(active_terminal) # update terminal border to show keyboard is hooked
while True:
if keyboard.read_event().event_type == keyboard.KEY_DOWN:
simple_board[y][x] = s.COLORS.RESET + original_board[y][x]
b = construct_board(simple_board)
ss.update_quadrant(active_terminal, get_printable_board("New board:", b, f"Coordinates:\n({x},{y})"))
if keyboard.is_pressed('w'):
y = max(0, min(y-1, 2))
if keyboard.is_pressed('a'):
x = max(0, min(x-1, 2))
if keyboard.is_pressed('s'):
y = max(0, min(y+1, 2))
if keyboard.is_pressed('d'):
x = max(0, min(x+1, 2))
simple_board[y][x] = s.COLORS.backYELLOW + original_board[y][x] + s.COLORS.RESET
time.sleep(0.05)
b = construct_board(simple_board)
ss.update_quadrant(active_terminal, get_printable_board("New board:", b, f"Coordinates:\n({x},{y})"))
if keyboard.is_pressed('enter'):
# Send move to server
if '▒' in simple_board[y][x]:
# At this point, the client can be sure that they have the
# correct game ID and that the move is valid. Thus, we add
# the game ID to the move string.
net.send_message(server, f'ttt,move,{game_id},{x}.{y}')
# receive new board (for display) from server
ss.update_quadrant(active_terminal, "Updated board:\n" + net.receive_message(server), padding=True)
ss.update_terminal(active_terminal, active_terminal) # reset terminal to normal
keyboard.unhook_all()
break
else:
ss.update_quadrant(active_terminal, get_printable_board("New board:", b, f"Coordinates:\n({x},{y})\nInvalid move. Try again."))
if keyboard.is_pressed('esc'):
ss.update_terminal(active_terminal, active_terminal) # reset terminal to normal
keyboard.unhook_all()
break
def battleship(server: Socket, gamestate: str) -> str:
net.send_message(server, 'battleship')
fishing_game_obj = fishing_game() # fishing is played LOCALLY, not over the network
def fishing(gamestate: str) -> tuple[str, str]:
"""
Fishing module handler for player.py. Returns tuple of [visual data, gamestate] both as strings.
"""
stdIn = ''
match gamestate:
case 'start':
return fishing_game_obj.start(), 'playing'
case 'playing':
stdIn = fishing_game_obj.get_input()
if stdIn == 'e':
return '', 'e'
return fishing_game_obj.results(), 'e'
case 'e':
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)
return result
def make_board(board_pieces) -> list[str]:
board = [''] * 35
# Hard coded for board printing specifically
for i in range(35):
for j in range(80):
if board_pieces[i*80+j] != '\n':
board[i] += (board_pieces[i*80+j])
return board