initial commit
This commit is contained in:
100
camel_race.py
Normal file
100
camel_race.py
Normal file
@@ -0,0 +1,100 @@
|
||||
from flask import request, url_for
|
||||
from flask_api import FlaskAPI, status, exceptions
|
||||
from typing import Union, Optional
|
||||
from random import choices
|
||||
|
||||
from game import CamelGame
|
||||
|
||||
app = FlaskAPI(__name__)
|
||||
|
||||
games = {}
|
||||
|
||||
allowed_id_chars = [chr(c) for c in range(0x41, 0x5B)] + [chr(c) for c in range(0x61, 0x7B)]
|
||||
allowed_id_chars.remove('l')
|
||||
allowed_id_chars.remove('I')
|
||||
|
||||
|
||||
def _generate_id():
|
||||
while True:
|
||||
new_id = ''.join(choices(allowed_id_chars, k=6))
|
||||
if new_id not in games:
|
||||
return new_id
|
||||
|
||||
|
||||
def _get_game_obj(game_id: str) -> Optional[CamelGame]:
|
||||
return games.get(game_id, None)
|
||||
|
||||
|
||||
@app.route('/game/<game_id>', methods=['GET'])
|
||||
def get_game(game_id: str):
|
||||
game = _get_game_obj(game_id)
|
||||
if game is None:
|
||||
return '', status.HTTP_404_NOT_FOUND
|
||||
|
||||
return {
|
||||
'status': game.state,
|
||||
'amount_left': game.side_length,
|
||||
'winning_ace': game.get_winner(),
|
||||
'left_cards': game.get_open_side_cards(),
|
||||
'aces': game.ace_position,
|
||||
'drinks': game.get_drinks(),
|
||||
'bets': game.bets,
|
||||
}
|
||||
|
||||
|
||||
@app.route('/game/<game_id>/start', methods=['GET'])
|
||||
def start_game(game_id: str):
|
||||
game = _get_game_obj(game_id)
|
||||
if game is None:
|
||||
return '', status.HTTP_404_NOT_FOUND
|
||||
|
||||
return {
|
||||
'started': game.start_game()
|
||||
}
|
||||
|
||||
|
||||
@app.route('/game/<game_id>/bet', methods=['POST'])
|
||||
def bet_on_game(game_id: str):
|
||||
game = _get_game_obj(game_id)
|
||||
if game is None:
|
||||
return '', status.HTTP_404_NOT_FOUND
|
||||
|
||||
user = request.data['USER']
|
||||
suit = request.data['SUIT']
|
||||
amount = int(request.data['AMOUNT'])
|
||||
|
||||
if game.bet(user, suit, amount):
|
||||
return {'ok': True}
|
||||
return {'ok': False}
|
||||
|
||||
|
||||
@app.route('/game/<game_id>/round', methods=['GET'])
|
||||
def do_round(game_id: str):
|
||||
game = _get_game_obj(game_id)
|
||||
if game is None:
|
||||
return '', status.HTTP_404_NOT_FOUND
|
||||
|
||||
card = game.do_round()
|
||||
|
||||
if card is None:
|
||||
return "game probably already done", status.HTTP_400_BAD_REQUEST
|
||||
|
||||
return {
|
||||
'card': card
|
||||
}
|
||||
|
||||
|
||||
@app.route('/game/', methods=['GET'])
|
||||
def start_new_game():
|
||||
game = CamelGame()
|
||||
game_id = _generate_id()
|
||||
games[game_id] = game
|
||||
game.init_game()
|
||||
return {
|
||||
'initialized': True,
|
||||
'url': url_for('get_game', game_id=game_id)
|
||||
}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run()
|
||||
Reference in New Issue
Block a user