-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminalclient.py
More file actions
146 lines (113 loc) · 4.05 KB
/
terminalclient.py
File metadata and controls
146 lines (113 loc) · 4.05 KB
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
import socket
import json #convert python dictionaries into JSON text
import threading
# terminal based client
def send_message(sock, data):
msg = json.dumps(data) + "\n"
sock.sendall(msg.encode()) #turn string into bytes adn send whole message thru socket
def handle_message(msg): #after you receive message from server
mtype = msg.get("type")
if mtype == "username_ok":
print("Username accepted")
elif mtype == "username_taken":
print("Username already taken")
elif mtype == "player_list":
print("Players online:", msg["players"])
elif mtype == "challenged":
print("You were challenged by", msg["by"])
elif mtype == "game_start":
print("Game started! You are player", msg["player_id"])
elif mtype == "game_state":
print("Game update")
print("Health:", msg["health"])
print("Time left:", msg["time_left"])
elif mtype == "game_over":
print("Game over")
print("Winner:", msg["winner"])
print("Final health:", msg["health"])
elif mtype == "chat":
print(f"{msg['from']}: {msg['message']}")
elif mtype == "spectate_ok":
print("Spectate mode enabled")
elif mtype == "error":
print("Error:", msg["message"])
else:
print("Unknown message:", msg)
def receive_messages(sock): #keeps listening to server forever
buffer = ""
while True: #keep listening until connecyion closes
try:
data = sock.recv(4096).decode() #reads up to 4096 bytes from socket and turns them to text
if not data: #no data recieved
print("Disconnected from server.")
break #server probably closed connection
buffer += data
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
if line.strip() == "":
continue
msg = json.loads(line)
handle_message(msg)
except:
print("Connection closed.")
break
def command_loop(sock): #to type commands in termianl
while True:
command = input("> ").strip()
if command.lower() == "quit":
print("Closing client...") #close socket and stop
sock.close()
break
elif command.startswith("challenge "):
target = command[len("challenge "):].strip()
send_message(sock, {
"type": "challenge",
"target": target
})
elif command.startswith("accept "):
target = command[len("accept "):].strip()
send_message(sock, {
"type": "accept",
"target": target
})
elif command.startswith("move "):
direction = command[len("move "):].strip().upper()
send_message(sock, {
"type": "input",
"direction": direction
})
elif command.startswith("chat "):
text = command[len("chat "):].strip()
send_message(sock, {
"type": "chat",
"message": text
})
elif command == "spectate":
send_message(sock, {
"type": "spectate"
})
else:
print("Commands:")
print(" challenge <username>")
print(" accept <username>")
print(" move <UP/DOWN/LEFT/RIGHT>")
print(" chat <message>")
print(" spectate")
print(" quit")
def main():
host = input("Enter server IP: ")
port = int(input("Enter port: "))
username = input("Enter username: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
join_msg = {
"type": "join",
"username": username
}
send_message(sock, join_msg)
receiver_thread = threading.Thread(target=receive_messages, args=(sock,), daemon=True)
receiver_thread.start()
print("Type commands after joining.")
command_loop(sock)
if __name__ == "__main__":
main()