├── data └── save.dat ├── music ├── car.wav ├── crash.wav └── laugh.wav ├── image ├── car1.png ├── car2.png ├── car3.png ├── car4.png ├── left.png └── right.png ├── README.md └── game.py /data/save.dat: -------------------------------------------------------------------------------- 1 | 837 -------------------------------------------------------------------------------- /music/car.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/music/car.wav -------------------------------------------------------------------------------- /image/car1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/car1.png -------------------------------------------------------------------------------- /image/car2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/car2.png -------------------------------------------------------------------------------- /image/car3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/car3.png -------------------------------------------------------------------------------- /image/car4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/car4.png -------------------------------------------------------------------------------- /image/left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/left.png -------------------------------------------------------------------------------- /image/right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/image/right.png -------------------------------------------------------------------------------- /music/crash.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/music/crash.wav -------------------------------------------------------------------------------- /music/laugh.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anil-matcha/opencvpython/master/music/laugh.wav -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | To run this game you need 2 | 1.python 3 | 2.opencv with python and its dependancies 4 | 3.pygame 5 | installed in your computer to run in terminal type :-python game.py 6 | -------------------------------------------------------------------------------- /game.py: -------------------------------------------------------------------------------- 1 | import pygame, random, sys ,os,time 2 | from pygame.locals import * 3 | import cv2 4 | import numpy as np 5 | from time import sleep 6 | import thread 7 | import pyautogui 8 | import math 9 | 10 | WINDOWWIDTH = 800 11 | WINDOWHEIGHT = 600 12 | TEXTCOLOR = (255, 255, 255) 13 | BACKGROUNDCOLOR = (0, 0, 0) 14 | FPS = 40 15 | BADDIEMINSIZE = 10 16 | BADDIEMAXSIZE = 40 17 | BADDIEMINSPEED = 8 18 | BADDIEMAXSPEED = 8 19 | ADDNEWBADDIERATE = 6 20 | PLAYERMOVERATE = 5 21 | count=3 22 | 23 | cap = cv2.VideoCapture(0) 24 | prevx, prevy = 0,0 25 | factor = 5 26 | cap.set(3,396) 27 | cap.set(4,216) 28 | 29 | def gamecontrol(moveLeft, moveRight, moveUp, moveDown): 30 | _, frame = cap.read() 31 | frame = cv2.blur(frame,(3,3)) 32 | 33 | # Convert BGR to HSV 34 | hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) 35 | 36 | # define range of blue color in HSV 37 | lower_blue = np.array([110,50,50]) 38 | upper_blue = np.array([130,255,255]) 39 | thresh = cv2.inRange(hsv,lower_blue, upper_blue) 40 | # Threshold the HSV image to get only blue colors 41 | mask = cv2.inRange(hsv, lower_blue, upper_blue) 42 | _,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 43 | max_area = 0 44 | best_cnt = None 45 | for cnt in contours: 46 | area = cv2.contourArea(cnt) 47 | if area > max_area: 48 | max_area = area 49 | best_cnt = cnt 50 | #print(best_cnt, max_area) 51 | M = cv2.moments(best_cnt) 52 | divfactor = max_area/10000.0 53 | if(divfactor < 1): 54 | divfactor = 1 55 | if(M['m00']>0 and max_area>100): 56 | cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00']) 57 | cv2.circle(frame,(cx,cy),5,255,-1) 58 | #print(cx,cy) 59 | if(cx>198): 60 | moveRight = False 61 | moveLeft = True 62 | else: 63 | moveLeft = False 64 | moveRight = True 65 | if(cy>108): 66 | moveUp = False 67 | moveDown = True 68 | else: 69 | moveDown = False 70 | moveUp = True 71 | else: 72 | print("invisible") 73 | #pyautogui.click() 74 | # Bitwise-AND mask and original image 75 | res = cv2.bitwise_and(frame,frame, mask= mask) 76 | res = (255-res) 77 | res=cv2.flip(res,1) 78 | #cv2.imshow('frame',frame) 79 | #cv2.imshow('mask',mask) 80 | cv2.imshow('res',res) 81 | return moveLeft, moveRight, moveUp, moveDown 82 | 83 | 84 | def terminate(): 85 | pygame.quit() 86 | sys.exit() 87 | 88 | def waitForPlayerToPressKey(): 89 | while True: 90 | for event in pygame.event.get(): 91 | if event.type == QUIT: 92 | terminate() 93 | if event.type == KEYDOWN: 94 | if event.key == K_ESCAPE: #escape quits 95 | terminate() 96 | return 97 | 98 | def playerHasHitBaddie(playerRect, baddies): 99 | for b in baddies: 100 | if playerRect.colliderect(b['rect']): 101 | return True 102 | return False 103 | 104 | def drawText(text, font, surface, x, y): 105 | textobj = font.render(text, 1, TEXTCOLOR) 106 | textrect = textobj.get_rect() 107 | textrect.topleft = (x, y) 108 | surface.blit(textobj, textrect) 109 | 110 | # set up pygame, the window, and the mouse cursor 111 | pygame.init() 112 | mainClock = pygame.time.Clock() 113 | windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) 114 | pygame.display.set_caption('car race') 115 | pygame.mouse.set_visible(False) 116 | 117 | # fonts 118 | font = pygame.font.SysFont(None, 30) 119 | 120 | # sounds 121 | gameOverSound = pygame.mixer.Sound('music/crash.wav') 122 | pygame.mixer.music.load('music/car.wav') 123 | laugh = pygame.mixer.Sound('music/laugh.wav') 124 | 125 | 126 | # images 127 | playerImage = pygame.image.load('image/car1.png') 128 | car3 = pygame.image.load('image/car3.png') 129 | car4 = pygame.image.load('image/car4.png') 130 | playerRect = playerImage.get_rect() 131 | baddieImage = pygame.image.load('image/car2.png') 132 | sample = [car3,car4,baddieImage] 133 | wallLeft = pygame.image.load('image/left.png') 134 | wallRight = pygame.image.load('image/right.png') 135 | 136 | 137 | # "Start" screen 138 | drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) 139 | drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30) 140 | pygame.display.update() 141 | waitForPlayerToPressKey() 142 | zero=0 143 | if not os.path.exists("data/save.dat"): 144 | f=open("data/save.dat",'w') 145 | f.write(str(zero)) 146 | f.close() 147 | v=open("data/save.dat",'r') 148 | topScore = int(v.readline()) 149 | v.close() 150 | while (count>0): 151 | # start of the game 152 | baddies = [] 153 | score = 0 154 | playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50) 155 | moveLeft = moveRight = moveUp = moveDown = False 156 | reverseCheat = slowCheat = False 157 | baddieAddCounter = 0 158 | pygame.mixer.music.play(-1, 0.0) 159 | 160 | while True: # the game loop 161 | score += 1 # increase score 162 | moveLeft, moveRight, moveUp, moveDown = gamecontrol(moveLeft, moveRight, moveUp, moveDown) 163 | #print(moveLeft, moveRight, moveUp, moveDown) 164 | for event in pygame.event.get(): 165 | 166 | if event.type == QUIT: 167 | terminate() 168 | ''' 169 | if event.type == KEYDOWN: 170 | if event.key == ord('z'): 171 | reverseCheat = True 172 | if event.key == ord('x'): 173 | slowCheat = True 174 | if event.key == K_LEFT or event.key == ord('a'): 175 | moveRight = False 176 | moveLeft = True 177 | if event.key == K_RIGHT or event.key == ord('d'): 178 | moveLeft = False 179 | moveRight = True 180 | if event.key == K_UP or event.key == ord('w'): 181 | moveDown = False 182 | moveUp = True 183 | if event.key == K_DOWN or event.key == ord('s'): 184 | moveUp = False 185 | moveDown = True 186 | 187 | if event.type == KEYUP: 188 | if event.key == ord('z'): 189 | reverseCheat = False 190 | score = 0 191 | if event.key == ord('x'): 192 | slowCheat = False 193 | score = 0 194 | if event.key == K_ESCAPE: 195 | terminate() 196 | 197 | 198 | if event.key == K_LEFT or event.key == ord('a'): 199 | moveLeft = False 200 | if event.key == K_RIGHT or event.key == ord('d'): 201 | moveRight = False 202 | if event.key == K_UP or event.key == ord('w'): 203 | moveUp = False 204 | if event.key == K_DOWN or event.key == ord('s'): 205 | moveDown = False 206 | 207 | 208 | ''' 209 | # Add new baddies at the top of the screen 210 | if not reverseCheat and not slowCheat: 211 | baddieAddCounter += 1 212 | if baddieAddCounter == ADDNEWBADDIERATE: 213 | baddieAddCounter = 0 214 | baddieSize =30 215 | newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47), 216 | 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 217 | 'surface':pygame.transform.scale(random.choice(sample), (23, 47)), 218 | } 219 | baddies.append(newBaddie) 220 | sideLeft= {'rect': pygame.Rect(0,0,126,600), 221 | 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 222 | 'surface':pygame.transform.scale(wallLeft, (126, 599)), 223 | } 224 | baddies.append(sideLeft) 225 | sideRight= {'rect': pygame.Rect(497,0,303,600), 226 | 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 227 | 'surface':pygame.transform.scale(wallRight, (303, 599)), 228 | } 229 | baddies.append(sideRight) 230 | 231 | 232 | 233 | # Move the player around. 234 | if moveLeft and playerRect.left > 0: 235 | playerRect.move_ip(-1 * PLAYERMOVERATE, 0) 236 | if moveRight and playerRect.right < WINDOWWIDTH: 237 | playerRect.move_ip(PLAYERMOVERATE, 0) 238 | if moveUp and playerRect.top > 0: 239 | playerRect.move_ip(0, -1 * PLAYERMOVERATE) 240 | if moveDown and playerRect.bottom < WINDOWHEIGHT: 241 | playerRect.move_ip(0, PLAYERMOVERATE) 242 | 243 | for b in baddies: 244 | if not reverseCheat and not slowCheat: 245 | b['rect'].move_ip(0, b['speed']) 246 | elif reverseCheat: 247 | b['rect'].move_ip(0, -5) 248 | elif slowCheat: 249 | b['rect'].move_ip(0, 1) 250 | 251 | 252 | for b in baddies[:]: 253 | if b['rect'].top > WINDOWHEIGHT: 254 | baddies.remove(b) 255 | 256 | # Draw the game world on the window. 257 | windowSurface.fill(BACKGROUNDCOLOR) 258 | 259 | # Draw the score and top score. 260 | drawText('Score: %s' % (score), font, windowSurface, 128, 0) 261 | drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20) 262 | drawText('Rest Life: %s' % (count), font, windowSurface,128, 40) 263 | 264 | windowSurface.blit(playerImage, playerRect) 265 | 266 | 267 | for b in baddies: 268 | windowSurface.blit(b['surface'], b['rect']) 269 | 270 | pygame.display.update() 271 | 272 | # Check if any of the car have hit the player. 273 | if playerHasHitBaddie(playerRect, baddies): 274 | if score > topScore: 275 | g=open("data/save.dat",'w') 276 | g.write(str(score)) 277 | g.close() 278 | topScore = score 279 | break 280 | 281 | mainClock.tick(FPS) 282 | 283 | # "Game Over" screen. 284 | pygame.mixer.music.stop() 285 | count=count-1 286 | gameOverSound.play() 287 | time.sleep(1) 288 | if (count==0): 289 | laugh.play() 290 | drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)) 291 | drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 30) 292 | pygame.display.update() 293 | time.sleep(2) 294 | waitForPlayerToPressKey() 295 | count=3 296 | gameOverSound.stop() 297 | --------------------------------------------------------------------------------