Compare commits

...
6 Commits
20 changed files with 273 additions and 228 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 Youssef: 192.168.50.226
David: 192.168.50.79 David: 192.168.50.79
@@ -1,153 +0,0 @@
import cv2
import numpy as np
from game import Game
# from Track import nothing
# Farbwerte für die Erkennung (Beispiel: Rot, Grün, Blau)
colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
color_names = ["Rot", "Gruen", "Blau"]
# Farbgrenzen für die Erkennung
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])
lower_green = np.array([40, 100, 100])
upper_green = np.array([70, 255, 255])
lower_blue = np.array([90, 100, 100])
upper_blue = np.array([130, 255, 255])
CURRENT_SCORES= {'score_red': 0,
'score_green': 0,
'score_blue': 0
}
# Funktion zur Farberkennung
def erkennung_farben(img):
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
results = []
count_red = 0
count_green = 0
count_blue = 0
for i, color in enumerate(colors):
if i == 0:
lower = lower_red
upper = upper_red
elif i == 1:
lower = lower_green
upper = upper_green
elif i == 2:
lower = lower_blue
upper = upper_blue
mask = cv2.inRange(hsv_img, lower, upper)
# Farbfläche finden
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
center = None
count = 0
for contour in contours:
if count < 3:
if cv2.contourArea(contour) > 100:
# Schwerpunkt der Kontur berechnen
M = cv2.moments(contour)
if M["m00"] > 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
center = (cX, cY)
count += 1
# Rechteck zeichnen
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, color_names[i], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
# Farbanzahl erhöhen
if i == 0:
count_red += 1
elif i == 1:
count_green += 1
elif i == 2:
count_blue += 1
results.append(center)
return img, results, count_red, count_green, count_blue
# Funktion zur Positionsermittlung
def ermittle_position(results, img_width):
positions = []
for result in results:
if result is None:
position = "Nicht gefunden"
else:
x = result[0]
if x < img_width / 3:
position = "Rechts"
elif x < 2 * img_width / 3:
position = "Mitte"
else:
position = "Links"
positions.append(position)
return positions
def count_colors(red: int, green: int, blue: int) -> None:
currrent_scores = {'score_red': red,
'score_green': green,
'score_blue': blue
}
Game.set_scoreboard(currrent_scores)
# Hauptprogramm
if __name__ == "__main__":
# Videoquelle öffnen (kann auch eine Bilddatei sein)
video = cv2.VideoCapture(1) # Hier "0" für die Kamera verwenden
while True:
# Einzelbild von der Videoquelle lesen
ret, frame = video.read()
# Fehlerbehandlung, wenn kein Bild gelesen werden kann
if not ret:
break
# Farben erkennen
farben_img, ergebnisse, count_red, count_green, count_blue = erkennung_farben(frame)
# Add counted colours to the scoreboard in the correct field
count_colors(count_red, count_green, count_blue)
# Anzahl der Farben anzeigen
cv2.putText(farben_img, f"Rot: {count_red}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, colors[0], 2)
cv2.putText(farben_img, f"Gruen: {count_green}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, colors[1], 2)
cv2.putText(farben_img, f"Blau: {count_blue}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, colors[2], 2)
# Positionen ermitteln
img_width = frame.shape[1]
positionen = ermittle_position(ergebnisse, img_width)
# Positionen anzeigen
for i, position in enumerate(positionen):
cv2.putText(farben_img, f"{color_names[i]}: {position}", (10, 150 + 30 * i),
cv2.FONT_HERSHEY_SIMPLEX, 1, colors[i], 2)
# Linien zeichnen
cv2.line(farben_img, (img_width // 3, 0), (img_width // 3, frame.shape[0]), (0, 0, 0), 2)
cv2.line(farben_img, (2 * img_width // 3, 0), (2 * img_width // 3, frame.shape[0]), (0, 0, 0), 2)
# Bild anzeigen
cv2.imshow("Farberkennung", farben_img)
# Auf "q" drücken, um die Schleife zu beenden
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Videoquelle und Fenster schließen
video.release()
cv2.destroyAllWindows()
+1 -1
View File
@@ -1,7 +1,7 @@
import time
import numpy as np import numpy as np
import cv2 import cv2
cap = cv2.VideoCapture(0) cap = cv2.VideoCapture(0)
def nothing(x): def nothing(x):
+1 -1
View File
@@ -16,7 +16,7 @@ questions = [('Wie heißt der längste Fluss auf der Welt?', 'Amazonas', 'Nil',
('Wie heißt der höchste Berg Europas?', 'Zugspitze', 'Matterhorn', 'Montblanc', 'Montblanc'), ('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'), ('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'), ('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'), ('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'), ('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'), ('Welches Land gewann 2014 die Fußball Weltmeisterschaft?', 'Brasilien', 'Argentien', 'Deutschland', 'Deutschland'),
+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()
+3 -7
View File
@@ -2,6 +2,7 @@ from Database.database import QuestionDataBase
import random import random
class Game: class Game:
def __init__(self, teamsize=0, correct_field=0): def __init__(self, teamsize=0, correct_field=0):
self.teamsize = teamsize self.teamsize = teamsize
@@ -9,7 +10,6 @@ class Game:
'score_green': 0, 'score_green': 0,
'score_blue': 0 'score_blue': 0
} }
self.questions = QuestionDataBase('src_folder/BackEnd/Database/EinsZweiOderDrei.db') self.questions = QuestionDataBase('src_folder/BackEnd/Database/EinsZweiOderDrei.db')
self.available_questions = list(range(1, self.questions.num_rows())) self.available_questions = list(range(1, self.questions.num_rows()))
self.field = correct_field self.field = correct_field
@@ -19,13 +19,13 @@ class Game:
def set_teamsize(self, teamsize: int): def set_teamsize(self, teamsize: int):
self.teamsize = teamsize self.teamsize = teamsize
def add_score(self, current_score: dict): def add_score(self, current_score: dict) -> dict:
for key in self.scoreboard.keys(): for key in self.scoreboard.keys():
if key in current_score.keys(): if key in current_score.keys():
self.scoreboard[key] = self.scoreboard[key] + current_score[key] self.scoreboard[key] = self.scoreboard[key] + current_score[key]
return self.scoreboard return self.scoreboard
def set_scoreboard(self, current_scores: dict): def set_scoreboard(self, current_scores: dict) -> dict:
self.scoreboard = self.add_score(current_scores) self.scoreboard = self.add_score(current_scores)
return self.scoreboard return self.scoreboard
@@ -50,7 +50,6 @@ class Game:
def shuffle_answeroptions(self): def shuffle_answeroptions(self):
answeroptions = ['Answeroption_1', 'Answeroption_2', 'Answeroption_3'] answeroptions = ['Answeroption_1', 'Answeroption_2', 'Answeroption_3']
keys = [] keys = []
print(self.question)
for answer in answeroptions: for answer in answeroptions:
keys.append(self.question[answer]) keys.append(self.question[answer])
@@ -73,6 +72,3 @@ class Game:
def final_result(self): def final_result(self):
self.final_score = dict(sorted(self.scoreboard.items(), key=lambda x: x[1], reverse=True)) self.final_score = dict(sorted(self.scoreboard.items(), key=lambda x: x[1], reverse=True))
+10 -7
View File
@@ -1,9 +1,11 @@
from flask import Flask, jsonify, Response, request from flask import Flask, jsonify, Response, request
from camera import Camera
from game import Game from game import Game
app = Flask(__name__) app = Flask(__name__)
my_game = Game() my_game = Game()
my_camera = Camera()
@app.route('/question', methods=['GET']) @app.route('/question', methods=['GET'])
def get_question(): def get_question():
@@ -20,13 +22,17 @@ def teamsize():
@app.route('/scoreboard', methods=['GET']) @app.route('/scoreboard', methods=['GET'])
def scoreboard(): def scoreboard():
my_game.set_scoreboard()
print(my_game.scoreboard) print(my_game.scoreboard)
return jsonify(my_game.scoreboard) return jsonify(my_game.scoreboard)
@app.route('/check', methods=['GET']) @app.route('/check', methods=['GET'])
def check(): def check():
return my_game.scoreboard 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']) @app.route('/reset', methods=['GET'])
def reset(): def reset():
@@ -46,14 +52,11 @@ def set_winner():
def main(): def main():
## Router ## Router
# app.run(host='192.168.50.79', port=5555, debug=True) app.run(host='192.168.50.79', port=5555, debug=True)
## Postman ## Postman
app.run(host='127.0.0.1', port=5555, debug=True) # app.run(host='127.0.0.1', port=5555, debug=True)
if __name__ == '__main__': if __name__ == '__main__':
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; height: 200px;
border-radius: 20px; border-radius: 20px;
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 5px; border-width: 5px;
border-color: transparent; border-color: transparent;
@@ -33,7 +33,7 @@
margin-top: -15px; margin-top: -15px;
border-radius: 5px; border-radius: 5px;
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 2px; border-width: 2px;
box-shadow: 1px 1px black; box-shadow: 1px 1px black;
@@ -59,7 +59,7 @@
padding: 10px; padding: 10px;
box-shadow: 5px 5px black; box-shadow: 5px 5px black;
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 5px; border-width: 5px;
border-radius: 20px; border-radius: 20px;
@@ -68,7 +68,7 @@
.TimerDiv { .TimerDiv {
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 5px; border-width: 5px;
border-radius: 20px; border-radius: 20px;
@@ -117,7 +117,7 @@
height: auto; height: auto;
padding: 10px ; padding: 10px ;
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 5px; border-width: 5px;
border-radius: 20px; border-radius: 20px;
@@ -138,10 +138,11 @@
max-width: 600px;; max-width: 600px;;
height: 300px; height: 300px;
margin-left: 110px; margin-left: 110px;
} }
.Answer {
}
.AnswerBox { .AnswerBox {
margin-left: 6px; margin-left: 6px;
position: relative; position: relative;
@@ -151,7 +152,7 @@
border: solid 2px; border: solid 2px;
border-radius: 20px; border-radius: 20px;
box-shadow: 5px 5px black; box-shadow: 5px 5px black;
background-color: white;; background-color: white;
} }
@@ -160,7 +161,7 @@
} }
#secondans { #secondans {
border: solid 5px #fba51b; border: solid 5px #72FF50;
} }
#thirdans { #thirdans {
@@ -219,7 +220,7 @@
height: 300px; height: 300px;
margin-left: 50px; margin-left: 50px;
background: linear-gradient(white, white) padding-box, 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-style: solid;
border-width: 5px; border-width: 5px;
border-radius: 20px; border-radius: 20px;
@@ -229,14 +230,14 @@
} }
#StartButton { #StartButton {
background-color: #4CAF50; background-color: #ff863d;
} }
#QuitButton { #QuitButton {
background-color: red; background-color: red;
} }
.MyButton:hover { #StartButton:hover {
background-color: #3E8E41; /* darker shade of green */ background-color: #ae572e; /* darker shade of green */
} }
+34 -3
View File
@@ -2,14 +2,31 @@ import { useEffect, useState} from "react";
import './App.css'; import './App.css';
import Header from "./components/Header"; import Header from "./components/Header";
import Body from "./components/Body"; import Body from "./components/Body";
import question from "./components/Question"; import {getQuestion, getScoreboard, getReset} from "./components/api";
function App() { function App() {
const [timeLeft, setTimeLeft] = useState(10*1000); 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 [timerRunning, setTimerRunning] = useState(false);
const [questionCount, setQuestionCount] = useState(0); const [questionCount, setQuestionCount] = useState(0);
const [teamsize, setTeamSize] = 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(() => { useEffect(() => {
let timer; let timer;
if (timerRunning && timeLeft > 0) { if (timerRunning && timeLeft > 0) {
@@ -18,6 +35,8 @@ function App() {
}, 10);} }, 10);}
else if (timeLeft === 0) { else if (timeLeft === 0) {
alert("Zeit ist um !"); alert("Zeit ist um !");
showcorrect();
getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
setTimerRunning(false); setTimerRunning(false);
setTimeLeft(10); setTimeLeft(10);
} }
@@ -30,14 +49,20 @@ function App() {
return `${seconds} s`; return `${seconds} s`;
} }
const showcorrect = () => {
alert("Richtiges Feld: " + correctfield + "\nRichtige Antwort: " + correctans)
}
const startQuestion = () => { const startQuestion = () => {
if (questionCount <= 5){ if (questionCount <= 5){
setQuestionCount(questionCount+1) setQuestionCount(questionCount+1)
getQuestion(setAns1, setAns2, setAns3, setQuestion, setCorrectField, setCorrectAns).then(r => console.log(r))
setTimeLeft(10*1000); setTimeLeft(10*1000);
setTimerRunning(true); setTimerRunning(true);
} }
else { else {
alert("Spiel vorbei !"); alert("Spiel vorbei !");
getReset(setAns1, setAns2, setAns3, setQuestion);
} }
} }
@@ -47,8 +72,14 @@ function App() {
} }
return (<> return (<>
<Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount}/> <Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount} question={question}/>
<Body startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize} teamsize={teamsize}/> <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"; import React from "react";
function Answers() { function Answers({ans1, ans2, ans3}) {
return( return(
<div className="Answers"> <div className="Answers">
<div className="AnswerBox" id="firstans">Jemand anderen doppelt ... </div> <div className="AnswerBox" id="firstans">
<div className="AnswerBox" id="secondans">Ronaldo >>> Messi</div> <div className="Answer">{ans1}</div>
<div className="AnswerBox" id="thirdans">I got right foot ...</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> </div>
) )
} }
@@ -2,12 +2,16 @@ import React from "react";
import Buttons from "./Buttons"; import Buttons from "./Buttons";
import Answers from "./Answers"; import Answers from "./Answers";
import ScoreBoard from "./ScoreBoard"; 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( return(
<div className="Body"> <div className="Body">
<Buttons startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize}/> <Buttons startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize}
<Answers/> setScoreGreen={setScoreGreen} setScoreRed={setScoreRed} setScoreBlue={setScoreBlue}
<ScoreBoard teamsize={teamsize}/> 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> </div>
) )
} }
@@ -2,8 +2,10 @@ import React, {useState} from "react";
import StartButton from "./StartButton"; import StartButton from "./StartButton";
import QuitButton from "./QuitButton"; import QuitButton from "./QuitButton";
import TeamSizePopUp from "./TeamsizePopUp"; 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 [gameStarted, setGameStarted] = useState(false)
const [openPopUp, setOpenPopUp] = useState(false) const [openPopUp, setOpenPopUp] = useState(false)
const [quitvisible, setQuitvisible] = useState(false) const [quitvisible, setQuitvisible] = useState(false)
@@ -26,6 +28,9 @@ function Buttons({startQuestion, timerRunning, stopTimer, setQuestionCount, setT
changeGame(false); changeGame(false);
stopTimer(); stopTimer();
setQuestionCount(0); 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 Heading from "./Heading";
import Timer from "./Timer"; import Timer from "./Timer";
import Question from "./Question"; import Question from "./Question";
function Header({timerRunning, timerContent, questionCount}) { function Header({timerRunning, timerContent, questionCount, question}) {
return( return(
<header className="Header"> <header className="Header">
<Heading/> <Heading/>
<Question questionCount={questionCount}/> <Question questionCount={questionCount} question={question}/>
<Timer timerRunning={timerRunning} timerContent={timerContent}/> <Timer timerRunning={timerRunning} timerContent={timerContent}/>
</header> </header>
) )
@@ -1,13 +1,13 @@
import React from "react"; import React from "react";
function Question({questionCount}) { function Question({questionCount, question}) {
return( return(
<div className="HeaderDiv"> <div className="HeaderDiv">
<div id="QuestionHeaderDiv"> <div id="QuestionHeaderDiv">
<h2 id="QuestionHeader">{questionCount ? questionCount + ".Frage" : "Fragen"}</h2> <h2 id="QuestionHeader">{questionCount ? questionCount + ".Frage" : "Fragen"}</h2>
</div> </div>
<div id="QuestionDiv"> <div id="QuestionDiv">
<h2 id="Question">Warum ist Kerem so schrott ? </h2> <h2 id="Question">{question}</h2>
</div> </div>
</div> </div>
) )
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
function ScoreBoard({teamsize}) { function ScoreBoard({teamsize, scoreblue, scoregreen, scorered}) {
return( return(
<div className={"ScoreBoard"}> <div className={"ScoreBoard"}>
<div> <div>
@@ -16,15 +16,15 @@ function ScoreBoard({teamsize}) {
<tbody> <tbody>
<tr> <tr>
<td>Red</td> <td>Red</td>
<td id="red-points">0</td> <td id="red-points">{scorered}</td>
</tr> </tr>
<tr> <tr>
<td>Yellow</td> <td>Green</td>
<td id="yellow-points">0</td> <td id="yellow-points">{scoregreen}</td>
</tr> </tr>
<tr> <tr>
<td>Blue</td> <td>Blue</td>
<td id="blue-points">0</td> <td id="blue-points">{scoreblue}</td>
</tr> </tr>
</tbody> </tbody>
@@ -15,19 +15,20 @@ function TeamSizePopUp({closeModal, changeGameState, startQuestion, setTeamSize}
} }
const TeamSizeButtonClicked = () => { const TeamSizeButtonClicked = () => {
if(inputValue <= 2 && inputValue > 0){ if(inputValue <= 3 && inputValue > 0){
/* try {
postTeamsize({ console.log(typeof inputValue)
"Teamsize": inputValue postTeamsize(inputValue).then(r => { if (r.ok) {console.log("OK")} });
}).then(data => console.log("Received answer" + data)) setTeamSize(inputValue);
*/
setTeamSize(inputValue)
changeGameState(true); changeGameState(true);
closePopUp(); closePopUp();
startQuestion(); startQuestion();
} catch (error) {
console.error(error)
}
} }
else { 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> <h2>Bitte Teamgröße wählen </h2>
</div> </div>
<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}/> onChange={getInput}/>
</div> </div>
<div> <div>
+37 -15
View File
@@ -1,31 +1,53 @@
import {createContext} from "react";
export function postTeamsize(data) { export function postTeamsize(data) {
return fetch("URL:PORT/TEAMSIZE",{ const requestOptions = {
methods: 'POST', method: 'POST',
headers: { headers: {
"Content-Type": "application/json" 'Accept': 'application/json',
}, 'Content-Type': 'application/json'},
body: JSON.stringify(data) body: JSON.stringify({ teamsize: data})
}) }
.then(response => response.json()) return fetch("http://192.168.0.94:5555/teamsize", requestOptions)
} }
export function getConnection() { 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 getCheck() {
} }
export function getReset() { export function getReset(setAns1, setAns2, setAns3, setQuestion) {
setAns1('?');
setAns2('?');
setAns3('?');
setQuestion('?');
return fetch("http://192.168.0.94:5555/reset")
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB