Renday commited on
Commit
c14c045
·
verified ·
1 Parent(s): a18b99d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -67
app.py CHANGED
@@ -1,92 +1,125 @@
1
- from flask import Flask, request, jsonify
2
- from flask_socketio import SocketIO, emit
3
- from flask_cors import CORS
4
  import random
 
 
5
 
6
  app = Flask(__name__)
7
- # CORS ist wichtig, damit deine Webseite auf den HF-Space zugreifen darf
8
- CORS(app, resources={r"/*": {"origins": "*"}})
9
- socketio = SocketIO(app, cors_allowed_origins="*", async_mode='gevent')
10
-
11
- # --- SPIEL LOGIK ---
12
- game_state = {
13
- "players": [],
14
- "middle": [],
15
- "deck": [],
16
- "turn_idx": 0,
17
- "knocked_by": None,
18
- "active": False
19
  }
20
 
21
- def create_deck():
22
- suits = ['Herz', 'Karo', 'Pik', 'Kreuz']
23
- ranks = {'7':7, '8':8, '9':9, '10':10, 'B':10, 'D':10, 'K':10, 'A':11}
24
- return [{'suit': s, 'rank': r, 'val': v} for s in suits for r, v in ranks.items()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- def calc_score(hand):
27
- scores = {'Herz': 0, 'Karo': 0, 'Pik': 0, 'Kreuz': 0}
28
- for c in hand: scores[c['suit']] += c['val']
29
- ranks = [c['rank'] for c in hand]
30
- if len(set(ranks)) == 1: return 30.5
31
- return max(scores.values())
32
 
33
  @app.route('/login', methods=['POST'])
34
  def login():
35
  data = request.json
36
  email = data.get('email')
37
- user = next((p for p in game_state['players'] if p['email'] == email), None)
38
- if not user:
39
- user = {"email": email, "coins": 1000, "hand": [], "score": 0, "is_admin": len(game_state['players']) == 0}
40
- game_state['players'].append(user)
41
- return jsonify({"stats": user})
 
 
 
 
 
 
42
 
43
  @socketio.on('join_game')
44
- def on_join(data):
45
- emit('update_table', game_state, broadcast=True)
 
 
 
46
 
47
  @socketio.on('start_round')
48
- def start_round():
49
- deck = create_deck()
50
- random.shuffle(deck)
51
- for p in game_state['players']:
52
- p['hand'] = [deck.pop(), deck.pop(), deck.pop()]
53
- p['score'] = calc_score(p['hand'])
54
- game_state.update({
55
- "middle": [deck.pop(), deck.pop(), deck.pop()],
56
- "deck": deck,
57
- "turn_idx": 0,
58
- "knocked_by": None,
59
- "active": True
60
- })
61
- emit('update_table', game_state, broadcast=True)
62
 
63
  @socketio.on('player_action')
64
- def on_action(data):
65
  email = data.get('email')
 
 
 
 
66
  action_type = data.get('type')
67
- current_player = game_state['players'][game_state['turn_idx']]
68
-
69
- if current_player['email'] != email: return
70
 
71
- if action_type == 'knock' and game_state['knocked_by'] is None:
72
- game_state['knocked_by'] = email
73
- elif action_type == 'swap_one':
74
  h_idx, m_idx = data['h_idx'], data['m_idx']
75
- current_player['hand'][h_idx], game_state['middle'][m_idx] = game_state['middle'][m_idx], current_player['hand'][h_idx]
 
76
  elif action_type == 'swap_all':
77
- current_player['hand'], game_state['middle'] = game_state['middle'], current_player['hand']
78
 
79
- current_player['score'] = calc_score(current_player['hand'])
80
- game_state['turn_idx'] = (game_state['turn_idx'] + 1) % len(game_state['players'])
81
-
82
- next_player = game_state['players'][game_state['turn_idx']]
83
- if next_player['email'] == game_state['knocked_by']:
84
- winner = max(game_state['players'], key=lambda p: p['score'])
85
- emit('game_over', {'winner': winner['email'], 'score': winner['score']}, broadcast=True)
86
- game_state['active'] = False
87
-
88
- emit('update_table', game_state, broadcast=True)
 
 
 
 
 
 
 
 
 
 
89
 
90
  if __name__ == '__main__':
91
- # Startet den Server auf Port 7860 (Hugging Face Standard)
92
- socketio.run(app, host="0.0.0.0", port=7860)
 
 
 
 
1
  import random
2
+ from flask import Flask, render_template, request, jsonify
3
+ from flask_socketio import SocketIO, emit
4
 
5
  app = Flask(__name__)
6
+ app.config['SECRET_KEY'] = 'casino-secret!'
7
+ socketio = SocketIO(app, cors_allowed_origins="*")
8
+
9
+ # --- SPIELLOGIK ---
10
+ SUITS = ['Herz', 'Karo', 'Pik', 'Kreuz']
11
+ RANKS = {
12
+ '7': 7, '8': 8, '9': 9, '10': 10,
13
+ 'B': 10, 'D': 10, 'K': 10, 'A': 11
 
 
 
 
14
  }
15
 
16
+ class GameState:
17
+ def __init__(self):
18
+ self.players = {} # email -> data
19
+ self.middle = []
20
+ self.deck = []
21
+ self.turn_idx = 0
22
+ self.active_emails = []
23
+ self.current_bet = 50
24
+ self.game_started = False
25
+
26
+ def reset_deck(self):
27
+ self.deck = [{'suit': s, 'rank': r, 'val': v} for s in SUITS for r, v in RANKS.items()]
28
+ random.shuffle(self.deck)
29
+
30
+ def calculate_score(self, hand):
31
+ # 31 Logik: Höchste Summe einer Farbe oder 30.5 für drei gleiche Ränge
32
+ scores = {'Herz': 0, 'Karo': 0, 'Pik': 0, 'Kreuz': 0}
33
+ for c in hand:
34
+ scores[c['suit']] += c['val']
35
+
36
+ # Check für 3 gleiche (z.B. drei 7er = 30.5)
37
+ ranks = [c['rank'] for c in hand]
38
+ if len(set(ranks)) == 1 and len(hand) == 3:
39
+ return 30.5
40
+
41
+ return max(scores.values())
42
 
43
+ game = GameState()
44
+
45
+ @app.route('/')
46
+ def index():
47
+ return render_template('index.html')
 
48
 
49
  @app.route('/login', methods=['POST'])
50
  def login():
51
  data = request.json
52
  email = data.get('email')
53
+ if email not in game.players:
54
+ game.players[email] = {
55
+ 'email': email,
56
+ 'coins': 1000,
57
+ 'hand': [],
58
+ 'score': 0,
59
+ 'is_admin': len(game.players) == 0 # Erster ist Admin
60
+ }
61
+ return jsonify({'stats': game.players[email]})
62
+
63
+ # --- SOCKET EVENTS ---
64
 
65
  @socketio.on('join_game')
66
+ def handle_join(data):
67
+ email = data.get('email')
68
+ if email not in game.active_emails:
69
+ game.active_emails.append(email)
70
+ broadcast_state()
71
 
72
  @socketio.on('start_round')
73
+ def start_round(data):
74
+ game.reset_deck()
75
+ game.game_started = True
76
+ game.middle = [game.deck.pop() for _ in range(3)]
77
+
78
+ for email in game.active_emails:
79
+ p = game.players[email]
80
+ p['hand'] = [game.deck.pop() for _ in range(3)]
81
+ p['score'] = game.calculate_score(p['hand'])
82
+ p['coins'] -= int(game.current_bet)
83
+
84
+ game.turn_idx = 0
85
+ broadcast_state()
 
86
 
87
  @socketio.on('player_action')
88
+ def handle_action(data):
89
  email = data.get('email')
90
+ if game.active_emails[game.turn_idx] != email:
91
+ return
92
+
93
+ p = game.players[email]
94
  action_type = data.get('type')
 
 
 
95
 
96
+ if action_type == 'swap_one':
 
 
97
  h_idx, m_idx = data['h_idx'], data['m_idx']
98
+ p['hand'][h_idx], game.middle[m_idx] = game.middle[m_idx], p['hand'][h_idx]
99
+
100
  elif action_type == 'swap_all':
101
+ p['hand'], game.middle = game.middle, p['hand']
102
 
103
+ elif action_type == 'knock':
104
+ # In einer echten Version würde das Spiel nach einer weiteren Runde enden
105
+ emit('game_over', {'winner': email}, broadcast=True)
106
+ return
107
+
108
+ p['score'] = game.calculate_score(p['hand'])
109
+ game.turn_idx = (game.turn_idx + 1) % len(game.active_emails)
110
+ broadcast_state()
111
+
112
+ @socketio.on('admin/set_bet')
113
+ def set_bet(data):
114
+ game.current_bet = data.get('bet', 50)
115
+
116
+ def broadcast_state():
117
+ state = {
118
+ 'players': [game.players[e] for e in game.active_emails],
119
+ 'middle': game.middle,
120
+ 'turn_idx': game.turn_idx
121
+ }
122
+ emit('update_table', state, broadcast=True)
123
 
124
  if __name__ == '__main__':
125
+ socketio.run(app, host='0.0.0.0', port=7860, debug=False)