Compare commits

...
17 Commits
Author SHA1 Message Date
engertda83421 f554f503c9 add presentation 2023-06-22 13:58:30 +02:00
engertda83421 ad2eea06e5 final version of 1,2 or 3 2023-06-22 09:41:54 +02:00
engertda83421 ddea6ea320 camera detection for correct field 2023-06-16 19:20:29 +02:00
engertda83421 4524a0a32b Renew camera detection 2023-06-10 11:10:33 +02:00
caliskan 27039171cf Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/caliskanbi83990/1_2_oder_3_repos 2023-05-29 23:52:19 +02:00
caliskan bea98333d8 [FrontEnd new files added] 2023-05-29 23:52:08 +02:00
engertda83421 2462c7474f Add detected colors in correct field to scoreboard 2023-05-26 20:42:28 +02:00
engertda83421 e8e368cad7 delete unused files 2023-05-26 19:57:31 +02:00
engertda83421 694062420d shuffle answeroptions and show final results desc 2023-05-26 19:55:32 +02:00
bachiriyo84019 f1759641d1 erste test für initial commit 2023-05-26 09:02:31 +02:00
engertda83421 beab4b0111 change scoreboard and question 2023-05-23 19:14:00 +02:00
engertda83421 60b02019e2 add functions for shuffle questions and return the correct field 2023-05-22 20:43:51 +02:00
caliskanbi c3367fad31 new files added 2023-05-19 18:00:38 +02:00
engertda83421 965624ca7a Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/caliskanbi83990/1_2_oder_3_repos 2023-05-19 10:02:36 +02:00
engertda83421 a83d5f045f Update. Add game and router 2023-05-19 10:02:29 +02:00
engertda83421 cdfdf0b78a Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/caliskanbi83990/1_2_oder_3_repos 2023-05-18 12:48:18 +02:00
engertda83421 ea1f8e399f corrected 2023-05-18 12:47:56 +02:00
23 changed files with 471 additions and 117 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

+14 -13
View File
@@ -19,7 +19,7 @@
height: 200px;
border-radius: 20px;
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-color: transparent;
@@ -33,7 +33,7 @@
margin-top: -15px;
border-radius: 5px;
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: 2px;
box-shadow: 1px 1px black;
@@ -59,7 +59,7 @@
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;
@@ -68,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;
@@ -117,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;
@@ -138,10 +138,11 @@
max-width: 600px;;
height: 300px;
margin-left: 110px;
}
.Answer {
}
.AnswerBox {
margin-left: 6px;
position: relative;
@@ -151,7 +152,7 @@
border: solid 2px;
border-radius: 20px;
box-shadow: 5px 5px black;
background-color: white;;
background-color: white;
}
@@ -160,7 +161,7 @@
}
#secondans {
border: solid 5px #fba51b;
border: solid 5px #72FF50;
}
#thirdans {
@@ -219,7 +220,7 @@
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;
@@ -229,14 +230,14 @@
}
#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 */
}
+34 -3
View File
@@ -2,14 +2,31 @@ import { useEffect, useState} from "react";
import './App.css';
import Header from "./components/Header";
import Body from "./components/Body";
import question from "./components/Question";
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) {
@@ -18,6 +35,8 @@ function App() {
}, 10);}
else if (timeLeft === 0) {
alert("Zeit ist um !");
showcorrect();
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
setTimerRunning(false);
setTimeLeft(10);
}
@@ -30,14 +49,20 @@ function App() {
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);
}
}
@@ -47,8 +72,14 @@ function App() {
}
return (<>
<Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount}/>
<Body startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize} teamsize={teamsize}/>
<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">Jemand anderen doppelt ... </div>
<div className="AnswerBox" id="secondans">Ronaldo >>> Messi</div>
<div className="AnswerBox" id="thirdans">I got right foot ...</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({startQuestion, timerRunning, stopTimer, setQuestionCount, setTeamSize, teamsize}) {
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 startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize}/>
<Answers/>
<ScoreBoard teamsize={teamsize}/>
<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>
)
}
@@ -2,8 +2,10 @@ import React, {useState} from "react";
import StartButton from "./StartButton";
import QuitButton from "./QuitButton";
import TeamSizePopUp from "./TeamsizePopUp";
import {getReset, getScoreboard} from "./api";
function Buttons({startQuestion, timerRunning, stopTimer, setQuestionCount, setTeamSize}) {
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)
@@ -26,6 +28,9 @@ function Buttons({startQuestion, timerRunning, stopTimer, setQuestionCount, setT
changeGame(false);
stopTimer();
setQuestionCount(0);
getReset(setAns1, setAns2, setAns3, setQuestion);
alert("Spiel abgebrochen !");
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
}
@@ -2,11 +2,11 @@ import React from "react";
import Heading from "./Heading";
import Timer from "./Timer";
import Question from "./Question";
function Header({timerRunning, timerContent, questionCount}) {
function Header({timerRunning, timerContent, questionCount, question}) {
return(
<header className="Header">
<Heading/>
<Question questionCount={questionCount}/>
<Question questionCount={questionCount} question={question}/>
<Timer timerRunning={timerRunning} timerContent={timerContent}/>
</header>
)
@@ -1,13 +1,13 @@
import React from "react";
function Question({questionCount}) {
function Question({questionCount, question}) {
return(
<div className="HeaderDiv">
<div id="QuestionHeaderDiv">
<h2 id="QuestionHeader">{questionCount ? questionCount + ".Frage" : "Fragen"}</h2>
</div>
<div id="QuestionDiv">
<h2 id="Question">Warum ist Kerem so schrott ? </h2>
<h2 id="Question">{question}</h2>
</div>
</div>
)
@@ -1,6 +1,6 @@
import React from "react";
function ScoreBoard({teamsize}) {
function ScoreBoard({teamsize, scoreblue, scoregreen, scorered}) {
return(
<div className={"ScoreBoard"}>
<div>
@@ -16,15 +16,15 @@ function ScoreBoard({teamsize}) {
<tbody>
<tr>
<td>Red</td>
<td id="red-points">0</td>
<td id="red-points">{scorered}</td>
</tr>
<tr>
<td>Yellow</td>
<td id="yellow-points">0</td>
<td>Green</td>
<td id="yellow-points">{scoregreen}</td>
</tr>
<tr>
<td>Blue</td>
<td id="blue-points">0</td>
<td id="blue-points">{scoreblue}</td>
</tr>
</tbody>
@@ -15,19 +15,20 @@ function TeamSizePopUp({closeModal, changeGameState, startQuestion, setTeamSize}
}
const TeamSizeButtonClicked = () => {
if(inputValue <= 2 && inputValue > 0){
/*
postTeamsize({
"Teamsize": inputValue
}).then(data => console.log("Received answer" + data))
*/
setTeamSize(inputValue)
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 2 eingeben ! ")
alert("Bitte Zahl zwischen 1 und 3 eingeben ! ")
}
}
@@ -40,7 +41,7 @@ function TeamSizePopUp({closeModal, changeGameState, startQuestion, setTeamSize}
<h2>Bitte Teamgröße wählen </h2>
</div>
<div>
<input type="number" id="TeamSizeInput" min={1} max={2} value={inputValue}
<input type="number" id="TeamSizeInput" min={1} max={3} value={inputValue}
onChange={getInput}/>
</div>
<div>
+37 -15
View File
@@ -1,31 +1,53 @@
import {createContext} from "react";
export function postTeamsize(data) {
return fetch("URL:PORT/TEAMSIZE",{
methods: 'POST',
const requestOptions = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
'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 getQuestionandPrint() {
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() {
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() {
export function getReset(setAns1, setAns2, setAns3, setQuestion) {
setAns1('?');
setAns2('?');
setAns3('?');
setQuestion('?');
return fetch("http://192.168.0.94:5555/reset")
}
+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