import cv2                              
import numpy as np
import math
import random
import os
#import serial
import time
#ser = serial.Serial("",9600)
#batting-1, bowling-2
count1=0;
a1=0;
count2=0;
a2=0;
ar1=[10,10,10,10,10,10];
ar2=[0,0,0,0,0,0];
br=[0,0,0,0,0,0];
comp_tot = 0
play_tot = 0
num1 = random.randrange(0,6);
rand = 0
videoFrame = cv2.VideoCapture(-1)

# TO DETECT THE VALUE SHOWN BY US
def fingercount():
    min_YCrCb = np.array([0,133,77],np.uint8)
    max_YCrCb = np.array([255,173,127],np.uint8)
    x=0
    y = range(40)
    r = range(7)
    r = [0,0,0,0,0,0,0]
    t = 0
    dis = range(8)
    q =range(2)
    keyPressed = -1 
    while(keyPressed < 0): 
        readSucsess, img = videoFrame.read()
        imageYCrCb = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
        blur = cv2.GaussianBlur(imageYCrCb,(3,3),0)
        skinRegion = cv2.inRange(blur,min_YCrCb,max_YCrCb)
        contours, hierarchy = cv2.findContours(skinRegion, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        drawing = np.zeros(img.shape,np.uint8)
        max_area=0
        ci=0
        while (len(contours)==0):
            #print "HAND NOT SHOWN"
            readSucsess, img = videoFrame.read()
            imageYCrCb = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
            blur = cv2.GaussianBlur(imageYCrCb,(3,3),0)
            skinRegion = cv2.inRange(blur,min_YCrCb,max_YCrCb)
            contours, hierarchy = cv2.findContours(skinRegion, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            drawing = np.zeros(img.shape,np.uint8)
            if len(contours)!=0:
                break
        for i in range(len(contours)):
                cnt=contours[i]
                area = cv2.contourArea(cnt)
                if(area>max_area):
                    max_area=area
                    ci=i
        cnt=contours[ci]
        hull = cv2.convexHull(cnt)
        moments = cv2.moments(cnt)
        while moments['m00']==0 :
            continue
        if moments['m00']!=0:
                    cx = int(moments['m10']/moments['m00']) # cx = M10/M00
                    cy = int(moments['m01']/moments['m00']) # cy = M01/M00
        centr=(cx,cy)       
        cv2.circle(drawing,centr,5,[0,0,255],2)       
        cv2.drawContours(drawing,[cnt],0,(0,255,0),2) 
        cv2.drawContours(drawing,[hull],0,(0,0,255),2) 
        cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        hull = cv2.convexHull(cnt,returnPoints = False)
        j=0
        if(1):
                   defects = cv2.convexityDefects(cnt,hull)
                   if defects == None :
                       print 'Hand not shown'
                       t=1
                       continue
                   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])
                        dist = cv2.pointPolygonTest(cnt,centr,True)
                        cv2.line(drawing,start,end,[0,255,0],2)                    
                        n = math.sqrt(((start[0]-end[0])*(start[0]-end[0]))+((start[1]-end[1])*(start[1]-end[1])))
                        angle=(math.atan2(cy-start[1],cx-start[0])*180)/math.pi
                        if n < 215 :
                            if n > 40 :
                                cv2.circle(drawing,end,5,[0,0,255],-1)
                                j = j+1
                                q[0] = end[0]
                                q[1] = end[1]
                   j = j+1                   
                   if j == 2 or j==3:                       
                        cv2.circle(drawing,centr,int(0.0060*36000),[0,0,255],2)
                        yi = math.sqrt(((q[0]-cx)*(q[0]-cx))+((q[1]-cy)*(q[1]-cy)))
                        if yi < int(0.0060*36000) :
                            j=6
                   if x < 30 :
                        x = x+1
                        y[x] = j
                   else:
                        x=0
                   i=0
        cv2.imshow('drawing',drawing)
        cv2.imshow('img',img)
        if t == 1:
            t = 0
            continue
        if x < 30 :
            if y[x] == 0:
                   r[0] = r[0]+1;
            if y[x] == 1:
                    r[1] = r[1]+1;
            if y[x] == 2:
                    r[2] = r[2]+1;
            if y[x] == 3:
                    r[3] = r[3]+1;
            if y[x] == 4:
                    r[4] = r[4]+1;
            if y[x] == 5:
                    r[5] = r[5]+1;
            if y[x] == 6:
                    r[6] = r[6]+1;
            x = x+1               
        elif x == 30:
            x=0
            i=1
            tmax = r[0]
            index = 0
            while(i<=6):
                if r[i] > tmax:
                    tmax=r[i]
                    index = i
                i = i+1
            
            r= [0,0,0,0,0,0,0]
            #print "Finger shown" 
            #print index
            return index        
        k = cv2.waitKey(10)
        if k == 27:
            break
    videoFrame.release()
def cls():
    print "\n" * 10
    
# ALGORITHM USING WEIGHTED PROBABILITIES
def weighted_choice(weights):
    totals = []
    running_total = 0

    for w in weights:
        running_total += w
        totals.append(running_total)

    rnd = random.random() * running_total
    for i, total in enumerate(totals):
        if rnd < total:
            return i
        
#THE NUMBER ARM SHOULD SHOW WHILE IT IS BATTING        
def collect_bat(num):
    global ar1
    global count1
    count1+=1
    out=weighted_choice(ar1)
    print "Arm:  ",out+1
    #print out+1
    rand=out+1
    if(count1%10==0):
        for i in range(0,6):
            ar1[i]=10
    ar1[num-1]-=1
    return rand

#THE NUMBER ARM SHOULD SHOWN WHILE IT IS BOWLING 
def collect_bowl(val):
    global ar2
    global br
    global count2;
    out=0
    for i in range(0,6):
        br[i]=ar2[i]+1
    out=weighted_choice(br)
    #print br
    print "Arm:  ",out+1
    rand=out+1
    count2+=1
    ar2[val-1]+=1
    return rand

while (True) :
    print "------------------------------------TOSS------------------------------------"
    bot_val=random.randrange(1,7);
    human_val=fingercount()
    print "BOT:",bot_val
    print "YOU SHOWED: ",human_val
    total=human_val+bot_val
    rem=total % 2
    print (75 * "-")
    print "\t\t\tIF SUM IS ODD, ROBOTIC ARM WILL BAT FIRST"
    print (75 * "-")
    if rem==1:
        print "------ARM BATTING FIRST------"
        time.sleep(3)        
        play_tot=0;
        comp_tot=0;
        while (True) :
            #PRESS 'q' TO EXIT"
            if cv2.waitKey(20) & 0xFF == ord('q'):
                break    
            num=fingercount()
            print "You:  ",num
            rand=collect_bat(num)
            print "\n"          
            num1 = num
            if num == rand :
                print "The Arm is out"
                print "The Arm's scored ",comp_tot ," runs!!!"
                print "THE TARGET FOR YOU",comp_tot+1,"runs!!"
                temp = cv2.waitKey(2000)
                time.sleep(3)
                cls()
                break
            else :
                comp_tot = comp_tot + rand
        print "ARM IS BOWLING"
        while (True) :
            #PRESS 'q' TO EXIT"
            if cv2.waitKey(20) & 0xFF == ord('q'):
                break    
            num=fingercount()
            rand=collect_bowl(num)            
            print "You:  ",num
            print "\n"
            num1 = num
            if num == rand :
                print "You are out"
                print "Your score is :",play_tot                
                if comp_tot > play_tot:
                    print "\n\nTHE ARM WINS\n\n"
                elif comp_tot == play_tot :
                    print "\n\nTHE GAME IS A TIE \n\n "
                else:
                    print "\n\nTHE PLAYER WINS \n\n"
                time.sleep(5)
                cls()
                break    
            else :
                play_tot = play_tot + num
                if play_tot > comp_tot :
                    print "\n\nTHE PLAYER WINS \n\n"
                    print "The Player's score is :",play_tot      
                    cls()
                    break                    
    else:
        print "------YOU BAT FIRST------"
        time.sleep(3)
        play_tot=0;
        comp_tot=0;
        while (True) :
            #PRESS 'q' TO EXIT"
            if cv2.waitKey(20) & 0xFF == ord('q'):
                break    
            num=fingercount()            
            rand=collect_bowl(num)
            print "You:  ",num
            print "\n"
            num1 = num
            if num == rand :
                print "You are out"
                print "You scored ",play_tot ," runs!!!"
                print "THE TARGET FOR ARM",play_tot+1,"runs!!"                
                temp = cv2.waitKey(2000)
                time.sleep(3)
                cls()
                break
            else :
                play_tot = play_tot + num
        print "YOUR ARE BOWLING"
        while (True) :            
            #PRESS 'q' TO EXIT"
            if cv2.waitKey(20) & 0xFF == ord('q'):
                break
            num=fingercount()
            rand=collect_bat(num)
            print "You:  ",num,"\n"
            print "\n"
            num1 = num
            if num == rand :
                print "Arm is out"
                print "Arm's score is :",comp_tot
                if comp_tot > play_tot:
                    print "\n\nTHE ARM WINS\n\n"
                elif comp_tot == play_tot :
                    print "\n\nTHE GAME IS A TIE \n\n "
                else:
                    print "\n\nTHE PLAYER WINS \n\n"
                time.sleep(5)
                cls()
                break    
            else :
                comp_tot = comp_tot + rand
                if comp_tot > play_tot :
                    print "\n\nTHE ARM WINS \n\n"
                    print "The Arm's score is :",play_tot      
                    cls()
                    break
    #PRESS 'q' TO EXIT"
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break
videoFrame.release()    
cv2.destroyAllWindows()

