File size: 10,837 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
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
#!/usr/bin/env python3
"""

Improved debug script to test keyboard controls and private chat functionality.

"""

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

def test_keyboard_backend():
    """Test keyboard controls backend functionality."""
    print("🎮 Testing Keyboard Controls Backend")
    print("=" * 60)
    
    try:
        # Initialize game facade
        facade = GameFacade()
        
        # Create test player
        player_id = facade.join_game("KeyboardTester")
        print(f"✅ Test player created: {player_id}")
        
        # Get initial player data
        try:
            player_stats = facade.get_player_stats(player_id)
            print(f"📍 Initial position: ({player_stats.get('x', '?')}, {player_stats.get('y', '?')})")
        except Exception as e:
            print(f"⚠️ Could not get initial position: {e}")
        
        # Test all movement directions (what keyboard would trigger)
        movements = [
            ("up", "🔼", "W/↑"),
            ("down", "🔽", "S/↓"), 
            ("left", "◀️", "A/←"),
            ("right", "▶️", "D/→")
        ]
        
        print("\n🎯 Testing movement commands (keyboard backend):")
        for direction, icon, keys in movements:
            try:
                print(f"   {icon} Testing {direction} movement (keys: {keys})...")
                success, new_position, events = facade.move_player(player_id, direction)
                
                if success:
                    print(f"      ✅ Success - New position: ({new_position.get('x', '?')}, {new_position.get('y', '?')})")
                    if events:
                        print(f"      📝 Events: {', '.join(events)}")
                else:
                    print(f"      ❌ Failed - Movement blocked")
                    
                time.sleep(0.3)  # Small delay between movements
                
            except Exception as e:
                print(f"      ❌ Error: {str(e)}")
        
        # Test action command (spacebar equivalent)
        print(f"\n⚡ Testing special action (spacebar)...")
        try:
            result = facade.handle_action(player_id)
            print(f"   ✅ Result: {result}")
        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 backend test failed: {str(e)}")
        return False

def test_private_chat_backend():
    """Test private chat backend functionality."""
    print("\n💬 Testing Private Chat Backend")
    print("=" * 60)
    
    try:
        # Initialize services
        facade = GameFacade()
        engine = get_game_engine()
        world = engine.get_world()
        
        # Create test players
        player1_id = facade.join_game("ChatTester1")
        player2_id = facade.join_game("ChatTester2")
        print(f"✅ Test players created: {player1_id}, {player2_id}")
        
        # Move players close to each other for proximity
        print("\n🚶 Moving players close to each other...")
        facade.move_player(player1_id, "right")
        facade.move_player(player1_id, "right")
        facade.move_player(player2_id, "right")
        
        # Test proximity detection
        print(f"\n👥 Testing proximity detection...")
        try:
            proximity_data = facade.get_proximity_info(player1_id)
            nearby_entities = proximity_data.get("nearby_entities", [])
            print(f"   ✅ Found {len(nearby_entities)} nearby entities")
            for entity in nearby_entities:
                print(f"      - {entity.get('name', entity.get('id', 'Unknown'))}")
        except Exception as e:
            print(f"   ❌ Proximity error: {str(e)}")
          # Test private message sending
        print(f"\n📤 Testing private message sending...")
        try:
            result = facade.send_private_message(
                player1_id,
                "ChatTester1", 
                player2_id,
                "Hello from private chat 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 = facade.get_private_messages(player1_id, player2_id)
            print(f"   ✅ Retrieved {len(messages)} private messages")
            for i, msg in enumerate(messages[-2:], 1):  # Show last 2 messages
                sender = msg.get('sender_id', 'Unknown')
                content = msg.get('message', 'No content')
                timestamp = msg.get('timestamp', 'No time')
                print(f"      {i}. [{timestamp}] {sender}: {content}")
        except Exception as e:
            print(f"   ❌ Retrieval error: {str(e)}")
        
        # Test public chat (for comparison)
        print(f"\n📢 Testing public chat...")
        try:
            result = facade.send_chat_message(player1_id, "Hello public chat!")
            print(f"   {'✅ Public message sent' if result else '❌ Public message failed'}")
            
            history = facade.get_chat_history(5)
            print(f"   ✅ Retrieved {len(history)} chat history entries")
        except Exception as e:
            print(f"   ❌ Public chat 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 backend test failed: {str(e)}")
        return False

def test_frontend_integration():
    """Test frontend integration and JavaScript presence."""
    print("\n🌐 Testing Frontend Integration")
    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 for keyboard script presence
        print("\n⌨️ Checking keyboard script integration...")
        content_lower = response.text.lower()
        
        checks = [
            ("gameKeyboard object", "gamekeyboard" in content_lower),
            ("WASD controls", "wasd" in content_lower),
            ("Arrow keys", "arrow" in content_lower),
            ("Key event handlers", "keydown" in content_lower or "keypress" in content_lower),
            ("Movement buttons", "move" in content_lower and "button" in content_lower),
        ]
        
        for check_name, check_result in checks:
            status = "✅ Found" if check_result else "❌ Missing"
            print(f"   {status}: {check_name}")
        
        # Check for private chat elements
        print("\n💬 Checking private chat integration...")
        chat_checks = [
            ("Private chat UI", "private" in content_lower and "chat" in content_lower),
            ("Nearby entities", "nearby" in content_lower),
            ("Chat tabs", "tab" in content_lower),
            ("Message input", "message" in content_lower),
        ]
        
        for check_name, check_result in chat_checks:
            status = "✅ Found" if check_result else "❌ Missing"
            print(f"   {status}: {check_name}")
        
        # Check for enhanced features
        print("\n🎨 Checking enhanced features...")
        enhanced_checks = [
            ("Player glow effect", "border" in content_lower and "yellow" in content_lower),
            ("Player names", "name" in content_lower and "level" in content_lower),
            ("Status line", "fantasy realm" in content_lower),
            ("Movement controls", "movement" in content_lower and "controls" in content_lower),
        ]
        
        for check_name, check_result in enhanced_checks:
            status = "✅ Found" if check_result else "❌ Missing"
            print(f"   {status}: {check_name}")
        
        return True
        
    except Exception as e:
        print(f"❌ Frontend integration test failed: {str(e)}")
        return False

def main():
    """Run comprehensive debug tests with improved logging."""
    print("🔍 MMORPG Debug Test - Keyboard & Private Chat")
    print("=" * 70)
    print("Testing backend functionality and frontend integration...")
    
    # Run all tests
    keyboard_ok = test_keyboard_backend()
    chat_ok = test_private_chat_backend()
    frontend_ok = test_frontend_integration()
    
    # Summary
    print("\n" + "=" * 70)
    print("📊 COMPREHENSIVE TEST SUMMARY")
    print("=" * 70)
    print(f"🎮 Keyboard Backend:    {'✅ PASS' if keyboard_ok else '❌ FAIL'}")
    print(f"💬 Private Chat Backend: {'✅ PASS' if chat_ok else '❌ FAIL'}")
    print(f"🌐 Frontend Integration: {'✅ PASS' if frontend_ok else '❌ FAIL'}")
    
    if all([keyboard_ok, chat_ok, frontend_ok]):
        print("\n🎉 ALL TESTS PASSED!")
        print("\n✨ Next steps for manual testing:")
        print("   1. Open http://localhost:7865 in your browser")
        print("   2. Join the game with a player name")
        print("   3. Test keyboard controls: WASD or Arrow keys")
        print("   4. Test spacebar for special actions")
        print("   5. Move near other players/NPCs for private chat")
        print("   6. Use the private chat interface")
    elif keyboard_ok and chat_ok:
        print("\n⚠️ Backend working, but frontend integration issues detected.")
        print("\n🔧 Recommended fixes:")
        print("   - Check browser console for JavaScript errors")
        print("   - Verify keyboard script is properly loaded")
        print("   - Ensure buttons have correct IDs for script binding")
    else:
        print("\n❌ Backend issues detected - need to fix core functionality first.")
    
    print("\n🌐 Application URL: http://localhost:7865")
    print("=" * 70)

if __name__ == "__main__":
    main()