Skip to content

Commit e5efee2

Browse files
committed
Update code formatting and fix bug in data validation
1 parent 5538c75 commit e5efee2

File tree

4 files changed

+271
-0
lines changed

4 files changed

+271
-0
lines changed

python-ws-server/player_analysis.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import json
2+
import os
3+
import glob
4+
5+
# Load the JSON data from the file
6+
def load_data(file_path):
7+
data = []
8+
with open(file_path, 'r') as file:
9+
for line in file:
10+
try:
11+
data.append(json.loads(line))
12+
except json.JSONDecodeError as e:
13+
print(f"Error decoding JSON from line: {line}\nError: {e}")
14+
return data
15+
16+
# Collect unique player names from the data
17+
def get_unique_player_names(data):
18+
player_names = set()
19+
for event in data:
20+
player_name = event.get('body', {}).get('player', {}).get('name')
21+
if player_name:
22+
player_names.add(player_name)
23+
return list(player_names)
24+
25+
# Filter events by player name
26+
def filter_events_by_player(data, player_name):
27+
return [event for event in data if event.get('body', {}).get('player', {}).get('name') == player_name]
28+
29+
# Analyze player data and generate a report
30+
def analyze_player_data(events):
31+
distance_traveled = 0
32+
blocks_broken = 0
33+
blocks_placed = 0
34+
35+
for event in events:
36+
if event['header']['eventName'] == 'PlayerTravelled':
37+
distance_traveled += event['body']['metersTravelled']
38+
elif event['header']['eventName'] == 'BlockBroken':
39+
blocks_broken += 1
40+
elif event['header']['eventName'] == 'BlockPlaced':
41+
blocks_placed += 1
42+
43+
report = f"Player Analysis Report:\n" \
44+
f"Total Distance Traveled: {distance_traveled} meters\n" \
45+
f"Blocks Broken: {blocks_broken}\n" \
46+
f"Blocks Placed: {blocks_placed}\n"
47+
48+
return report
49+
50+
def main():
51+
file_path = 'C:\\Users\\juedwards\\github_python'
52+
json_files = glob.glob(os.path.join(file_path, '*.json'))
53+
print("Available JSON files:")
54+
for idx, file in enumerate(json_files, start=1):
55+
print(f"{idx}. {os.path.basename(file)}")
56+
57+
file_choice = int(input("Enter the number of the JSON file you'd like to analyze: ")) - 1
58+
if file_choice < 0 or file_choice >= len(json_files):
59+
print("Invalid selection.")
60+
return
61+
62+
selected_file = json_files[file_choice]
63+
data = load_data(selected_file)
64+
65+
player_names = get_unique_player_names(data)
66+
if not player_names:
67+
print("No player data found in the selected file.")
68+
return
69+
70+
player_reports = []
71+
for player_name in player_names:
72+
player_events = filter_events_by_player(data, player_name)
73+
report = analyze_player_data(player_events)
74+
player_reports.append((player_name, report))
75+
76+
print("Player Analysis Summary:")
77+
print(f"{'Player Name':<20}{'Distance Traveled':<20}{'Blocks Broken':<15}{'Blocks Placed':<15}")
78+
for name, report in player_reports:
79+
distance_traveled, blocks_broken, blocks_placed = parse_report(report)
80+
print(f"{name:<20}{distance_traveled:<20}{blocks_broken:<15}{blocks_placed:<15}")
81+
82+
def parse_report(report):
83+
lines = report.split('\n')
84+
distance_traveled = float(lines[1].split(': ')[1].split(' ')[0])
85+
blocks_broken = int(lines[2].split(': ')[1])
86+
blocks_placed = int(lines[3].split(': ')[1])
87+
return distance_traveled, blocks_broken, blocks_placed
88+
89+
if __name__ == "__main__":
90+
main()

python-ws-server/player_analysis2.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import json
2+
import matplotlib.pyplot as plt
3+
from mpl_toolkits.mplot3d import Axes3D
4+
5+
# Load and parse the JSON data
6+
data = []
7+
with open('C:\\Users\\juedwards\\github_python\\2102240011.json', 'r') as file:
8+
for line in file:
9+
data.append(json.loads(line))
10+
11+
# Initialize a dictionary to store coordinates by player
12+
player_paths = {}
13+
14+
# Iterate over the data to fill player_paths
15+
for entry in data:
16+
player_id = entry['body']['player']['name'] # Adjust based on actual data structure
17+
x = entry['body']['player']['position']['x']
18+
y = entry['body']['player']['position']['y'] # Ensure 'y' coordinate is being accessed correctly
19+
z = entry['body']['player']['position']['z']
20+
if player_id not in player_paths:
21+
player_paths[player_id] = {'x': [], 'y': [], 'z': []}
22+
player_paths[player_id]['x'].append(x)
23+
player_paths[player_id]['y'].append(y)
24+
player_paths[player_id]['z'].append(z)
25+
26+
# Plotting
27+
fig = plt.figure(figsize=(10, 8))
28+
ax = fig.add_subplot(111, projection='3d')
29+
30+
for player_id, coords in player_paths.items():
31+
ax.plot(coords['x'], coords['z'], coords['y'], marker='o', linestyle='-', label=player_id) # Note the order of coordinates
32+
33+
ax.set_title('Player Journeys in 3D Space')
34+
ax.set_xlabel('X Coordinate')
35+
ax.set_ylabel('Z Coordinate')
36+
ax.set_zlabel('Y Coordinate') # Y coordinate is along the vertical axis in this plot
37+
ax.legend()
38+
plt.show()

python-ws-server/server5.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import asyncio
2+
import websockets
3+
import json
4+
from uuid import uuid4
5+
from datetime import datetime
6+
7+
# Events to subscribe to, based on the JSON events gist provided
8+
INTERESTING_EVENTS = [
9+
"PlayerMessage",
10+
"PlayerTravelled",
11+
"PlayerTransform",
12+
"PlayerTeleported",
13+
"BlockBroken",
14+
"BlockPlaced",
15+
"ItemAcquired",
16+
"ItemCrafted",
17+
"ItemDestroyed",
18+
"ItemDropped",
19+
"ItemEnchanted",
20+
"ItemSmelted",
21+
"ItemUsed"
22+
# Add more event names as needed based on your interest
23+
]
24+
25+
# Generate a file name based on the current date and time
26+
session_start_time = datetime.now().strftime("%d%m%y%H%M")
27+
log_file_name = f"{session_start_time}.json"
28+
29+
async def log_event(json_message):
30+
try:
31+
message = json.loads(json_message) if not isinstance(json_message, dict) else json_message
32+
except TypeError as e:
33+
print(f"Error processing message: {e}")
34+
return
35+
36+
# Save the event to the session log file
37+
with open(log_file_name, "a") as log_file:
38+
log_file.write(json.dumps(message) + "\n")
39+
40+
async def subscribe_to_events(websocket):
41+
for event_name in INTERESTING_EVENTS:
42+
await websocket.send(json.dumps({
43+
"header": {
44+
"version": 1,
45+
"requestId": str(uuid4()),
46+
"messageType": "commandRequest",
47+
"messagePurpose": "subscribe"
48+
},
49+
"body": {
50+
"eventName": event_name
51+
},
52+
}))
53+
54+
async def mineproxy(websocket, path):
55+
print('Connected to Minecraft')
56+
await subscribe_to_events(websocket)
57+
58+
try:
59+
# Listen for messages from Minecraft
60+
async for msg in websocket:
61+
await log_event(msg)
62+
except websockets.exceptions.ConnectionClosedError:
63+
print('Disconnected from Minecraft')
64+
65+
async def start_server():
66+
print(f'Server starting, logging to {log_file_name}...')
67+
server = await websockets.serve(mineproxy, "localhost", 3000)
68+
print('Server started. On Minecraft, type /connect localhost:3000')
69+
await server.wait_closed()
70+
71+
asyncio.run(start_server())

python-ws-server/super_analysis.py

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import json
2+
import os
3+
import glob
4+
import matplotlib.pyplot as plt
5+
from mpl_toolkits.mplot3d import Axes3D
6+
7+
# Load the JSON data from the file
8+
def load_data(file_path):
9+
data = []
10+
with open(file_path, 'r') as file:
11+
for line in file:
12+
try:
13+
data.append(json.loads(line))
14+
except json.JSONDecodeError as e:
15+
print(f"Error decoding JSON from line: {line}\nError: {e}")
16+
return data
17+
18+
# Plot the 3D chart of player journeys
19+
def plot_player_journeys(data):
20+
player_paths = {}
21+
for entry in data:
22+
player_id = entry['body']['player']['name']
23+
x = entry['body']['player']['position']['x']
24+
y = entry['body']['player']['position']['y']
25+
z = entry['body']['player']['position']['z']
26+
if player_id not in player_paths:
27+
player_paths[player_id] = {'x': [], 'y': [], 'z': []}
28+
player_paths[player_id]['x'].append(x)
29+
player_paths[player_id]['y'].append(y)
30+
player_paths[player_id]['z'].append(z)
31+
32+
fig = plt.figure(figsize=(10, 8))
33+
ax = fig.add_subplot(111, projection='3d')
34+
for player_id, coords in player_paths.items():
35+
ax.plot(coords['x'], coords['z'], coords['y'], marker='o', linestyle='-', label=player_id)
36+
37+
ax.set_title('Player Journeys in 3D Space')
38+
ax.set_xlabel('X Coordinate')
39+
ax.set_ylabel('Z Coordinate')
40+
ax.set_zlabel('Y Coordinate')
41+
ax.legend()
42+
43+
# Generate and display the player analysis report
44+
def display_player_analysis(data):
45+
player_reports = {}
46+
for event in data:
47+
player_name = event.get('body', {}).get('player', {}).get('name')
48+
if player_name:
49+
if player_name not in player_reports:
50+
player_reports[player_name] = {'distance_traveled': 0, 'blocks_broken': 0, 'blocks_placed': 0}
51+
if event['header']['eventName'] == 'PlayerTravelled':
52+
player_reports[player_name]['distance_traveled'] += event['body']['metersTravelled']
53+
elif event['header']['eventName'] == 'BlockBroken':
54+
player_reports[player_name]['blocks_broken'] += 1
55+
elif event['header']['eventName'] == 'BlockPlaced':
56+
player_reports[player_name]['blocks_placed'] += 1
57+
58+
print(f"{'Player Name':<20}{'Distance Traveled':<20}{'Blocks Broken':<15}{'Blocks Placed':<15}")
59+
for name, report in player_reports.items():
60+
print(f"{name:<20}{report['distance_traveled']:<20}{report['blocks_broken']:<15}{report['blocks_placed']:<15}")
61+
62+
def main():
63+
file_path = 'C:\\Users\\juedwards\\github_python\\2102240119.json'
64+
data = load_data(file_path)
65+
display_player_analysis(data) # Display the player analysis report in the console
66+
plot_player_journeys(data)
67+
plt.show() # Show the 3D plot
68+
69+
70+
71+
if __name__ == "__main__":
72+
main()

0 commit comments

Comments
 (0)