Compare commits

...
15 Commits
29 changed files with 707 additions and 144 deletions

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
Bilal IP : 192.168.50.130
Bilal: 192.168.50.130
Youssef: 192.168.50.226
David: 192.168.50.79
@@ -0,0 +1,44 @@
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
def nothing(x):
pass
cv2.namedWindow("Trackbars")
cv2.createTrackbar("L - H", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("L - V", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("U - H", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U - S", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U - V", "Trackbars", 255, 255, nothing)
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (640, 480))
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
l_h = cv2.getTrackbarPos("L - H", "Trackbars")
l_s = cv2.getTrackbarPos("L - S", "Trackbars")
l_v = cv2.getTrackbarPos("L - V", "Trackbars")
u_h = cv2.getTrackbarPos("U - H", "Trackbars")
u_s = cv2.getTrackbarPos("U - S", "Trackbars")
u_v = cv2.getTrackbarPos("U - V", "Trackbars")
lower_range = np.array([l_h, l_s, l_v])
upper_range = np.array([u_h, u_s, u_v])
mask = cv2.inRange(hsv, lower_range, upper_range)
result = cv2.bitwise_and(frame, frame, mask=mask)
# show thresholded image
cv2.imshow("mask", mask)
cv2.imshow("result", result)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
+11 -21
View File
@@ -3,7 +3,7 @@ import pandas as pd
from sqlite3 import Error
questions = [('Wie heißt der längst Fluss auf der Welt?', 'Amazonas', 'Nil', 'Jangtsekiang', 'Nil'),
questions = [('Wie heißt der längste Fluss auf der Welt?', 'Amazonas', 'Nil', 'Jangtsekiang', 'Nil'),
('Aus welcher englischen Stadt stammt die Musikgruppe die Beatles?', 'London', 'Sheffield', 'Liverpool', 'Liverpool'),
('Zu welchem Land gehört Grönland?', 'Norwegen', 'Island', 'Dänemark', 'Dänemark'),
('Wie heißen die ursprünglichen Bewohner Australiens?', 'Aborigines', 'Eingeborene', 'Australian Natives', 'Aborigines'),
@@ -16,7 +16,7 @@ questions = [('Wie heißt der längst Fluss auf der Welt?', 'Amazonas', 'Nil', '
('Wie heißt der höchste Berg Europas?', 'Zugspitze', 'Matterhorn', 'Montblanc', 'Montblanc'),
('Wie lange braucht das Licht in etwa von der Sonne zur Erde?', '80 Sekunden', '8 Minuten', '7 Tage', '8 Minuten'),
('Was hat James Watt erfunden?', 'Glühbirne', 'Elektrischen Widerstand', 'Dampfmaschine', 'Dampfmaschine'),
('Wie hieß der erste Deutsch Bundeskanzler?', 'Helmut Schmidt', 'Konrad Adenauer', 'Willy Brandt', 'Konrad Adenauer'),
('Wie hieß der erste Deutsche Bundeskanzler?', 'Helmut Schmidt', 'Konrad Adenauer', 'Willy Brandt', 'Konrad Adenauer'),
('Von wem stammt das Gemälde der Mona Lisa?', 'Picasso', 'Vincent van Gogh', 'Leonardo da Vinci', 'Leonardo da Vinci'),
('Wie heißt der Erfinder der Jeanshose?', 'Tom Wrangler', 'Levi Strauss', 'Peter Diesel', 'Levi Strauss'),
('Welches Land gewann 2014 die Fußball Weltmeisterschaft?', 'Brasilien', 'Argentien', 'Deutschland', 'Deutschland'),
@@ -29,7 +29,7 @@ class QuestionDataBase:
def __init__(self, file_name) -> None:
self.file_name = file_name
try:
self.connection = sqlite3.connect(database=self.file_name)
self.connection = sqlite3.connect(database=self.file_name, check_same_thread=False)
print(f'Successfully connected to SQLite (Version: ' + sqlite3.version + ')..\n')
except Error as err:
print(err)
@@ -45,14 +45,13 @@ class QuestionDataBase:
def create_table(self):
table_config = "CREATE TABLE IF NOT EXISTS Questions" \
"(QuestionNr TEXT PRIMARY KEY," \
" Answeroption_1 \nTEXT," \
" Answeroption_2 TEXT," \
" Answeroption_3 TEXT," \
" Correct_answeroption TEXT)"
"Answeroption_1 \nTEXT," \
"Answeroption_2 TEXT," \
"Answeroption_3 TEXT," \
"Correct_answeroption TEXT)"
self.cursor.execute(table_config)
print("Successfully create tables.. ")
def insert_table(self, questions: list):
self.cursor.executemany("INSERT OR IGNORE INTO Questions VALUES (?, ?, ?, ?, ?)", questions)
print("Successfully insert data into table.")
@@ -61,12 +60,10 @@ class QuestionDataBase:
self.cursor.execute("SELECT COUNT(*) FROM Questions")
return self.cursor.fetchone()[0]
def delete_data(self, table_name):
self.cursor.execute(f"DELETE FROM {table_name}")
def read_question_data(self, file_name: str):
def read_question_data(self, file_name: str) -> pd.DataFrame:
try:
data = pd.read_csv(file_name, delimiter=';')
except Error as err:
@@ -74,16 +71,9 @@ class QuestionDataBase:
print(err)
return data
## ToDO: get question, return type(dict)
def get_questions():
pass
if __name__ == "__main__":
database = QuestionDataBase('Project/BackEnd/Database/EinsZweiOderDrei.db')
insert_table = database.insert_table(questions)
if __name__ == "__main__":
database = QuestionDataBase('src_folder/BackEnd/Database/EinsZweiOderDrei.db')
insert_table = database.insert_table(questions)
database.commit()
database.close_connection()
+21 -21
View File
@@ -1,21 +1,21 @@
Question, Answer1, Answer2, Answer3, Right Answer
('Wie heißt der längst Fluss auf der Welt?', 'Amazonas', 'Nil', 'Jangtsekiang', 'Nil'),
('Aus welcher englischen Stadt stammt die Musikgruppe die Beatles?', 'London', 'Sheffield', 'Liverpool', 'Liverpool'),
('Zu welchem Land gehört Grönland?', 'Norwegen', 'Island', 'Dänemark', 'Dänemark'),
('Wie heißen die ursprünglichen Bewohner Australiens?', 'Aborigines', 'Eingeborene', 'Australian Natives', 'Aborigines'),
('Mit welchem Korn verglich Jesus das Reich Gottes?', 'Senfkorn', 'Weizenkorn', 'Haferkorn', 'Senfkorn'),
('Wie lange können Kaiserpinguine tauchen?', '5min', '10min', '20min', '20min'),
('Wer war der Kommandant der Apollo 11?', 'Louis Armstrong', 'Neil Armstrong', 'Lance Armstrong', 'Neil Armstrong'),
('Wie heißt die größte Stadt der Welt (nach Einwohnern)?', 'São Paulo', 'Tokio', 'Seoul', 'Tokio',),
('In welchem Land liegt Helsinki?', 'Finnland', 'Norwegen', 'Schweden', 'Finnland'),
('Wie viele Bundesländer hat Deutschland?', '16', '17', '20', '16'),
('Wie heißt der höchste Berg Europas?', 'Zugspitze', 'Matterhorn', 'Montblanc', 'Montblanc'),
('Wie lange braucht das Licht in etwa von der Sonne zur Erde?', '80 Sekunden', '8 Minuten', '7 Tage', '8 Minuten'),
('Was hat James Watt erfunden?', 'Glühbirne', 'Elektrischen Widerstand', 'Dampfmaschine', 'Dampfmaschine'),
('Wie hieß der erste Deutsch Bundeskanzler?', 'Helmut Schmidt', 'Konrad Adenauer', 'Willy Brandt', 'Konrad Adenauer'),
('Von wem stammt das Gemälde der Mona Lisa?', 'Picasso', 'Vincent van Gogh', 'Leonardo da Vinci', 'Leonardo da Vinci'),
('Wie heißt der Erfinder der Jeanshose?', 'Tom Wrangler', 'Levi Strauss', 'Peter Diesel', 'Levi Strauss'),
('Welches Land gewann 2014 die Fußball Weltmeisterschaft?', 'Brasilien', 'Argentien', 'Deutschland', 'Deutschland'),
('Welcher ist der "rote Planet" unseres Sonnensystems?', 'Mars', 'Venus', 'Jupiter', 'Mars'),
('Was bezeichnet die chemische Formel \'NaCl\'?', 'Kochsalz', 'Wasser', 'Stickstoff'),
('Welche Form hat die Narbe auf Harry Potters Stirn?', 'Dreieck', 'Blitz', 'Kreuz', 'Blitz')
QuestionNr, Answeroption_1, Answeroption_2, Answeroption_3, Correct_answeroption;
Wie heißt der längst Fluss auf der Welt?, Amazonas, Nil, Jangtsekiang, Nil;
Aus welcher englischen Stadt stammt die Musikgruppe die Beatles?, London, Sheffield, Liverpool, Liverpool;
Zu welchem Land gehört Grönland?, Norwegen, Island, Dänemark, Dänemark
Wie heißen die ursprünglichen Bewohner Australiens?, Aborigines, Eingeborene, Australian Natives, Aborigines
Mit welchem Korn verglich Jesus das Reich Gottes?, Senfkorn, Weizenkorn, Haferkorn, Senfkorn
Wie lange können Kaiserpinguine tauchen?, 5min, 10min, 20min, 20min
Wer war der Kommandant der Apollo 11?, Louis Armstrong, Neil Armstrong, Lance Armstrong, Neil Armstrong
Wie heißt die größte Stadt der Welt (nach Einwohnern)?, São Paulo, Tokio, Seoul, Tokio
In welchem Land liegt Helsinki?, Finnland, Norwegen, Schweden, Finnland
Wie viele Bundesländer hat Deutschland?, 16, 17, 20, 16
Wie heißt der höchste Berg Europas?, Zugspitze, Matterhorn, Montblanc, Montblanc
Wie lange braucht das Licht in etwa von der Sonne zur Erde?, 80 Sekunden, 8 Minuten, 7 Tage, 8 Minuten
Was hat James Watt erfunden?, Glühbirne, Elektrischen Widerstand, Dampfmaschine, Dampfmaschine
Wie hieß der erste Deutsch Bundeskanzler?, Helmut Schmidt, Konrad Adenauer, Willy Brandt, Konrad Adenauer
Von wem stammt das Gemälde der Mona Lisa?, Picasso, Vincent van Gogh, Leonardo da Vinci, Leonardo da Vinci
Wie heißt der Erfinder der Jeanshose?, Tom Wrangler, Levi Strauss, Peter Diesel, Levi Strauss;
Welches Land gewann 2014 die Fußball Weltmeisterschaft?, Brasilien, Argentien, Deutschland, Deutschland;
Welcher ist der "rote Planet" unseres Sonnensystems?, Mars, Venus', Jupiter, Mars;
Was bezeichnet die chemische Formel 'NaCl'?, Kochsalz, Wasser, Stickstoff, Kochsalz;
Welche Form hat die Narbe auf Harry Potters Stirn?, Dreieck, Blitz, Kreuz, Blitz;
+129
View File
@@ -0,0 +1,129 @@
import cv2
import numpy as np
import pandas as pd
class Camera():
def __init__(self) -> None:
self.colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
self.color_names = ["Rot", "Gruen", "Blau"]
self.lower_red = np.array([0, 185, 15])
self.upper_red = np.array([50, 255, 255])
self.lower_green = np.array([20, 70, 25])
self.upper_green = np.array([65, 200, 255])
self.lower_blue = np.array([100, 220, 5])
self.upper_blue = np.array([255, 255, 255])
self.video = cv2.VideoCapture(0)
self.start_process = True
self.correct_field_frame = 0
self.mean_error = []
self.scores = {'score_red': 0,
'score_green': 0,
'score_blue': 0
}
def get_frame(self):
try:
_, self.image = self.video.read(0)
except Exception as err:
print("Can not capture the video..\n")
print(err)
return self.image
def take_picture(self):
path = 'src_folder/Game_Images/'
file_name = 'current_score.png'
image_path = path+file_name
cv2.imwrite(image_path, self.image)
def detect_color(self, image):
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
count_red, count_green, count_blue= 0,0,0
for i, color in enumerate(self.colors):
if i == 0:
lower = self.lower_red
upper = self.upper_red
elif i == 1:
lower = self.lower_green
upper = self.upper_green
elif i == 2:
lower = self.lower_blue
upper = self.upper_blue
mask = cv2.inRange(hsv_img, lower, upper)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if 100 < cv2.contourArea(contour):
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, self.color_names[i], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
if i == 0:
count_red += 1
elif i == 1:
count_green += 1
elif i == 2:
count_blue += 1
self.scores['score_red'] = count_red
self.scores['score_green'] = count_green
self.scores['score_blue'] = count_blue
def current_score(self, scores: dict):
return scores
def range_of_interest(self, frame, correct_field: int):
num_windows_in_y = 1
num_windows_in_x = 3
height, width, _ = frame.shape
roi_height = height/num_windows_in_y
roi_width = width/num_windows_in_x
images = []
for x in range(0,num_windows_in_y):
for y in range(0,num_windows_in_x):
tmp_image=frame[int(x*roi_height):int((x+1)*roi_height), int(y*roi_width):int((y+1)*roi_width)]
images.append(tmp_image)
correct_field_frame = images[correct_field]
return correct_field_frame
def reduce_errors(self, mean_error_list: list):
for team_color in self.current_score.keys():
df = pd.DataFrame(mean_error_list)
total = df[team_color].sum()
number_of_rows = len(df.index)
error = total/number_of_rows
self.current_score[team_color] = round(error)
def process(self):
square_error = []
for i in range(0,100):
frame = self.get_frame()
interested_area = self.range_of_interest(frame, self.correct_field_frame)
self.detect_color(interested_area)
cv2.line(img=frame, pt1=(frame.shape[1]//3, 0), pt2=(frame.shape[1]//3, frame.shape[0]), color=(0, 0, 0), thickness=2)
cv2.line(img=frame, pt1=(2 * frame.shape[1]//3, 0), pt2=(2 * frame.shape[1]//3, frame.shape[0]), color=(0, 0, 0), thickness=2)
cv2.imshow("Kamera 1,2 oder 3", frame)
square_error.append(self.scores)
self.take_picture()
print(f'{i}. Iteration scores: {self.scores}')
self.start_process = False
# nur zum testen: my_camera.start_process auf True setzen und correct_field_frame zwischen 1 und 3 wählen
# if __name__ == "__main__":
# my_camera = Camera()
# my_camera.process()
View File
Whitespace-only changes.
+74
View File
@@ -0,0 +1,74 @@
from Database.database import QuestionDataBase
import random
class Game:
def __init__(self, teamsize=0, correct_field=0):
self.teamsize = teamsize
self.scoreboard = {'score_red': 0,
'score_green': 0,
'score_blue': 0
}
self.questions = QuestionDataBase('src_folder/BackEnd/Database/EinsZweiOderDrei.db')
self.available_questions = list(range(1, self.questions.num_rows()))
self.field = correct_field
self.question = {}
self.final_score = {}
def set_teamsize(self, teamsize: int):
self.teamsize = teamsize
def add_score(self, current_score: dict) -> dict:
for key in self.scoreboard.keys():
if key in current_score.keys():
self.scoreboard[key] = self.scoreboard[key] + current_score[key]
return self.scoreboard
def set_scoreboard(self, current_scores: dict) -> dict:
self.scoreboard = self.add_score(current_scores)
return self.scoreboard
def reset_game(self):
self.scoreboard = {'score_red': 0,
'score_green': 0,
'score_blue': 0
}
def get_question(self):
questions = self.questions.cursor.execute("Select * from Questions")
field_names = [i[0] for i in questions.description]
questions_data = questions.fetchall()
random_question_number = random.choice(self.available_questions)
self.available_questions.remove(random_question_number)
question= list(questions_data[random_question_number])
self.question = dict(zip(field_names, question))
self.shuffle_answeroptions()
self.add_correct_field()
def shuffle_answeroptions(self):
answeroptions = ['Answeroption_1', 'Answeroption_2', 'Answeroption_3']
keys = []
for answer in answeroptions:
keys.append(self.question[answer])
random.shuffle(keys)
for index, answer in enumerate(answeroptions):
self.question[answer] = keys[index]
def add_correct_field(self):
answeroption = ['Answeroption_1', 'Answeroption_2', 'Answeroption_3', 'Correct_answeroption']
for i in range(0, len(answeroption) -1):
if self.question[answeroption[-1]] == self.question[answeroption[i]]:
index = answeroption.index(answeroption[i]) + 1
self.set_correct_field(index)
break
self.question.update([('Correct_field', index)])
def set_correct_field(self, correct_field: int):
self.field = correct_field
def final_result(self):
self.final_score = dict(sorted(self.scoreboard.items(), key=lambda x: x[1], reverse=True))
+62
View File
@@ -0,0 +1,62 @@
from flask import Flask, jsonify, Response, request
from camera import Camera
from game import Game
app = Flask(__name__)
my_game = Game()
my_camera = Camera()
@app.route('/question', methods=['GET'])
def get_question():
my_game.get_question()
print(my_game.question)
return jsonify(my_game.question)
@app.route('/teamsize', methods=['POST'])
def teamsize():
team_size = request.json
my_game.set_teamsize(team_size.get('teamsize'))
print(f'Teamsize: {my_game.teamsize}\n')
return Response(status=200)
@app.route('/scoreboard', methods=['GET'])
def scoreboard():
print(my_game.scoreboard)
return jsonify(my_game.scoreboard)
@app.route('/check', methods=['GET'])
def check():
my_camera.start_process = True
my_camera.correct_field_frame = my_game.field
my_camera.process()
my_game.set_scoreboard(my_camera.scores)
my_camera.start_process = False
return jsonify(my_game.scoreboard)
@app.route('/reset', methods=['GET'])
def reset():
my_game.reset_game()
return Response(status=200)
@app.route('/scores', methods=['POST'])
def get_scores():
scores = request.json
my_game.add_score(scores)
return Response(status=200)
@app.route('/winner', methods=['GET'])
def set_winner():
my_game.final_result()
return jsonify(my_game.final_score)
def main():
## Router
app.run(host='192.168.50.79', port=5555, debug=True)
## Postman
# app.run(host='127.0.0.1', port=5555, debug=True)
if __name__ == '__main__':
main()
-15
View File
@@ -1,15 +0,0 @@
from flask import Flask, jsonify, Response
app = Flask(__name__)
@app.route('/CONNECTION', methods=['GET'])
def connection():
return Response(status=200)
def main():
app.run(host='127.0.0.1', port=5555, debug=True)
if __name__ == '__main__':
main()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 24 KiB

+3 -1
View File
@@ -5,7 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app"/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
<title>1_2_oder3</title>
</head>
<body>
+82 -32
View File
@@ -2,7 +2,9 @@
.PopUpBackground {
width: 100vw;
height: 100vh;
background-color: rgba(200, 200, 200, 200);
background-color: rgba(255, 255, 255, 0.5);
backdrop-filter: blur(10px);
background-size: 100%;
position: absolute;
display: flex;
justify-content: center;
@@ -14,9 +16,30 @@
.PopUpContainer {
width: 500px;
height: 500px;
height: 200px;
border-radius: 20px;
background-color: white;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 5px;
border-color: transparent;
box-shadow: 5px 5px black;
}
#Cancel {
margin-left: 470px;
padding-left: 5px;
padding-right: 5px;
margin-top: -15px;
border-radius: 5px;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 2px;
box-shadow: 1px 1px black;
border-color: transparent;
position: fixed;
cursor: pointer;
}
@@ -31,12 +54,12 @@
.HeaderDiv {
margin-left: 50px;
text-align: center;
max-width: 1000px;
max-width: 600px;
width: 100%;
padding: 10px;
box-shadow: 5px 5px black;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #fba51b 50%, #3b5da4 100%) border-box;
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 5px;
border-radius: 20px;
@@ -45,7 +68,7 @@
.TimerDiv {
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #fba51b 50%, #3b5da4 100%) border-box;
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 5px;
border-radius: 20px;
@@ -56,15 +79,14 @@
}
#TimerPic {
visibility: hidden;
}
#Seconds {
visibility: hidden;
border: solid 2px black;
border-radius: 10px;
padding: 2px;
}
#QuestionHeaderDiv {
background-color: white;
border: solid #0C134F 2px;
@@ -76,6 +98,7 @@
#QuestionHeader {
color: #0C134F;
}
#QuestionDiv {
background-color: white;
border: solid #0C134F 2px;
@@ -84,6 +107,7 @@
box-shadow: 2px 2px black;
}
#Question {
color: black;
}
@@ -93,7 +117,7 @@
height: auto;
padding: 10px ;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #fba51b 50%, #3b5da4 100%) border-box;
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 5px;
border-radius: 20px;
@@ -102,47 +126,51 @@
cursor: pointer;
}
#headingimage:hover {
background-color: #F6F6F6;
}
.Body{
text-align: center;
}
.Answers {
padding: 10px;
float: left;
padding: 10px;
width: 100%;
max-width: 1000px;;
height: 500px;
margin-left: 80px;
max-width: 600px;;
height: 300px;
margin-left: 110px;
}
.Answer {
}
.AnswerBox {
margin-left: 6px;
position: relative;
height: 500px;
width: 32%;
height: 300px;
width: 30%;
float: left;
border: solid 2px;
border-radius: 20px;
box-shadow: 5px 5px black;
background-color: white;
}
#firstans {
border: solid 2px #a10012;
border: solid 5px #a10012;
}
#secondans {
border: solid 2px #fba51b;
border: solid 5px #72FF50;
}
#thirdans {
border: solid 2px #3b5da4;
border: solid 5px #3b5da4;
}
.Buttons {
float: left;
max-width: 250px;
max-width: 220px;
padding-top: 10px;
padding-left: 30px;
}
@@ -159,14 +187,40 @@
cursor: pointer;
}
#TeamSizeInput {
margin-left: 70px;
float: left;
margin-right: -50px;
padding: 7px;
border-radius: 6px;
font-size: 16px;
background: #fbfbfb;
border: 2px solid transparent;
height: 36px;
box-shadow: 0 0 0 1px #dddddd, 0 2px 4px 0 rgb(0 0 0 / 7%), 0 1px 2px 0 rgb(0 0 0 / 5%);
}
#TeamSizeInput:focus {
border: 2px solid #000;
border-radius: 4px;
}
#PopUpButton {
position: relative;
margin-top: 5px;
font-size: 16px;
background-color: #4CAF50;
}
.ScoreBoard {
float: left;
padding: 10px;
width: 100px;
height: 500px;
margin-left: 40px;
height: 300px;
margin-left: 50px;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #a10012 0%, #fba51b 50%, #3b5da4 100%) border-box;
linear-gradient(to right, #a10012 0%, #72FF50 50%, #3b5da4 100%) border-box;
border-style: solid;
border-width: 5px;
border-radius: 20px;
@@ -176,19 +230,15 @@
}
#StartButton {
background-color: #4CAF50;
background-color: #ff863d;
}
#QuitButton {
background-color: red;
}
.MyButton:hover {
background-color: #3E8E41; /* darker shade of green */
#StartButton:hover {
background-color: #ae572e; /* darker shade of green */
}
#QuitButton {
visibility: hidden;
}
+75 -2
View File
@@ -2,11 +2,84 @@ import { useEffect, useState} from "react";
import './App.css';
import Header from "./components/Header";
import Body from "./components/Body";
import {getQuestion, getScoreboard, getReset} from "./components/api";
function App() {
const [timeLeft, setTimeLeft] = useState(10*1000);
const [question, setQuestion] = useState('?')
const [ans1, setAns1] = useState('?')
const [ans2, setAns2] = useState('?')
const [ans3, setAns3] = useState('?')
const [correctans, setCorrectAns] = useState()
const [correctfield, setCorrectField] = useState()
const [scoreblue, setScoreBlue] = useState()
const [scoregreen, setScoreGreen] = useState()
const [scorered, setScoreRed] = useState()
const [timerRunning, setTimerRunning] = useState(false);
const [questionCount, setQuestionCount] = useState(0);
const [teamsize, setTeamSize] = useState(0);
useEffect(() => {
// This function will be executed when the component is loaded
getReset(setAns1, setAns2, setAns3, setQuestion);
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
}, []);
useEffect(() => {
let timer;
if (timerRunning && timeLeft > 0) {
timer = setTimeout(() => {
setTimeLeft(timeLeft-10);
}, 10);}
else if (timeLeft === 0) {
alert("Zeit ist um !");
showcorrect();
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
setTimerRunning(false);
setTimeLeft(10);
}
return () => clearTimeout(timer);
}, [timeLeft, timerRunning]);
function formatTime(time) {
const seconds = Math.floor((time / 1000) % 60).toString().padStart(2, '0');
return `${seconds} s`;
}
const showcorrect = () => {
alert("Richtiges Feld: " + correctfield + "\nRichtige Antwort: " + correctans)
}
const startQuestion = () => {
if (questionCount <= 5){
setQuestionCount(questionCount+1)
getQuestion(setAns1, setAns2, setAns3, setQuestion, setCorrectField, setCorrectAns).then(r => console.log(r))
setTimeLeft(10*1000);
setTimerRunning(true);
}
else {
alert("Spiel vorbei !");
getReset(setAns1, setAns2, setAns3, setQuestion);
}
}
const stopTimer = () => {
setTimerRunning(false)
setTimeLeft(10*1000);
}
return (<>
<Header/>
<Body/>
<Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount} question={question}/>
<Body startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount}
setTeamSize={setTeamSize} teamsize={teamsize}
ans2={ans2} ans3={ans3} ans1={ans1}
scoreblue={scoreblue} scorered={scorered} scoregreen={scoregreen}
setScoreGreen={setScoreGreen} setScoreRed={setScoreRed} setScoreBlue={setScoreBlue}
setAns3={setAns3} setAns1={setAns1} setAns2={setAns2} setQuestion={setQuestion}
/>
</>
);
}
@@ -1,11 +1,17 @@
import React from "react";
function Answers() {
function Answers({ans1, ans2, ans3}) {
return(
<div className="Answers">
<div className="AnswerBox" id="firstans">AnswerBox1 </div>
<div className="AnswerBox" id="secondans">AnswerBox2</div>
<div className="AnswerBox" id="thirdans">AnswerBox3</div>
<div className="AnswerBox" id="firstans">
<div className="Answer">{ans1}</div>
</div>
<div className="AnswerBox" id="secondans">
<div className="Answer">{ans2}</div>
</div>
<div className="AnswerBox" id="thirdans">
<div className="Answer">{ans3}</div>
</div>
</div>
)
}
@@ -2,12 +2,16 @@ import React from "react";
import Buttons from "./Buttons";
import Answers from "./Answers";
import ScoreBoard from "./ScoreBoard";
function Body() {
function Body({startQuestion, timerRunning, stopTimer, setQuestionCount, setTeamSize, teamsize, ans1, ans2, ans3, scoreblue,
scoregreen, scorered, setScoreBlue, setScoreGreen, setScoreRed,
setAns1, setAns2, setAns3, setQuestion}) {
return(
<div className="Body">
<Buttons/>
<Answers/>
<ScoreBoard/>
<Buttons startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize}
setScoreGreen={setScoreGreen} setScoreRed={setScoreRed} setScoreBlue={setScoreBlue}
setAns1={setAns1} setAns2={setAns2} setAns3={setAns3} setQuestion={setQuestion}/>
<Answers ans3={ans3} ans2={ans2} ans1={ans1}/>
<ScoreBoard teamsize={teamsize} scoreblue={scoreblue} scorered={scorered} scoregreen={scoregreen}/>
</div>
)
}
@@ -1,12 +1,51 @@
import React from "react";
import React, {useState} from "react";
import StartButton from "./StartButton";
import QuitButton from "./QuitButton";
function Buttons() {
import TeamSizePopUp from "./TeamsizePopUp";
import {getReset, getScoreboard} from "./api";
function Buttons({startQuestion, timerRunning, stopTimer, setQuestionCount, setTeamSize, setScoreBlue, setScoreGreen, setScoreRed,
setAns1, setAns2, setAns3, setQuestion}) {
const [gameStarted, setGameStarted] = useState(false)
const [openPopUp, setOpenPopUp] = useState(false)
const [quitvisible, setQuitvisible] = useState(false)
const changeGame = (bool) => {
setGameStarted(bool)
setQuitvisible(bool)
}
const startClicked = () => {
if(!timerRunning && !gameStarted) {
setOpenPopUp(true);
}
else if (!timerRunning && gameStarted) {
startQuestion();
}
}
const quitGame = () => {
changeGame(false);
stopTimer();
setQuestionCount(0);
getReset(setAns1, setAns2, setAns3, setQuestion);
alert("Spiel abgebrochen !");
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
}
return(
<div className="Buttons">
<StartButton/>
<QuitButton/>
<StartButton
onClick={startClicked}
content={(gameStarted) ? "Nächste Frage" : "Spiel Starten" }
/>
{quitvisible && <QuitButton quitGame={quitGame}/>}
{openPopUp && <TeamSizePopUp closeModal={setOpenPopUp}
changeGameState={changeGame}
startQuestion={startQuestion}
setTeamSize={setTeamSize}
/>}
</div>
)
}
@@ -2,12 +2,12 @@ import React from "react";
import Heading from "./Heading";
import Timer from "./Timer";
import Question from "./Question";
function Header() {
function Header({timerRunning, timerContent, questionCount, question}) {
return(
<header className="Header">
<Heading/>
<Question/>
<Timer/>
<Question questionCount={questionCount} question={question}/>
<Timer timerRunning={timerRunning} timerContent={timerContent}/>
</header>
)
}
@@ -1,9 +1,12 @@
import React from "react";
function Heading() {
const onClick = () => {
window.location.reload();
}
return(
<div className="Heading">
<img src={process.env.PUBLIC_URL + "12oder3-logo.png"} alt="1_2_oder_3" id="headingimage"/>
<img src={process.env.PUBLIC_URL + "12oder3-logo.png"} alt="1_2_oder_3" id="headingimage" onClick={onClick}/>
</div>
)
@@ -1,13 +1,13 @@
import React from "react";
function Question() {
function Question({questionCount, question}) {
return(
<div className="HeaderDiv">
<div id="QuestionHeaderDiv">
<h2 id="QuestionHeader">Frage:</h2>
<h2 id="QuestionHeader">{questionCount ? questionCount + ".Frage" : "Fragen"}</h2>
</div>
<div id="QuestionDiv">
<h2 id="Question">?</h2>
<h2 id="Question">{question}</h2>
</div>
</div>
)
@@ -1,7 +1,7 @@
import React from "react";
function QuitButton() {
function QuitButton({quitGame}) {
return(
<button className="MyButton" id="QuitButton">
<button className="MyButton" id="QuitButton" onClick={quitGame}>
Abbruch
</button>
)
@@ -1,7 +1,35 @@
import React from "react";
function ScoreBoard() {
return(<div className={"ScoreBoard"}>ScoreBoard</div>)
function ScoreBoard({teamsize, scoreblue, scoregreen, scorered}) {
return(
<div className={"ScoreBoard"}>
<div>
<p>Spieler pro Team: {teamsize ? teamsize : ""}</p>
</div>
<table>
<thead>
<tr>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>Red</td>
<td id="red-points">{scorered}</td>
</tr>
<tr>
<td>Green</td>
<td id="yellow-points">{scoregreen}</td>
</tr>
<tr>
<td>Blue</td>
<td id="blue-points">{scoreblue}</td>
</tr>
</tbody>
</table>
</div>)
}
export default ScoreBoard
@@ -1,19 +1,11 @@
import {useState} from "react";
import TeamSizePopUp from "./TeamsizePopUp";
function StartButton() {
const [openPopUp, setOpenPopUp] = useState(false)
function startclicked() {
setOpenPopUp(true);
}
function StartButton({onClick, content}) {
return(
<>
<button className="MyButton" id="StartButton" onClick={startclicked}>
Start Game
<button className="MyButton" id="StartButton" onClick={onClick}>
{content}
</button>
{openPopUp && <TeamSizePopUp closeModal={setOpenPopUp}/>}
</>
)
}
@@ -1,17 +1,52 @@
import React from "react";
import setTeamsize from "./data_functions";
import React, {useState} from "react";
import {postTeamsize} from "./api";
function TeamSizePopUp({closeModal}) {
function TeamSizePopUp({closeModal, changeGameState, startQuestion, setTeamSize}) {
function closePopUp() {
const [inputValue, setInputValue] = useState(2);
const getInput = (event) => {
setInputValue(event.target.value);
}
const closePopUp = () => {
closeModal(false);
}
const TeamSizeButtonClicked = () => {
if(inputValue <= 3 && inputValue > 0){
try {
console.log(typeof inputValue)
postTeamsize(inputValue).then(r => { if (r.ok) {console.log("OK")} });
setTeamSize(inputValue);
changeGameState(true);
closePopUp();
startQuestion();
} catch (error) {
console.error(error)
}
}
else {
alert("Bitte Zahl zwischen 1 und 3 eingeben ! ")
}
}
return (
<div className="PopUpBackground">
<div className="PopUpContainer">
<h2>Bitte Teamgröße wählen</h2>
<input type="number" id="TeamSizeInput"/>
<button className="MyButton" onClick={closePopUp}>Bestätigen</button>
<div>
<div id="Cancel" onClick={closePopUp}>X</div>
<h2>Bitte Teamgröße wählen </h2>
</div>
<div>
<input type="number" id="TeamSizeInput" min={1} max={3} value={inputValue}
onChange={getInput}/>
</div>
<div>
<button className="MyButton" id="PopUpButton" onClick={TeamSizeButtonClicked}>Bestätigen und Spiel starten</button>
</div>
</div>
</div>
)
@@ -1,10 +1,10 @@
import React from "react";
function Timer() {
function Timer({timerRunning, timerContent}) {
return(
<div className="TimerDiv">
<img src={process.env.PUBLIC_URL + "icons8-time.gif"} alt="timer" id="TimerPic"/>
<h2 id="Seconds">0:00 s</h2>
<h2 id="Seconds">{timerContent}</h2>
</div>
)
}
@@ -0,0 +1,53 @@
export function postTeamsize(data) {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({ teamsize: data})
}
return fetch("http://192.168.0.94:5555/teamsize", requestOptions)
}
export function getConnection() {
return 0
}
export function getQuestion(setAns1, setAns2, setAns3, setQuestion, setCorrectField, setCorrectAnsw) {
return fetch("http://192.168.0.94:5555/question")
.then(response => response.json())
.then(data => {
setQuestion(data.QuestionNr)
setAns1(data.Answeroption_1)
setAns2(data.Answeroption_2)
setAns3(data.Answeroption_3)
setCorrectField(data.Correct_field)
setCorrectAnsw(data.Correct_answeroption)
console.log(data)
})
.catch(error => console.error(error));
}
export function getScoreboard(setScoreBlue, setScoreGreen, setScoreRed) {
return fetch("http://192.168.0.94:5555/scoreboard")
.then(response => response.json())
.then(data => {
setScoreBlue(data.score_blue)
setScoreRed(data.score_red)
setScoreGreen(data.score_green)
})
.catch(error => console.error(error))
}
export function getCheck() {
}
export function getReset(setAns1, setAns2, setAns3, setQuestion) {
setAns1('?');
setAns2('?');
setAns3('?');
setQuestion('?');
return fetch("http://192.168.0.94:5555/reset")
}
@@ -1,6 +0,0 @@
let teamsize
function setTeamsize(_teamsize) {
teamsize = _teamsize;
}
export default setTeamsize
+1 -1
View File
@@ -1,6 +1,6 @@
body {
background-image: url("../public/17580.jpg");
background-size: 1920px;
background-size: cover;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB