This article is for Django Girls Japan Python beginners, This is a study session material for "Let's make a rock-paper-scissors game with Python". Since the author is also a beginner, we apologize for any inconvenience. Namer environment: Windows 10 python3.5
With the http.server module, you can write a program written in Python in a web server. It is possible to execute. You can easily create a web application without preparing a web server or setting up moromoro. You can try it.
This time Janken Poi in Python Based on the rock-paper-scissors game created in, create something that runs on the browser.
The structure of the file is as follows.
While in the janken folder at the command prompt python -m http.server --cgi And press the enter key to start the local server. (For Python2, enter python -m CGIHTTPServer.)
Now you can run the game on your browser.
This is the html source placed directly under the janken folder.
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"> </head>
<body>
<center><br><br>
<form action="/cgi-bin/janken.py" method="POST"><h1><font color="#FF7F50">Janken</font></h1><br /><br />
<font size="5"><input type="radio" name="janken" value=1>Goo<br />
<input type="radio" name="janken" value=2>Choki<br />
<input type="radio" name="janken" value=3>Par<br /><br /></font>
<input type="submit" name="submit" />
</form>
</center>
</body>
</html>
<form action="/cgi-bin/janken.py" method="POST">
Here you can pass requests from this page to janken.py under the cgi-bin folder. (Details of the html source are omitted here.)
The source for janken.py under the janken / cgi-bin folder.
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import cgi
import random
form = cgi.FieldStorage()
dic = {"1": "Goo", "2": "Choki", "3": "Par"}
user = form.getfirst('janken')
user_choice = dic[user]
choice_list = ["1", "'2", "3"]
pc = dic[random.choice(choice_list)]
draw = '<font color="#32CD32">DRAW</font>'
win = '<font color="#FF7F50">You Win!!</font>'
lose = '<font color="#0000FF">You lose!!</font>'
if user_choice == pc:
judge = draw
else:
if user_choice == "Goo":
if pc == "Choki":
judge = win
else:
judge = lose
elif user_choice == "Choki":
if pc == "Par":
judge = win
else:
judge = lose
else:
if pc == u"Goo":
judge = win
else:
judge = lose
html_body = """
<html><body><center><br><br><br>
What you chose%s<br><br>
The computer chose%s<br><br>
<font size="5">Result is%s </font><br><br>
<a Href ="http://127.0.0.1:8000/janken.html">Return</a>
</center></body></html>""" % (user_choice, pc, judge)
print("Content-type: text/html\n")
print(html_body)