Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added cookies to do time keeping #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion escaperoom/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import jsonschema

from .room import Game, Puzzle
from room import Game, Puzzle


class CampaignReader:
Expand Down
66 changes: 44 additions & 22 deletions escaperoom/server.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,47 @@
import argparse
import datetime
from datetime import *
from typing import Any, Optional

from flask import Flask, redirect, render_template, request
from flask import Flask, redirect, render_template, request, make_response

from .reader import CampaignReader
from .room import Game
from reader import CampaignReader
from room import Game
import logging

# Flask app.
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)

# Global variable for capturing game details.
GAME: Optional[Game] = None
# Global variable for capturing total time.
EPOCH: datetime.datetime = datetime.datetime(1970, 1, 1)
START_TIME: datetime.datetime = EPOCH
MAX_PLAY_TIME_MINUTES = 60


@app.route("/")
@app.route("/", methods=['POST', 'GET'])
def index():
"""Method to render homepage."""
return render_template(
"index.html", title=GAME.title, text=GAME.text, images=GAME.images,
)

if request.method == 'GET':
return render_template(
"index.html", title=GAME.title, text=GAME.text, images=GAME.images, playtime=MAX_PLAY_TIME_MINUTES,
)
elif request.method == 'POST':
user = request.form['teamname']
if not user:
raise
expireTime = datetime.now() + timedelta(minutes = (MAX_PLAY_TIME_MINUTES + 60))
response = make_response(redirect("/puzzle/1"))
response.set_cookie('userID', user, expires=expireTime)
response.set_cookie('startTime', str(datetime.now()), expires=expireTime)
return response

def get_puzzle(puzzle_id: str) -> Any:
"""Method to get the puzzle.

:param puzzle_id: ID of the puzzle.
"""
global START_TIME
if puzzle_id == CampaignReader.STARTING_PUZZLE_KEY and START_TIME == EPOCH:
START_TIME = datetime.datetime.now()
if puzzle_id == CampaignReader.STARTING_PUZZLE_KEY:
teamName = request.cookies.get('userID')
startTime = request.cookies.get('startTime')
app.logger.info('Team ' + teamName + ' started at ' + startTime)

if GAME and puzzle_id in GAME.puzzles:
puzzle = GAME.puzzles[puzzle_id]
Expand All @@ -54,19 +63,29 @@ def submit_answer(puzzle_id: str) -> Any:
"""
if GAME and puzzle_id in GAME.puzzles:
puzzle = GAME.puzzles[puzzle_id]
start_time = datetime.fromisoformat(request.cookies.get('startTime'))
team_name = request.cookies.get('userID')
playing_time = datetime.now() - start_time
if request.form["answer"].lower() == puzzle.answer.lower():
if puzzle.next_puzzle == CampaignReader.FINAL_PUZZLE_KEY:
seconds = int((datetime.datetime.now() - START_TIME).total_seconds())
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
app.logger.info(team_name + " finished in " + str(playing_time))
hours, remainder = divmod(playing_time.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
return render_template(
"winner.html",
timetaken=f"{hours} hours {minutes} minutes {seconds} seconds",
timetaken=f"{int(round(hours, 0))} hours {int(round(minutes, 0))} minutes {int(round(seconds, 0))} seconds",
)
else:
app.logger.info(team_name + " goes to puzzle " + puzzle.title + " after " + str(playing_time))
return redirect(f"/puzzle/{puzzle.next_puzzle}")
elif (playing_time.total_seconds() / 60) > MAX_PLAY_TIME_MINUTES:
app.logger.info(team_name + " failed after " + str(playing_time))
hours, remainder = divmod(playing_time.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
return render_template(
"loser.html",
timetaken=f"{int(round(hours, 0))} hours {int(round(minutes, 0))} minutes {int(round(seconds, 0))} seconds",
)
else:
return render_template(
"puzzle.html",
Expand Down Expand Up @@ -116,3 +135,6 @@ def main():

# Run flask app.
app.run(host=arguments.host, port=arguments.port)

if __name__ == '__main__':
main()
11 changes: 7 additions & 4 deletions escaperoom/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<div class="container">
<div class="jumbotron">
<h1 class="display-4">Escaperoom!</h1>
<p class="lead">Work together as a team to solve puzzles. Escape the room before time runs out.</p>
<p class="lead">Work together as a team to solve puzzles. Escape the room before time runs out after {{playtime}} minutes.</p>
<hr class="my-4">
<p><b>{{title}}</b></p>
<p>{{text}}</p>
Expand All @@ -38,9 +38,12 @@ <h1 class="display-4">Escaperoom!</h1>
</div>
{% endif %}
<br/>
<p class="lead">
<a class="btn btn-primary btn" href="/puzzle/1" role="button">Ready, Set, Go...</a>
</p>

<form method="post">
<p><input type=text name=teamname placeholder="Enter your teamname here">
<p><input type=submit value="Ready, Set, Go...">
</form>

</div>
</div>

Expand Down
28 changes: 28 additions & 0 deletions escaperoom/templates/loser.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<title>Escaperoom!</title>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1 class="display-4">Time is up!</h1>
<p class="lead">You and your friends have not finished the escaperoom.</p>
<p class="lead">Total time taken is {{ timetaken }}.</p>
</div>
</div>

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>