I’ve created a rock-paper-scissors game with openCv. Everything works kinda well but when a game has ended, I want to give the player(s) the choice if they want to continue or if they want to quit. When they quit, there is no problem because than the command cv.destroyAllWindows() comes into place and all windows are cleared. But when they want to continue playing. The screen should reset or the window should close and reopen a brand new one, but I can’t seem to make that work… Any ideas?
from datetime import datetime
from sqlite3 import Timestamp
from turtle import reset
import cv2 as cv
import mediapipe as mp
import random
import firebase_admin
from firebase_admin import firestore
from firebase_admin import credentials
from datetime import datetime
from threading import Event
import time
# Maak timestamps aan
now = datetime.now()
timestamp = datetime.timestamp(now)
datetime = datetime.fromtimestamp(timestamp, tz=None)
date_time = datetime.strftime("%m/%d/%Y, %H:%M:%S")
# Connectie met firebase
cred = credentials.Certificate('../serviceAccountKey.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
# Laat de speler kiezen of ze tegen de computer of tegen een vriend/vriendin willen spelen
def mode():
print("Kies je spelmodus")
print("[1] Tegen de computer")
print("[2] Tegen een vriend")
mode()
option = int(input("Geef de modus in:"))
if option == 1:
username1 = input("Graag uw volledige naam:")
username2 = "CPU"
elif option == 2:
username1 = input("Graag uw volledige naam:")
username2 = input("Graag uw volledige naam:")
window_name = "window"
# connectie met webcam
vid = cv.VideoCapture(0)
# klok
clock = 0
p1_move = p2_move = None
gameText = ""
success = True
# Win Counter
wcounter1 = 0
wcounter2 = 0
# Lose Counter
lcounter1 = 0
lcounter2 = 0
# Draw Counter
dcounter = 0
def game():
global wcounter1, wcounter2, clock ,lcounter1, lcounter2, gameText, dcounter, window_name
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
# bepaal of een handgebaar schaar, steen of papier is
def getHandMove(hand_landmarks):
landmarks = hand_landmarks.landmark
if all([landmarks[i].y < landmarks[i+3].y for i in range(9,20,4)]):return "steen"
elif landmarks[13].y < landmarks[16].y and landmarks[17].y < landmarks[20].y:return "schaar"
else: return "papier"
# trackt de camera voor handen en plaats 'landmarks' op de handen voor tracking
with mp_hands.Hands(model_complexity=0,
min_detection_confidence=0.5,
min_tracking_confidence=0.5) as hands:
while wcounter1 < 3 and wcounter2 < 3:
list = ["schaar","steen","papier"]
cpu = random.choice(list)
ret, frame = vid.read()
frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
results = hands.process(frame,)
frame = cv.cvtColor(frame, cv.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landsmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(frame,
hand_landsmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style())
# start van het spel
if 0 <= clock < 60:
success = True
gameText = "Ready?"
elif clock < 80: gameText = "schaar"
elif clock < 100: gameText = "steen"
elif clock == 100: gameText = "papier"
# vraagt de resultaten van de handgebaren
elif clock == 105:
if option == 1:
hls = results.multi_hand_landmarks
if hls and len(hls) == 1:
player = getHandMove(hls[0])
else:
success = False
if success:
# Toont aan welke speler welk handgebaar gebruikte
gameText = f"{username1} koos voor {player}. {username2} koos voor {cpu}."
if player == cpu: gameText = f"{gameText} gelijkspel!"; dcounter +=1
# De voorwaarden waaraan {username1} moet voldoen om te winnen
elif player == "papier" and cpu == "steen": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
elif player == "steen" and cpu == "schaar": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
elif player == "schaar" and cpu == "papier": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
# Als aan geen enkele bovenstaande voorwaarde wordt voldaan, dan wint {username2}
else: gameText = f"{gameText} {username2} wint!"; wcounter2 +=1; lcounter1 +=1
else:
gameText = "Ongeldig"
elif option == 2:
hls = results.multi_hand_landmarks
if hls and len(hls) == 2:
p1_move = getHandMove(hls[0])
p2_move = getHandMove(hls[1])
else:
success = False
if success:
# Toont aan welke speler welk handgebaar gebruikte
gameText = f"{username1} koos voor {p1_move}. {username2} koos voor {p2_move}."
if p1_move == p2_move: gameText = f"{gameText} gelijkspel!"; dcounter +=1
# De voorwaarden waaraan {username1} moet voldoen om te winnen
elif p1_move == "papier" and p2_move == "steen": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
elif p1_move == "steen" and p2_move == "schaar": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
elif p1_move == "schaar" and p2_move == "papier": gameText = f"{gameText} {username1} wint!";wcounter1 +=1; lcounter2 +=1
# Als aan geen enkele bovenstaande voorwaarde wordt voldaan, dan wint {username2}
else: gameText = f"{gameText} {username2} wint!"; wcounter2 +=1; lcounter1 +=1
else:
gameText = "Ongeldig"
# Plaatst de counter die het aantal gelijkspellen aangeeft
cv.rectangle(frame, (240, 420), (435, 450), (0,0,0), -1)
cv.putText(frame, f"gelijkspel: {dcounter}", (265, 443), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
# Plaatst het aantal winsten en verloren spellen van speler 1 op het frame
cv.rectangle(frame, (0, 420), (180, 490), (0,0,0), -1)
cv.putText(frame, f"Winst: {wcounter1}", (25, 443), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
cv.putText(frame, f"Verlies: {lcounter1}", (25, 473), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
# Plaatst het aantal winsten en verloren spellen van speler 2 op het frame
cv.rectangle(frame, (500, 420), (680, 490), (0,0,0), -1)
cv.putText(frame, f"Winst: {wcounter2}", (510, 443), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
cv.putText(frame, f"Verlies: {lcounter2}", (510, 473), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
# Plaatsen van de tekst op het frame
cv.putText(frame, f"{clock}", (50,50), cv.FONT_HERSHEY_PLAIN, 2, (0,255,255), 2, cv.LINE_AA)
cv.putText(frame, gameText, (50,80), cv.FONT_HERSHEY_PLAIN, 1, (0,255,255), 2, cv.LINE_AA)
clock = (clock + 1) % 200
if wcounter1 == 3:
db.collection(u'spellen').add({'id': f'{datetime.timestamp()}', 'winnaar':f'{username1}', 'verliezer': f'{username2}'})
cv.rectangle(frame, (0, 0), (320, 490), (0,100,0), -1)
cv.rectangle(frame, (320, 0), (720, 680), (0,0,153), -1)
cv.putText(frame, f"{username1} heeft gewonnen", (200, 230), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
elif wcounter2 == 3:
db.collection(u'spellen').add({'id': f'{datetime.timestamp()}', 'winnaar':f'{username2}', 'verliezer': f'{username1}'})
cv.rectangle(frame, (0, 0), (320, 490), (0,0,153), -1)
cv.rectangle(frame, (320, 0), (720, 680), (0,100,0), -1)
cv.putText(frame, f"{username2} heeft gewonnen", (200, 230), cv.FONT_HERSHEY_PLAIN, 1.5, (255,255,255), 2, cv.LINE_AA)
# Rendert het frame
cv.imshow('frame', frame)
#verbreek de loop door op de q toets te drukken
if cv.waitKey(1) & 0xFF == ord('q'): break
game()
vid.release()
time.sleep(3)
def next():
print("Wens je nog eens te spelen of het spel te beëindigen? (y/n)")
next()
choice = str(input())
if choice == "y":
game()
elif choice == "n":
cv.destroyAllWindows()