78 lines
2.1 KiB
Python
78 lines
2.1 KiB
Python
import eventlet
|
|
|
|
eventlet.monkey_patch()
|
|
|
|
from flask import Flask, jsonify, request
|
|
from flask_cors import CORS
|
|
from flask_socketio import SocketIO
|
|
|
|
app = Flask(__name__)
|
|
CORS(app, origins=["*", "0.0.0.0"])
|
|
socketio = SocketIO(app, cors_allowed_origins="*")
|
|
|
|
|
|
game_state = {
|
|
"gameActive": False,
|
|
"players": [],
|
|
"playerTurn": 0
|
|
}
|
|
|
|
@app.route("/add", methods=["POST"])
|
|
def add_player():
|
|
data = request.get_json()
|
|
if not data:
|
|
return jsonify({"error": "No JSON body received"}), 400
|
|
|
|
name = data.get("name")
|
|
group = data.get("group")
|
|
|
|
if not name or group not in ["stripes", "solids"]:
|
|
return jsonify({"error": "Invalid data"}), 400
|
|
|
|
game_state["players"].append({"name": name, "group": group})
|
|
|
|
# emit socket update
|
|
socketio.emit("player_update", {"players": game_state["players"]})
|
|
|
|
return jsonify({"message": f"Player {name} added to {group} group"})
|
|
|
|
@app.route("/reset", methods=["GET"])
|
|
def reset():
|
|
game_state["gameActive"] = False
|
|
game_state["players"] = []
|
|
game_state["playerTurn"] = 0
|
|
socketio.emit("player_update", {"players": game_state["players"]})
|
|
return jsonify(game_state)
|
|
|
|
|
|
@app.route("/status", methods=["GET"])
|
|
def status():
|
|
return jsonify(game_state)
|
|
|
|
@app.route("/start", methods=["GET"])
|
|
def start_game():
|
|
players = game_state["players"]
|
|
game_state["gameActive"] = True
|
|
current_player = players[game_state["playerTurn"]]
|
|
socketio.emit("player_update", {"nextPlayer": current_player})
|
|
return jsonify(game_state)
|
|
|
|
|
|
@app.route("/next", methods=["GET"])
|
|
def next_player():
|
|
players = game_state["players"]
|
|
if not players:
|
|
return jsonify({"error": "No players"}), 400
|
|
|
|
current_player = players[game_state["playerTurn"]]
|
|
|
|
# Advance the turn
|
|
game_state["playerTurn"] = (game_state["playerTurn"] + 1) % len(players)
|
|
|
|
socketio.emit("player_update", {"nextPlayer": current_player}) # Tell clients listening of update
|
|
return jsonify({
|
|
"nextPlayer": current_player
|
|
})
|
|
|
|
if __name__ == "__main__":
|
|
socketio.run(app, host="0.0.0.0", port=8080) |