55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
from bottle import template, get, run, post, request, redirect, response
|
|
from chess import Game
|
|
|
|
|
|
KEY = "abcdefgh"
|
|
TEMPLATE = "template.tpl"
|
|
games = dict()
|
|
|
|
def is_submitted(name):
|
|
"""Return True if form element with name was submitted."""
|
|
return request.forms.get(name) != None
|
|
|
|
@get("/")
|
|
def index():
|
|
"""Drop cookie if it doesn't exist. Redirect to /game/."""
|
|
if request.get_cookie("gameid", secret=KEY) not in games.keys():
|
|
game = Game()
|
|
id = str(max(list(map(int, games.keys()))+[0]) + 1)
|
|
games[id] = game
|
|
response.set_cookie("gameid", id, path='/', secret=KEY)
|
|
redirect("/game/")
|
|
|
|
@get("/game/")
|
|
def show():
|
|
"""Show board. Redirect to index if id given by cookie not in games."""
|
|
id = request.get_cookie("gameid", secret=KEY)
|
|
if id not in games:
|
|
redirect("/")
|
|
return template(TEMPLATE, game=games[id], valid=True)
|
|
|
|
@post("/game/")
|
|
def move():
|
|
"""Catch form submissions and manipulate the game instance."""
|
|
id = request.get_cookie("gameid", secret=KEY)
|
|
valid = True
|
|
if is_submitted("newgame"):
|
|
del games[id]
|
|
redirect("/")
|
|
if is_submitted("prev"):
|
|
games[id].prev()
|
|
elif is_submitted("first"):
|
|
games[id].first()
|
|
elif is_submitted("next"):
|
|
games[id].next()
|
|
elif is_submitted("last"):
|
|
games[id].last()
|
|
else:
|
|
AN = request.forms.get("move")
|
|
valid = games[id].AN_move(AN)
|
|
return template(TEMPLATE, game=games[id], valid=valid)
|
|
|
|
|
|
run(host="localhost", port=8080)
|
|
|