File size: 2,055 Bytes
a78e101
 
 
 
6caeb35
a78e101
 
 
6caeb35
438862f
ca24c9d
 
438862f
a78e101
 
 
 
8723647
 
 
 
 
 
 
 
 
438862f
 
 
8723647
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a78e101
 
438862f
6caeb35
ca24c9d
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
from flask import Flask, render_template, session
from flask_socketio import SocketIO, emit
from game import Game
import uuid
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'  # Replace with a secure key

# Configure SocketIO with eventlet for WebSocket support and specific CORS origin
socketio = SocketIO(app, 
                    cors_allowed_origins="https://broadfield-dev-dungeon-game.hf.space",  # Your Spaces URL
                    async_mode='eventlet')  # Use eventlet for WebSocket support

# Store game instances per client session
games = {}

@app.route('/')
def index():
    session['sid'] = str(uuid.uuid4())  # Unique session ID for each client
    return render_template('index.html')

@socketio.on('connect')
def handle_connect(auth=None):
    sid = session.get('sid')
    games[sid] = Game()
    game_state = games[sid].get_game_state()
    print(f"Emitting update_game for SID {sid}:", game_state)  # Debug log
    emit('update_game', game_state)
    emit('message', 'Connected to the dungeon! Use arrow keys to move.')

@socketio.on('move')
def handle_move(direction):
    sid = session.get('sid')
    if sid in games:
        game = games[sid]
        game.move_player(direction)
        emit('update_game', game.get_game_state())

@socketio.on('use_item')
def handle_use_item(item_type):
    sid = session.get('sid')
    if sid in games:
        game = games[sid]
        if item_type == 'potion' and 'potion' in game.inventory:
            game.inventory.remove('potion')
            game.player_health = min(game.player_health + 5, 20)
            emit('message', 'Used a health potion! Health restored.')
            emit('update_game', game.get_game_state())

@socketio.on('disconnect')
def handle_disconnect():
    sid = session.get('sid')
    if sid in games:
        del games[sid]

if __name__ == '__main__':
    print("Starting server on port", os.environ.get('PORT', 7860))  # Debug log
    port = int(os.environ.get('PORT', 7860))
    socketio.run(app, debug=True, host='0.0.0.0', port=port)