我正在创建一个python proram,我们可以使用我们的手势而不是键盘来玩古典蛇xenzia游戏。在我的蛇被击中边界时,pygame窗口就被摧毁了。我然后重新初始化游戏功能,但似乎没有做的技巧,并抛出一个错误。我想重新初始化pygame窗口,以便用户可以重新启动游戏,而不是再次启动游戏。任何帮助表示赞赏。提前谢谢。这是我的代码:
import pygame, random, sys
from pygame.locals import *
import cv2
import numpy as np
import math
import sqlite3
from tkinter import *
from ctypes import windll
import time
def collide(x1, x2, y1, y2, w1, w2, h1, h2):
if x1+w1>x2 and x1<x2+w2 and y1+h1>y2 and y1<y2+h2:return True
else:return False
def die(screen, score):
global conn,cap
f=pygame.font.SysFont('Arial', 30);t=f.render('Your score was:
'+str(score), True, (0, 0, 0));screen.blit(t, (10,
270));pygame.display.update();pygame.time.wait(2000)
time.sleep(3)
pygame.display.quit()
cv2.destroyAllWindows()
r2 = conn.execute("select score from highscore order by score limit 10")
sc_list = list(r2.fetchall())
if(score <= int(max(sc_list[0])) and score >= int(min(sc_list[0]))):
n = enter_name()
#print(n)
conn.execute("insert into highscore(name,score) values (?,?)",
(n,score))
conn.commit()
cap.release()
#pygame.display.quit()
#sys.exit(0)
main_menu()
def get_name():
global e,string
string = e.get()
return string
root1.destroy()
def enter_name():
global root,w
root1 = Tk()
#global e,root1
root1.geometry('%dx%d+%d+%d' % (700,500, 640, 100))
b = Button(root1,text='okay',command=get_name)
b.place(x=300,y=200)
e = Entry(root1)
e.place(x=250,y=150)
e.focus_set()
return string
root1.mainloop()
def game():
decl()
time.sleep(2)
cap = cv2.VideoCapture(0)
global
start,xs1,ys1,dirs1,score1,applepos1,s1,appleimage1,img1,f1,clock1,res
pygame.init()
pygame.display.set_caption('Snake')
SetWindowPos(pygame.display.get_wm_info()['window'], -1, 0, 10, 0, 0,
0x0001)
pygame.draw.line(s1,(255,255,255),(5,0),(5,600),3)
while (cap.isOpened()):
#s1.fill((0,0,0))
#SNAKE'S EXECUTION
#-----------------------------------------------------------------------
----------------
#if(start == True):
clock1.tick(10)
for e in pygame.event.get():
if e.type == QUIT:
sys.exit(0)
'''
elif e.type == KEYDOWN:
if e.key == K_UP and dirs1 != 0:dirs1 = 2
elif e.key == K_DOWN and dirs1 != 2:dirs1 = 0
elif e.key == K_LEFT and dirs1 != 1:dirs1 = 3
elif e.key == K_RIGHT and dirs1 != 3:dirs1 = 1
'''
i = len(xs1)-1
while i >= 2:
if collide(xs1[0], xs1[i], ys1[0], ys1[i], 20, 20, 20, 20):die(s1,
score1)
i-= 1
if collide(xs1[0], applepos1[0], ys1[0], applepos1[1], 20, 10, 20,
10):score1+=1;xs1.append(700);ys1.append(700);applepos1=
(random.randint(0,590),random.randint(0,590))
if xs1[0] < 0 or xs1[0] > 580 or ys1[0] < 0 or ys1[0] > 580:die(s1,
score1)
i = len(xs1)-1
while i >= 1:
xs1[i] = xs1[i-1];ys1[i] = ys1[i-1];i -= 1
if dirs1==0:
ys1[0] += 20
elif dirs1==1:
xs1[0] += 20
elif dirs1==2:
ys1[0] -= 20
elif dirs1==3:
xs1[0] -= 20
s1.fill((0,0,0))
for i in range(0, len(xs1)):
s1.blit(img1, (xs1[i], ys1[i]))
s1.blit(appleimage1, applepos1);t1=f1.render(str(score1), True,
(255,255,255));s1.blit(t1, (10, 10));pygame.display.update()
#-----------------------------------------------------------------------
----------------
#DETECTION'S EXECUTION
#-----------------------------------------------------------------------
----------------
ret, img = cap.read()
# get hand data from the rectangle sub window on the screen
cv2.rectangle(img, (450,450), (200,200), (0,255,0),0)
crop_img = img[200:450, 200:450]
# convert to grayscale
grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
# applying gaussian blur
value = (35, 35)
blurred = cv2.GaussianBlur(grey, value, 0)
# thresholdin: Otsu's Binarization method
_, thresh1 = cv2.threshold(blurred, 127, 255,
cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# show thresholded image
# check OpenCV version to avoid unpacking error
(version, _, _) = cv2.__version__.split('.')
if version == '3':
image, contours, hierarchy = cv2.findContours(thresh1.copy(), \
cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
elif version == '2':
contours, hierarchy = cv2.findContours(thresh1.copy(),cv2.RETR_TREE,
\
cv2.CHAIN_APPROX_NONE)
# find contour with max area
cnt = max(contours, key = lambda x: cv2.contourArea(x))
# create bounding rectangle around the contour (can skip below two
lines)
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(crop_img, (x, y), (x+w, y+h), (0, 0, 255), 0)
# finding convex hull
hull = cv2.convexHull(cnt)
# drawing contours
drawing = np.zeros(crop_img.shape,np.uint8)
cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 0)
cv2.drawContours(drawing, [hull], 0,(0, 0, 255), 0)
# finding convex hull
hull = cv2.convexHull(cnt, returnPoints=False)
# finding convexity defects
defects = cv2.convexityDefects(cnt, hull)
count_defects = 0
cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)
# applying Cosine Rule to find angle for all defects (between fingers)
# with angle > 90 degrees and ignore defects
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
# find length of all sides of triangle
a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)
b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)
c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)
# apply cosine rule here
angle = math.acos((b**2 + c**2 - a**2)/(2*b*c)) * 57
# ignore angles > 90 and highlight rest with red dots
if angle <= 90:
count_defects += 1
cv2.circle(crop_img, far, 1, [0,0,255], -1)
#dist = cv2.pointPolygonTest(cnt,far,True)
# draw a line from start to end i.e. the convex points (finger tips)
# (can skip this part)
cv2.line(crop_img,start, end, [0,255,0], 2)
#cv2.circle(crop_img,far,5,[0,0,255],-1)
# define actions required
if count_defects == 1 and dirs1 != 0:
dirs1 = 2
#print('!!!!!!!!!1')
start=True
elif count_defects == 2 and dirs1 != 2:
dirs1 = 0
elif count_defects == 3 and dirs1 != 1:
dirs1 = 3
elif count_defects == 4 and dirs1 != 3:
dirs1 = 1
all_img = np.hstack((drawing, crop_img))
cv2.imshow('Contours', all_img)
cv2.imshow('Thresholded', thresh1)
# show appropriate images in windows
cv2.imshow('Gesture', img)
#cv2.resizeWindow('Gesture',800,800)
cv2.moveWindow('Gesture',700,50)
k = cv2.waitKey(10)
if k == 27:
break
#-----------------------------------------------------------------------
----------------