use session cookie to support multiple players

master
Simon Pirkelmann 2020-09-11 16:40:20 +02:00
parent 415303c10f
commit 3b1896d5ab
2 changed files with 32 additions and 12 deletions

43
app.py
View File

@ -1,15 +1,18 @@
from flask import Flask, render_template, request
from flask import Flask, render_template, request, session
import random
app = Flask(__name__)
app.secret_key = b'RoboRallyRolling'
random.seed(0)
moves = ['forward', 'backward', 'turn left', 'turn right', 'turn around']
class Card:
global_counter = 0
card_counter = 0
def __init__(self):
self.number = Card.global_counter
Card.global_counter += 1
self.number = Card.card_counter
Card.card_counter += 1
self.action = random.choice(moves)
self.priority = random.randint(0, 100)
@ -20,13 +23,29 @@ card_deck = {}
for i in range(0,20):
card_deck[i] = Card()
player_hand = [card_deck[i] for i in range(9)]
player_counter = 0
MAX_PLAYERS = 3
player_hand = {}
@app.route('/', methods=['GET', 'POST'])
def hello_world():
global player_counter
if not 'player_id' in session:
if player_counter < MAX_PLAYERS:
# new player
session['player_id'] = player_counter
player_counter += 1
# give him some cards
player_hand[session['player_id']] = random.sample(list(card_deck.values()), 9)
print("current hand: ", [str(c) for c in player_hand[session['player_id']]])
else:
return "Sorry, maximum number of players reached!"
player_id = session['player_id']
if request.method == 'GET':
return render_template('drag_example.html', cmds=player_hand)
return render_template('drag_example.html', cmds=player_hand[player_id], player_id=player_id)
elif request.method == 'POST':
print(request.form)
@ -37,16 +56,16 @@ def hello_world():
card1 = card_deck[i1] # get card by number
card2 = card_deck[i2]
j1 = player_hand.index(card1) # get index of card in the hand
j2 = player_hand.index(card2)
j1 = player_hand[player_id].index(card1) # get index of card in the hand
j2 = player_hand[player_id].index(card2)
player_hand[j1], player_hand[j2] = player_hand[j2], player_hand[j1] # swap the cards in the list
player_hand[player_id][j1], player_hand[player_id][j2] = player_hand[player_id][j2], player_hand[player_id][j1] # swap the cards in the list
print("current hand: ", [str(c) for c in player_hand])
print("current hand: ", [str(c) for c in player_hand[player_id]])
return 'OK'
if __name__ == '__main__':
app.run()
app.run(host='0.0.0.0', port=5000)

View File

@ -12,6 +12,7 @@
</head>
<body>
<h1>Welcome Player {{ player_id }}</h1>
<!-- container -->
<div class="container">