LoginSignup
13
13

More than 5 years have passed since last update.

Pythonでじゃんけんポイっ 初心者向け Windows ローカルサーバで動かそう

Last updated at Posted at 2016-11-03

この記事は、Django Girls Japan Python初級者向け、
「Pythonでじゃんけんゲームを作ろう」の勉強会用資料です。
尚、記載者も初心者のため、何らかの不具合などござましたら申し訳ございません。
記載者環境:Windows 10 python3.5

CGIサーバー

http.serverモジュールを使うと、Pythonで書いたプログラムをWebサーバの中で
実行する事が可能です。
Webサーバを用意したり、モロモロの設定をしなくても手軽にWebアプリケーションを作って
ためす事ができます。

今回は
Pythonでじゃんけんポイっ
で作成したじゃんけんゲームをもとに、ブラウザ上で動かすものを作ります。

ファイルの構造は以下のようにします。

kaisou.JPG

コマンドプロンプトでjankenフォルダにいる状態で
python -m http.server --cgi
と入力し、エンターキーを押すとローカルサーバが起動します。
(Python2の場合は python -m CGIHTTPServer と入力してください。)

cgi.JPG

これで、ブラウザ上でゲームを動かす事ができるようになります。
janken3.JPG

HTMLのソース

jankenフォルダ直下におく、htmlのソースです。

<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">じゃーんけーん</font></h1><br /><br />
    <font size="5"><input type="radio" name="janken" value=1>グー<br />
    <input type="radio" name="janken" value=2>チョキ<br />
    <input type="radio" name="janken" value=3>パー<br /><br /></font>
    <input type="submit" name="submit" />
  </form>
  </center>
</body>
</html>

  <form action="/cgi-bin/janken.py" method="POST">

ここで、このページからのリクエストをcgi-binフォルダ下にあるjanken.pyにわたす事ができます。
(htmlのソースの詳細は、ここでは割愛いたします。)

Pythonファイル

janken/cgi-bin フォルダ下にあるjanken.pyのソースです。

# -*- coding: utf-8 -*-
# !/usr/bin/env python

import cgi
import random

form = cgi.FieldStorage()

dic = {"1": "グー", "2": "チョキ", "3": "パー"}

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 == "グー":
        if pc == "チョキ":
            judge = win
        else:
            judge = lose

    elif user_choice == "チョキ":
        if pc == "パー":
            judge = win
        else:
            judge = lose

    else:
        if pc == u"グー":
            judge = win
        else:
            judge = lose


html_body = """
<html><body><center><br><br><br>
あなたが選んだのは %s<br><br>
コンピュータが選んだのは%s<br><br>
<font size="5"> 結果は %s </font><br><br>
<a Href ="http://127.0.0.1:8000/janken.html">戻る</a>
</center></body></html>""" % (user_choice, pc, judge)

print("Content-type: text/html\n")
print(html_body)

13
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13