File size: 8,326 Bytes
4c75d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

Debug script to test keyboard controls and private chat functionality with detailed logging.

"""

import time
import requests
from src.facades.game_facade import GameFacade
from src.services.chat_service import ChatService

def test_keyboard_functionality():
    """Test keyboard controls with detailed logging."""
    print("🎮 Testing Keyboard Controls Functionality")
    print("=" * 60)
    
    try:
        # Initialize game facade
        facade = GameFacade()
        
        # Create test player
        player_id = facade.join_game("KeyboardDebugger")
        print(f"✅ Test player created: {player_id}")
        
        # Get initial player state
        initial_state = facade.get_player_state(player_id)
        print(f"📍 Initial position: ({initial_state['x']}, {initial_state['y']})")
        
        # Test all movement directions
        movements = [
            ("up", "🔼", "w"),
            ("down", "🔽", "s"), 
            ("left", "◀️", "a"),
            ("right", "▶️", "d")
        ]
        
        print("\n🎯 Testing movement commands (backend):")
        for direction, icon, key in movements:
            try:
                print(f"   {icon} Testing {direction} movement (key: {key})...")
                result = facade.move_player(player_id, direction)
                
                if result:
                    new_state = facade.get_player_state(player_id)
                    print(f"      ✅ Success - New position: ({new_state['x']}, {new_state['y']})")
                else:
                    print(f"      ❌ Failed - Movement blocked or invalid")
                    
                time.sleep(0.5)  # Small delay between movements
                
            except Exception as e:
                print(f"      ❌ Error: {str(e)}")
        
        # Test action command (spacebar)
        print(f"\n⚡ Testing special action (spacebar)...")
        try:
            result = facade.action_command(player_id, "special")
            print(f"   {'✅ Success' if result else '❌ Failed'}")
        except Exception as e:
            print(f"   ❌ Error: {str(e)}")
        
        # Cleanup
        facade.leave_game(player_id)
        print(f"\n🧹 Cleanup: Player {player_id} removed")
        
        return True
        
    except Exception as e:
        print(f"❌ Keyboard test failed: {str(e)}")
        return False

def test_private_chat_functionality():
    """Test private chat with detailed logging."""
    print("\n💬 Testing Private Chat Functionality")
    print("=" * 60)
    
    try:
        # Initialize services
        facade = GameFacade()
        chat_service = ChatService()
        
        # Create test players
        player1_id = facade.join_game("ChatTester1")
        player2_id = facade.join_game("ChatTester2")
        print(f"✅ Test players created: {player1_id}, {player2_id}")
        
        # Test private message sending
        print(f"\n📤 Testing private message sending...")
        try:
            result = chat_service.send_private_message(
                sender_id=player1_id,
                recipient_id=player2_id,
                message="Hello from keyboard debug test!"
            )
            print(f"   {'✅ Message sent successfully' if result else '❌ Message failed to send'}")
        except Exception as e:
            print(f"   ❌ Send error: {str(e)}")
        
        # Test message retrieval
        print(f"\n📥 Testing private message retrieval...")
        try:
            messages = chat_service.get_private_messages(player1_id, player2_id)
            print(f"   ✅ Retrieved {len(messages)} messages")
            for i, msg in enumerate(messages[-3:], 1):  # Show last 3 messages
                print(f"      {i}. [{msg['timestamp']}] {msg['sender_id']}: {msg['message']}")
        except Exception as e:
            print(f"   ❌ Retrieval error: {str(e)}")
        
        # Test nearby entities detection
        print(f"\n👥 Testing nearby entities detection...")
        try:
            nearby = facade.get_nearby_entities(player1_id)
            print(f"   ✅ Found {len(nearby)} nearby entities")
            for entity in nearby:
                print(f"      - {entity['id']} ({entity['type']}) at distance {entity.get('distance', 'unknown')}")
        except Exception as e:
            print(f"   ❌ Nearby detection error: {str(e)}")
        
        # Test chat history
        print(f"\n📚 Testing chat history...")
        try:
            history = chat_service.get_chat_history(player1_id, limit=5)
            print(f"   ✅ Retrieved {len(history)} chat records")
        except Exception as e:
            print(f"   ❌ History error: {str(e)}")
        
        # Cleanup
        facade.leave_game(player1_id)
        facade.leave_game(player2_id)
        print(f"\n🧹 Cleanup: Test players removed")
        
        return True
        
    except Exception as e:
        print(f"❌ Private chat test failed: {str(e)}")
        return False

def test_server_connectivity():
    """Test server connectivity and UI availability."""
    print("\n🌐 Testing Server Connectivity")
    print("=" * 60)
    
    try:
        # Test main application URL
        print("📡 Testing main application...")
        response = requests.get("http://localhost:7865", timeout=10)
        print(f"   Status: {'✅ Online' if response.status_code == 200 else '❌ Error'}")
        print(f"   Response time: {response.elapsed.total_seconds():.2f}s")
        print(f"   Content length: {len(response.content)} bytes")
        
        # Check if Gradio interface is responding
        print("\n🖥️ Testing Gradio interface...")
        if "gradio" in response.text.lower() or "interface" in response.text.lower():
            print("   ✅ Gradio interface detected")
        else:
            print("   ⚠️ Gradio interface not clearly detected")
        
        # Check for keyboard script presence
        print("\n⌨️ Checking keyboard script integration...")
        if "gamekeyboard" in response.text.lower() or "wasd" in response.text.lower():
            print("   ✅ Keyboard controls detected in page")
        else:
            print("   ❌ Keyboard controls not found in page")
        
        # Check for private chat elements
        print("\n💬 Checking private chat integration...")
        if "private" in response.text.lower() and "chat" in response.text.lower():
            print("   ✅ Private chat elements detected")
        else:
            print("   ❌ Private chat elements not clearly detected")
        
        return True
        
    except Exception as e:
        print(f"❌ Server connectivity test failed: {str(e)}")
        return False

def main():
    """Run comprehensive debug tests."""
    print("🔍 MMORPG Features Debug Test")
    print("=" * 60)
    print("Testing keyboard controls and private chat functionality...")
    
    # Run all tests
    keyboard_ok = test_keyboard_functionality()
    chat_ok = test_private_chat_functionality()
    server_ok = test_server_connectivity()
    
    # Summary
    print("\n" + "=" * 60)
    print("📊 TEST SUMMARY")
    print("=" * 60)
    print(f"🎮 Keyboard Controls:  {'✅ PASS' if keyboard_ok else '❌ FAIL'}")
    print(f"💬 Private Chat:       {'✅ PASS' if chat_ok else '❌ FAIL'}")
    print(f"🌐 Server Connectivity: {'✅ PASS' if server_ok else '❌ FAIL'}")
    
    if all([keyboard_ok, chat_ok, server_ok]):
        print("\n🎉 All features working! Issues may be in frontend integration.")
        print("\n💡 Next steps to fix UI issues:")
        print("   1. Check JavaScript console for errors")
        print("   2. Verify keyboard script is properly loaded")
        print("   3. Ensure private chat UI is properly connected")
        print("   4. Test in browser at: http://localhost:7865")
    else:
        print("\n⚠️ Some features have issues - backend problems detected.")
    
    print("=" * 60)

if __name__ == "__main__":
    main()