Error in pupilFrame = cv2.equalizeHist(frame[y+(h*0.25):(y+h), x:(x+w)]) - histogram-equalization

Hello i have this error in complation can any one helpe me please
##ERROR##
raceback (most recent call last):
File "C:\Users\ASUS\Desktop\PFE Master Eye Tracker 2021\PFE_Eye_Tracker_code\opencv-eye-tracking-master\eye_control.py", line 47, in
pupilFrame = cv2.equalizeHist(frame[y+(h*0.25):(y+h), x:(x+w)])
TypeError: slice indices must be integers or None or have an index method
Process finished with exit code -1073740791 (0xC0000409)
##CODE##
This my code
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0) #initialize video capture
left_counter=0 #counter for left movement
right_counter=0 #counter for right movement
th_value=5 #changeable threshold value
def thresholding( value ): # function to threshold and give either left or right
global left_counter
global right_counter
if (value<=54): #check the parameter is less than equal or greater than range to
left_counter=left_counter+1 #increment left counter
if (left_counter>th_value): #if left counter is greater than threshold value
print ('RIGHT') #the eye is left
left_counter=0 #reset the counter
elif(value>=54): # same procedure for right eye
right_counter=right_counter+1
if(right_counter>th_value):
print ('LEFT')
right_counter=0
while 1:
ret, frame = cap.read()
cv2.line(frame, (320,0), (320,480), (0,200,0), 2)
cv2.line(frame, (0,200), (640,200), (0,200,0), 2)
if ret==True:
col=frame
frame = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
pupilFrame=frame
clahe=frame
blur=frame
edges=frame
eyes = cv2.CascadeClassifier('haarcascade_eye.xml')
detected = eyes.detectMultiScale(frame, 1.3, 5)
for (x,y,w,h) in detected: #similar to face detection
cv2.rectangle(frame, (x,y), ((x+w),(y+h)), (0,0,255),1) #draw rectangle around eyes
cv2.line(frame, (x,y), ((x+w,y+h)), (0,0,255),1) #draw cross
cv2.line(frame, (x+w,y), ((x,y+h)), (0,0,255),1)
# using histogram equalization of better image.
pupilFrame = cv2.equalizeHist(frame[y+(h*.25):(y+h), x:(x+w)])
cl1 = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) #set grid size
clahe = cl1.apply(pupilFrame) #clahe
blur = cv2.medianBlur(clahe, 7) #median blur
circles = cv2.HoughCircles(blur ,cv2.cv.CV_HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=7,maxRadius=21) #houghcircles
if circles is not None: #if atleast 1 is detected
circles = np.round(circles[0, :]).astype("int") #change float to integer
print ('integer',circles)
for (x,y,r) in circles:
cv2.circle(pupilFrame, (x, y), r, (0, 255, 255), 2)
cv2.rectangle(pupilFrame, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
#set thresholds
thresholding(x)
#frame = cv2.medianBlur(frame,5)
cv2.imshow('image',pupilFrame)
cv2.imshow('clahe', clahe)
cv2.imshow('blur', blur)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

Change * 0.25 to //4
like this:
from
pupilFrame = cv2.equalizeHist(frame[y+(h*.25):(y+h), x:(x+w)])
to
pupilFrame = cv2.equalizeHist(frame[y+(h//4):(y+h), x:(x+w)])

Related

Pygame get coordinates of colour on image [duplicate]

I would like to get an array which would consist of RGBA code of every pixel in the pygame display
I tried this:
for i in range(SCREEN_WIDTH):
for j in range(SCREEN_HEIGHT):
Pixels.append(pygame.Surface.get_at((i, j)))
But I got an error message that Surface.get_at does not work for tuples so I removed one set of bracket and then it told me that Surface.get_at does not work with integers, so I am confused, how can I get the RGBA value of all pixels? Thank you
EDIT, Ok after a comment I post full runable code:
import pygame
pygame.init()
PPM = 15
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pos_X = SCREEN_WIDTH/PPM/3
pos_Y = SCREEN_HEIGHT/PPM/3
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
FPS = 24
TIME_STEP = 1.0 / FPS
running = True
lead_x = pos_X*PPM
lead_y = pos_Y*PPM
k = 0
Pixels = []
while running:
screen.fill((255, 255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
running = False
if k == 0:
for i in range(SCREEN_WIDTH):
for j in range(SCREEN_HEIGHT):
Pixels.append(pygame.Surface.get_at((i, j)))
k +=1
pygame.draw.rect(screen, (128,128,128), [lead_x, lead_y,50,50])
pygame.display.update()
pygame.display.flip() # Update the full display Surface to the screen
pygame.time.Clock().tick(FPS)
pygame.quit()
And I got these exact error, nothing less and nothing more:
Exception has occurred: TypeError
descriptor 'get_at' for 'pygame.Surface' objects doesn't apply to 'tuple' object
.get_at is a instance function method (see Method Objects) of pygame.Surface. So it has to be called on an instance of pygame.Surface. screen is the Surface object, which represents the window. So it has to be:
Pixels.append(pygame.Surface.get_at((i, j)))
Pixels.append(screen.get_at((i, j)))
respectively
Pixels.append(pygame.Surface.get_at(screen, (i, j)))
To get all pixels value as bytes, you can use
pygame.Surface.get_buffer(screen).raw

How to simulate an object balancing on another in pybullet?

I am trying to simulate a ball balancing on a board with pybullet and openAI gym, but for now I am working with any shapes. I have the gym part down, but I am not sure how to approach this with pybullet. Here is an example of code I wrote up for one object, I want to make that move and balance another object on it. here is the code for the openAI env, and what I have worked on so far to render it with pybullet:
import os import gym import numpy as np import pybullet as pb import pybullet_data import math import random
class BeamEnv(gym.Env):
def __init__(self, obs_low_bounds = np.array([ 0, 0, "TBD", -45]),
obs_high_bounds = np.array([12, 12, "TBD", 45])):
self.physicsClient = pb.connect(pb.GUI) pb.setAdditionalSearchPath(pybullet_data.getDataPath()) self._seed()
"""Environment for a ball and beam system where agent has control of tilt.
Args:
obs_low_bounds (list, optional): [target location(in), ball location(in),
ball velocity(in/s), beam angle(deg)]. Defaults to [ 0, 0, "TBD", -45].
obs_high_bounds (list, optional): As above so below. Defaults to [12, 12, "TBD", 45].
"""
super(BeamEnv, self).__init__()
# Hyperparameters
self.ACC_GRAV = 386.22 # [in/s]
self.MOTOR_SPEED = 46.875 # 1.28[sec/60deg] converted to [deg/s]
self.TIME_STEP = 0.1 # [s]
# Observation Space
# _bounds = []
self.obs_low_bounds = obs_low_bounds
self.obs_high_bounds = obs_high_bounds
self._determine_max_velocity()
self.observation_space = gym.spaces.Box(low = self.obs_low_bounds,
high = self.obs_high_bounds,
dtype = np.float32)
# Action Space
# increase, decrease or keep current angle
self.action_space = gym.spaces.Descrete(3)
# Reward Range
self.reward_range = (-1, 1)
def _set_velocity_bounds(self):
"""Use Inclined Plane and Kinematics Formulas
to determine min/max velocities and set the obs_low/high_bounds
"""
# Max Distance
distance_max = self.obs_high_bounds[1]
# Max Angle
ang_max = self.obs_high_bounds[3]
# Max acceletation (Inclined Plane Formula)
a_max = self.ACC_GRAV * np.sin(np.deg2rad(ang_max))
# Max Velocity (vf^2 = v0^2 + 2ad)
vel_max = np.sqrt(2*a_max*distance_max)
# Set Bounds
self.obs_low_bounds[2] = -vel_max
self.obs_high_bounds[2] = vel_max
def _compute_observation(self): cubePos, cube0rn = pb.getBasePositionAndOrientation(self.botId) cubeEuler = pb.getEulerFromQuaternion(cubeOrn) linear, angular = pb.getBaseVelocity(self.botId) return[cubeEuler[0],angular[0],self.vt]
def _compute_reward(self): _, cubeOrn = pb.getBasePosition(self.botId) cubeEuler = pb.getEulerFromQuaternion(cube0rn) return(1 - abs(cubeEuler[0])) *
0.1 - abs(self.vt - self.vd)
def _compute_done(self): cubePos, _ = pb.getBasePositionAndOrientation(self.botId) return cubePos[2] < 0.15 or self._envStepCounter >= 1500
def reset(self, target_location = None,
ball_location = None):
pb.resetSimulation() pb.setGravity(0,0,-9.8) """default timeStep is 1/240s""" pb.setTimeStep(0.01) planeId = pb.loadURDF('plane.urdf') #loading bot cubeStarPos=[0,0,0.001] cubeStartOrientation = pb.getQuaternionFromEuler([0,0,0]) path = os.path.abspath(os.path.dirname(__file__)) self.botId = pb.loadURDF(os.path.join(path, "beam.xml"), cubeStartPos, cubeStartOrientation) self._observation = self._compute_observation() return np.array(self._observation)
"""Reset the environment so the ball is not moving, there is no angle,
Args:
target_location (float, optional): Desired location of ball. Defaults to random.
ball_location (float, optional): Current location of ball. Defaults to random.
Returns:
list: observation of (target location, ball location, ball velocity, beam angle)
"""
# Set target location
if target_location is not None:
self.target_location = target_location
else:
possible_targets = list(range(self.obs_low_bounds[0], self.obs_high_bounds[0]))
self.target_location = random.choice(possible_targets)
# Set ball location
if ball_location is not None:
self.ball_location = ball_location
else:
possible_ball_locations = list(range(self.obs_low_bounds[1], self.obs_high_bounds[1]))
self.ball_location = random.choice(possible_ball_locations)
# Set Intial Velocity and Angle to Zero
self.ball_velocity = 0 # [in/s]
self.beam_angle = 0 # [deg]
return self._next_observation()
def _next_observation(self):
"""Determines what will happen in the next time step
Returns:
list: observation of (target location, ball location, ball velocity, beam angle)
"""
# Calculate Acceleration (Inclined Plane Equation)
ball_acceleration = self.ACC_GRAV * np.sin(np.deg2rad(self.beam_angle))
# Calculate Next Position (x = x0 + v0t + 0.5at^2)
self.ball_location = self.ball_location + self.ball_velocity * self.TIME_STEP + 0.5 * ball_acceleration * self.TIME_STEP**2
# Calculate New Velocity (v = v0 + at)
self.ball_velocity = self.ball_velocity + ball_acceleration * self.TIME_STEP
# Clip Ball Location
self.ball_location = max(min(self.ball_location,
self.obs_high_bounds[1]),
self.obs_low_bounds[1])
# Clip Ball Velocity
self.ball_velocity = max(min(self.ball_velocity,
self.obs_high_bounds[2]),
self.obs_low_bounds[2])
# Return Observation
return [self.target_location, self.ball_location, self.ball_velocity, self.beam_angle]
def _take_action(self,action):
"""Determines change in angle due to action
Args:
action (int): increase, decrease or keep current angle
"""
# Change action to signs by subtracting by 1 ie (0,1,2) --> (-1,0,1)
action -= 1
# Change the angle by unit step
self.beam_angle = self.beam_angle + action * self.MOTOR_SPEED * self.TIME_STEP
# Clip
self.beam_angle = max(min(self.beam_angle,
self.obs_high_bounds[3]),
self.obs_low_bounds[3])
def step(self, action):
"""Take action, collect reward and get new observation
Args:
action (int): increase, decrease or keep current angle
Returns:
tuple: (observation, reward, done, info)
"""
# Take the action
self._take_action(action)
# Determine Success
if (round(abs((self.target_location - self.ball_location)),3) == 0) & (round(self.ball_velocity, 3) == 0) & (round(self.beam_angle, 3) == 0):
done = True
else:
done = False
# Find Reward
reward = 1 if done else -1
# Find Next Observation
obs = self._next_observation()
# Return what happened
return obs, reward, done, {}
def _seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return[seed]
here is an object in pybullet, the board I will be balancing an object on. I am not sure how to make it move by a variable force or render it based on my openAI gym script.
import numpy
import pybullet as pb
physicsClient = pb.connect(pb.GUI)
> #creates plane import pybullet_data pb.setAdditionalSearchPath(pybullet_data.getDataPath()) planeId =
> pb.loadURDF('plane.urdf')
>
>
> visualShapeId = pb.createVisualShape(
> shapeType=pb.GEOM_MESH,
> fileName='procedural_objects/126/126.obj',
> rgbaColor=None,
> meshScale=[0.1, 0.1, 0.1])
>
> collisionShapeId = pb.createCollisionShape(
> shapeType=pb.GEOM_MESH,
> fileName='procedural_objects/126/126.obj',
> meshScale=[0.1, 0.1, 0.1])
>
> #connects visual shape and collider multiBodyId = pb.createMultiBody(
> baseMass=1.0,
> baseCollisionShapeIndex=collisionShapeId,
> baseVisualShapeIndex=visualShapeId,
> basePosition=[0, 0, 1],
> baseOrientation=pb.getQuaternionFromEuler([0, 0, 0]))
>
> pb.setGravity(0, 0, -9.8) pb.setRealTimeSimulation(1)
> #use setTimeStep fn to override default time step (1/240s)
any advice how to get pybullet to generate a random shape (ignore ball) balancing on another random shape?

return Caffe model results to a html web page

I have a Caffe model which detects objects on a video and show the results as bounding boxes and class lable's of each object. I'm using opencv function "cv2.imshow()" to show the results but I want to show this result on a html web page. I'm not using any frameworks link django.
how should I do this?
this is part of my code I want to show its result on a web page:
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
#frame = vs.read()
ret, frame = cap.read()
frame = imutils.resize(frame, width=400)
# grab the frame dimensions and convert it to a blob
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (400, 300)),
0.008, (400, 300), 128)
# pass the blob through the network and obtain the detections and predictions
net.setInput(blob)
detections = net.forward()
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated with
# the prediction
confidence = detections[0, 0, i, 2]
if confidence > treshHold:
# extract the index of the class label from the
# `detections`, then compute the (x, y)-coordinates of
# the bounding box for the object
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# draw the prediction on the frame
label = "{}: {:.2f}%".format(CLASSES[idx],
confidence * 100)
cv2.rectangle(frame, (startX, startY), (endX, endY),
COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
# show the output frame
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
Compose html page, insert necessary links, write result to a file and you are done.
Check here for example: link

creating a separate module with functions to make another code run in pygame

ok so i dont really understand functions atm and my assignment is to create a separate python module that has all of the functions need to make a program run. the program being supplied by the professor and is already completed and can not be changed by me. im not asking anybody to sit here and do all of the functions them self, although that would be amazing, i just need maybe 1 or two completed and maybe an explanation on how they work. below is completed program given to me.
import pygame
import lab06_bubbles as bubbles
import random
# ### NOTE: In this lab, I *DON'T* want you to change anything in this file. I want you to create
# lab06_bubbles.py so that this works as described in the lab document (and video) ###
# Pygame setup
win_width = 1200
win_height = 800
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode((win_width, win_height))
font = pygame.font.SysFont("Courier New", 12)
clock = pygame.time.Clock()
done = False
numBubbles = random.randint(50, 100) # Initial number of bubbles
numWebs = 2 # Initial number of connections between each bubble
paused = False # Are we paused?
minAreaWidth = 50 # The minimum width of the bubble area
maxAreaWidth = win_width # The maximum width of the bubble area
minAreaHeight = 50 # The minimum height of the bubble area
maxAreaHeight = win_height - 50 # The maximum height of the bubble area
# Generate the initial play area and bubble list
currentArea = bubbles.randomArea(minAreaWidth, minAreaHeight, maxAreaWidth, maxAreaHeight)
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
# Game Loop
while not done:
# #############
# # UPDATE #
# #############
deltaTime = clock.tick() / 1000.0
if paused:
deltaTime = 0.0
bubbles.updateBubbles(bubbleList, currentArea, deltaTime)
# #############
# # INPUT #
# #############
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
elif event.key == pygame.K_LEFT:
numBubbles -= 5
if numBubbles < 5:
numBubbles = 5
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_RIGHT:
numBubbles += 5
if numBubbles > 100:
numBubbles = 100
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_UP:
numWebs += 1
elif event.key == pygame.K_DOWN:
numWebs -= 1
if numWebs < 0:
numWebs = 0
elif event.key == pygame.K_SPACE:
currentArea = bubbles.randomArea(minAreaWidth, minAreaHeight, maxAreaWidth, maxAreaHeight)
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_p:
paused = not paused
# #############
# # DRAW #
# #############
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), currentArea, 1)
bubbles.drawBubbles(bubbleList, screen, numWebs)
screen.blit(font.render("# Bubbles: " + str(len(bubbleList)) + " area: " + str(currentArea) + \
" num_webs: " + str(numWebs), False, (128,128,128)), (0, win_height - 48))
screen.blit(font.render("[Left / Right] : decrease / increase number of bubbles [space]: regenerate bounds [escape]: quit", \
False, (128,128,128)), (0, win_height - 32))
screen.blit(font.render("[Up / Down] : decrease / increase number of connections [p]: pause", False, \
(128,128,128)), (0, win_height - 16))
pygame.display.flip()
# Pygame shutdown
pygame.font.quit()
pygame.display.quit()
this is the function outline module that was given to me and this is where i have no idea what to do.
def randomArea(minW, minH, maxW, maxH):
"""
:param minW: the minimum width of this box
:param minH: the minimum height of this box
:param maxW: the maximum width of this box (normally the width of the "playfield")
:param maxH: the maximum height of this box (normally the height of the "playfield")
:return: a pygame-style rect (x, y, w, h) that fits within the "playfield"
"""
def spawnBubbles(num, area, minSize, maxSize, maxSpeed):
"""
:param num: the number of bubbles to create
:param area: a pygame-style rect (x, y, w, h) that all bubbles should spawn completely inside
:param minSize: the minimum size of a bubble
:param maxSize: the maximum size of a bubble (should fit within the minimum size passed to
randomArea)
:param maxSpeed: the maximum horizontal and vertical speed a bubble should have (in px / s)
:return: A list of lists where each sub-list is of the form [x, y, radius, horiz_speed,
vert_speed]
"""
def getClosest(interest, L, num):
"""
:param interest: the bubble of interest
:param L: the list of all bubbles
:param num: the number of closest bubbles to find
:return: a list of num bubbles (not counting the interest) that are closest to the interest
object
"""
def updateBubbles(L, area, dt):
"""
Makes all bubbles move. If a bubble hits the left / right sides of the area, negate their
horiz_speed and
move them just inside the area; if a bubble hits the top / bottom of the area, negate their
vert_speed and
move them just inside the area.
:param L: The list of all bubbles
:param area: the pygame-style rect bounding the play area.
:param dt: The number of seconds that has passed since the last update
:return: None
"""
def drawBubbles(L, surf, num_webs):
"""
Draws the bubbles and the connections between them. This function calls the getClosest
function internally
:param L: The list of all bubbles
:param surf: The surface to draw to
:param num_webs: The number of connections to draw between bubbles
:return: None
"""
i just need some help with this please. this is what the final product should look like.
First thing I won't do your assignment for you but I can try and help by giving you the following clues:
every time you use the import statement in a python script to import a module (fancy name for another script), Python will go and look for that module in two places:
the current working directory (usually the folder where the script you are working on is)
if it can't find it in the current working directory it will go and look for it in the Python installed libraries.
So the first thing you want, is to make sure that lab06_bubbles is in the same directory as the script you will run.
then, since your professor imports lab06_bubbles as bubbles , everywhere in his program where bubbles.function is mentioned it will go and look for that function in the lab06_bubbles.py file in which you have to build all the functions that the program will need.
Then the professor gives you all the information you need to build the function:
what the arguments are
what the function should return
You, have to do the magic in the middle.
say one of the functions was called getDist with the following description:
def getDist(pointa, pointb):
"""
Takes two points, and return the distance between those points.
:param pointa: a tuple with the x, y coordinates of point a
:param pointb: a tuple with the x, y coordinates of point b
:return: a float representing the distance between the two points
"""
you would need to code the function as follow:
def getDist(pointa, pointb):
xa,ya = pointa
xb,yb = pointb
dist_ab = ((xa-xb)**2+(ya-yb)**2)**0.5
return float(dist_ab)
hope that helps

how do i update time in my program?

i am totally new to python. thus please explain thoroughly wen u respond to my query.
in my code i want to measure the time the player lasts before his cursor touches the bouncing ball on the screen but the time i am obtaining is the sum of all the seconds since the first time the command was initialised. i need to stop the counting of seconds as soon as the user ends the game and to begin afresh wen the play again option is chosen...
also i wud lyk a way to make the player qualify for the next level without usin d detection of position of mouse....since dat is making the program code logic incorrect...
here is my code:
import pygame,sys
from pygame.locals import*
from pygame import *
import random
def main():
# set up sounds
# import pygame
#gameOverSound = pygame.mixer.Sound('gameover.wav')
#pygame.mixer.music.load('background.mid')
#from pygame import *
#import random
#pygame.mixer.pre_init(44100, 16, 2, 4096)
#background =image.load('C:\Users\Administrator\Desktop\oearth.png')
ballpic = image.load('ball1.png')
ballpic.set_colorkey((0,0,0))
#find a way to include verification of more than one colour key
# to add more than one shape....pending
numballs = 10
delay = 5
done = False
balls = []
stars = []
#generate an if loop for execution of both the parts
k = 2
init()
screen = display.set_mode((640, 480))
display.set_caption('mouse game by shivangi and ananya')
event.set_grab(1)
#pygame.time.Clock() Creates a Clock object (assign this to a name), which you can then call the tick() method on
#to find out how much time has passed since the last time you called tick()
#pygame.time.delay(milliseconds) Pauses game for time specified
#pygame.time.get_ticks() Returns the number of milliseconds passed since pygame.init() was #called
for count in range(numballs):
balls.append(dict)
balls[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
screen = display.set_mode((640, 480)) #####screen = display.set_mode((640,480),FULLSCREEN,32).....check functioning...
#pygame.display.list_modes()
#[(800, 600), (1280, 1024), (1280, 960), (1280, 800), (1280, 768), (1280, 720),
#(1152, 864), (1088, 612), (1024, 768), (960, 600), (848, 480), (800, 600),
#(720, 576), (720, 480), (640, 480), (640, 400), (512, 384), (480, 360), (400, 300),
#(320, 240), (320, 200), (640, 480)]
while done == False:
pygame.time.Clock()
init()
screen.fill((0,100,0))
for count in range(numballs):
screen.blit(ballpic, (balls[count]['x'], balls[count]['y']))
display.update()
time.delay(delay)
for count in range(numballs):
balls[count]['x'] = balls[count]['x'] + balls[count]['xmove']
balls[count]['y'] = balls[count]['y'] + balls[count]['ymove']
for count in range(numballs):
if balls[count]['x'] > 620:
balls[count]['xmove'] = random.randint(-2, 0)
if balls[count]['x'] < -10:
balls[count]['xmove'] = random.randint(0, 6)
if balls[count]['y'] > 470:
balls[count]['ymove'] = random.randint(-9, 0)
if balls[count]['y'] < -10:
balls[count]['ymove'] = random.randint(0, 5)
for e in event.get():
if e.type == KEYUP:
if e.key == K_ESCAPE:
done = True
if screen.get_at((mouse.get_pos())) == (227,209,43):
done = True
if done == True:
#pygame.mixer.init()
break
sec = time.get_ticks()/1000
quit()
while sec < k:
print "you lasted for only",sec,"seconds...try again to qualify for the next level..."
quit()
break
time_lasted = 0
while sec >= k:
starpic = image.load('star.png')
starpic.set_colorkey((0,0,0))
#find a way to include verification of more than one colour key...PENDING
numstars = 30
delay = 8
done = False
stars = []
for count in range(numstars):
stars.append(dict)
stars[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
screen = display.set_mode((640, 480))
display.set_caption('mouse game')
event.set_grab(1)
while done == False:
init()
screen.fill((160,32,240))
for count in range(numstars):
screen.blit(starpic, (stars[count]['x'], stars[count]['y']))
display.update()
time.delay(delay)
for count in range(numstars):
stars[count]['x'] = stars[count]['x'] + stars[count]['xmove']
stars[count]['y'] = stars[count]['y'] + stars[count]['ymove']
for count in range(numstars):
if stars[count]['x'] > 620:
stars[count]['xmove'] = random.randint(-2, 0)
if stars[count]['x'] < -10:
stars[count]['xmove'] = random.randint(0, 2)
if stars[count]['y'] > 470:
stars[count]['ymove'] = random.randint(-2, 0)
if stars[count]['y'] < -10:
stars[count]['ymove'] = random.randint(0, 2)
for e in event.get():
if e.type == KEYUP:
if e.key == K_ESCAPE:
done = True
if screen.get_at((mouse.get_pos())) == (255,255,255,255):
done = True
if done == True:
time_lasted = time.get_ticks()/1000
quit()
break
#sec = time.update()
#time_lasted = time.update()
#correction of time error to be done....pending....
quit()
print "You lasted for", sec, "seconds in the first level!"
print "\n"
print "you lasted for",time_lasted,"in the second level!"
print "\n"
print "your total score is :", int(sec) + int(time_lasted)
print "\n"
print "game over...! Thank you for playing!! :D :P :)"
quit()
break
main()
x = 1
x = raw_input("Do you want to play again?")
while x.upper() in ['YES','Y']:
main()
x = raw_input("Do you want to play again?")
while x.upper() in ['NO','N']:
break
# when player starts game
start = time.get_ticks()
# during game
current = time.get_ticks()
time_you_played = (current - start)/1000
EDIT:
Timer to count seconds.
class Timer():
def __init__(self):
self._start = 0
def start(self):
self._start = pygame.time.get_ticks()
def current(self):
return (pygame.time.get_ticks() - self._start)/1000
Example - how to use:
import pygame
# add class Timer here
pygame.init()
t = Timer()
t.start() # start or restart timer
pygame.time.wait(3000) # for test only
print t.current() # print seconds
pygame.time.wait(2000) # for test only
print t.current() # print seconds
You don't have to stop timer because you can use start() to restart timer.