이번주 목(2024-02-29) 까지 진행한 개인 과제 중
4번 문항을 푼 코드를 리뷰하고자 한다.
가위 바위 보 게임 웹 페이지 구현이다.
# 필수 라이브러리
'''
0. Flask : 웹서버를 시작할 수 있는 기능. app이라는 이름으로 플라스크를 시작한다
1. render_template : html파일을 가져와서 보여준다
'''
from flask import Flask, render_template, request
from rsp_game_web import *
app = Flask(__name__)
import os
from flask_sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "database.db")
db = SQLAlchemy(app)
class RSPGame(db.Model):
id = db.Column(db.Integer, primary_key=True)
computer = db.Column(db.String(100), nullable=False)
user = db.Column(db.String(100), nullable=False)
result = db.Column(db.String(100), nullable=False)
# [DB 생성 코드]
# with app.app_context():
# db.create_all()
@app.route("/")
def game():
# 데이터 정의 및 초기화
user_input = None
result = None
# 가위 바위 보 게임 진행
user_input = request.args.get('query')
if user_input:
result = play_game_web(user_input.lower())
if result:
row = RSPGame(computer=result["Computer"], user=result["User"], result=result["Result"])
db.session.add(row)
db.session.commit()
# 이전 기록 DB에서 가져오기
results = RSPGame.query.all()
# Html로 전송할 데이터 담기
data = {
"Current": result,
"Statistic": [
RSPGame.query.filter_by(result="승리").count(),
RSPGame.query.filter_by(result="패배").count(),
RSPGame.query.filter_by(result="무승부").count()],
"Results": results}
# 데이터 전송
return render_template('rsp_game.html', data=data)
if __name__ == "__main__":
app.run(debug=True)
app.py 파일이다.
database.db에 RSPGame Table을 생성 및 활성화 하는 코드와
Flask를 이용한 로컬 서버 구동을 담당한다.
import random
RSP_DATA = {
"Korean": ["가위", "바위", "보"],
"English": ["scissors", "rock", "paper"]
}
def play_game_web(user_input):
com_idx = random.randrange(3)
if user_input in RSP_DATA["Korean"]:
temp_list = RSP_DATA["Korean"]
elif user_input in RSP_DATA["English"]:
temp_list = RSP_DATA["English"]
else:
print("유효하지 않은 입력입니다. 다시 시도해주십시오.")
return None
user_idx = temp_list.index(user_input)
# result
# 0: 무승부, 1: 승리, 2: 패배
result = (user_idx - com_idx) % 3
if result == 0:
result_text = "무승부"
elif result == 1:
result_text = "승리"
else:
result_text = "패배"
return {"Computer": temp_list[com_idx], "User": user_input, "Result": result_text}
rsp_game_web.py는 2번 문항 코드에서 변형했다.
https://creative-darkstar.tistory.com/11
[TIL] 20240223 9일차
다음주 목(2024-02-29) 까지 진행할 개인 과제 중 2번 문항을 풀이한 코드를 리뷰하고자 한다. 가위 바위 보 게임 구현이다. if __name__ == "__main__": # [무, 승, 패] status = [0, 0, 0] set_game() 초기에 파이썬
creative-darkstar.tistory.com
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>가위 바위 보 게임</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
<h1>가위 바위 보 게임</h1>
<p>[가위, 바위, 보] 또는 [scissors, rock, paper]중 하나를 선택하여 입력하십시오.</p>
<p></p>
<form action="{{ url_for('game') }}">
<input type="text" name="query">
<button type="submit">입력</button>
</form>
<p></p>
{% if data.Current %}
<p>컴퓨터: {{ data.Current.Computer }} | 사용자: {{ data.Current.User }} | 결과: {{ data.Current.Result }}!</p>
{% else %}
<p>조건에 맞는 값을 입력해 게임을 진행하세요.</p>
{% endif %}
<p></p>
<p>승리: {{ data.Statistic[0] }}회 | 패배: {{ data.Statistic[1] }}회 | 무승부: {{ data.Statistic[2] }}회</p>
<p></p>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">컴퓨터</th>
<th scope="col">사용자</th>
<th scope="col">결과</th>
</tr>
</thead>
<tbody>
{% for row in data.Results %}
<tr>
<th scope="row">{{ row.id }}</th>
<td>{{ row.computer }}</td>
<td>{{ row.user }}</td>
<td>{{ row.result }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
웹페이지를 보여주는 html 파일이다.
현재 실행했을 때
input으로 A 라는 값을 입력한 상태로 새로고침을 하면
해당 값이 초기화가 되지 않고 새로고침할 때마다 게임을 진행하고 데이터를 db에 저장하는 현상이 있는데
아직 해결하지 못한 상태이다.
해결하는대로 글을 작성하고자 한다.
'PYTHON' 카테고리의 다른 글
[TIL] 20240409 40일차 (0) | 2024.04.09 |
---|---|
[TIL] 20240408 39일차 (0) | 2024.04.08 |
[TIL] 20240228 12일차 (0) | 2024.02.28 |
[TIL] 20240227 11일차 (1) | 2024.02.27 |
[TIL] 20240226 10일차 (1) | 2024.02.26 |