File size: 4,677 Bytes
7ef7190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import random
import string
from flask import Flask, request, jsonify, render_template
from threading import Timer

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

# In-memory storage for game sessions and player data
sessions = {}
players = {}

def generate_session_id():
    return ''.join(random.choices(string.digits, k=4))

def generate_player_id():
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))

def create_game_session():
    session_id = generate_session_id()
    while session_id in sessions:
        session_id = generate_session_id()
    sessions[session_id] = {
        'players': [],
        'words': {},
        'current_player': None,
        'guesses': set(),
        'incorrect_guesses': 0
    }
    return session_id

def join_game_session(session_id):
    if session_id not in sessions:
        return None
    player_id = generate_player_id()
    sessions[session_id]['players'].append(player_id)
    players[player_id] = {'session_id': session_id}
    return player_id

def update_game_state(session_id, guess):
    session = sessions[session_id]
    current_player = session['current_player']
    opponent = [p for p in session['players'] if p != current_player][0]

    guess = guess.lower()
    session['guesses'].add(guess)

    if guess not in session['words'][opponent]:
        session['incorrect_guesses'] += 1

    if session['incorrect_guesses'] >= 6:
        return 'game_over'

    if all(letter in session['guesses'] for letter in session['words'][opponent]):
        return 'winner'

    session['current_player'] = opponent
    return 'continue'

def check_win_condition(session_id):
    session = sessions[session_id]
    for player in session['players']:
        if all(letter in session['guesses'] for letter in session['words'][player]):
            return player
    return None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/play', methods=['POST'])
def play():
    session_id = create_game_session()
    player_id = join_game_session(session_id)
    return jsonify({'session_id': session_id, 'player_id': player_id})

@app.route('/join/<session_id>', methods=['POST'])
def join(session_id):
    player_id = join_game_session(session_id)
    if player_id:
        if len(sessions[session_id]['players']) == 2:
            sessions[session_id]['current_player'] = sessions[session_id]['players'][0]
        return jsonify({'player_id': player_id})
    return jsonify({'error': 'Session not found or full'}), 404

@app.route('/submit_word', methods=['POST'])
def submit_word():
    data = request.json
    session_id = data['session_id']
    player_id = data['player_id']
    word = data['word'].lower()

    if len(word) != 7:
        return jsonify({'error': 'Word must be 7 letters long'}), 400

    sessions[session_id]['words'][player_id] = word

    if len(sessions[session_id]['words']) == 2:
        return jsonify({'status': 'game_started'})
    return jsonify({'status': 'waiting_for_opponent'})

@app.route('/guess', methods=['POST'])
def guess():
    data = request.json
    session_id = data['session_id']
    player_id = data['player_id']
    guess = data['guess'].lower()

    if player_id != sessions[session_id]['current_player']:
        return jsonify({'error': 'Not your turn'}), 400

    result = update_game_state(session_id, guess)

    if result == 'game_over':
        winner = check_win_condition(session_id)
        return jsonify({'status': 'game_over', 'winner': winner})
    elif result == 'winner':
        return jsonify({'status': 'game_over', 'winner': player_id})

    return jsonify({'status': 'continue'})

@app.route('/game_state/<session_id>')
def game_state(session_id):
    if session_id not in sessions:
        return jsonify({'error': 'Session not found'}), 404

    session = sessions[session_id]
    return jsonify({
        'players': session['players'],
        'current_player': session['current_player'],
        'guesses': list(session['guesses']),
        'incorrect_guesses': session['incorrect_guesses'],
        'words': {player: ''.join(['_' if letter not in session['guesses'] else letter for letter in word])
                  for player, word in session['words'].items()}
    })

def cleanup_inactive_sessions():
    current_time = time.time()
    for session_id in list(sessions.keys()):
        if current_time - sessions[session_id].get('last_activity', 0) > 60:
            del sessions[session_id]
    Timer(60, cleanup_inactive_sessions).start()

if __name__ == '__main__':
    cleanup_inactive_sessions()
    app.run(host='0.0.0.0', port=7860)