Example #1
0
 def execute(self, board):
     super().execute()
     new_balls = []
     for each_ball in board._balls:
         ball1 = ball(each_ball.x, each_ball.y, each_ball.x_vel,
                      max(each_ball.y_vel, 1), False, each_ball.fire,
                      each_ball.fast_ball, each_ball.gold_ball)
         ball2 = ball(each_ball.x, each_ball.y, each_ball.x_vel,
                      min(-1, -each_ball.y_vel), False, each_ball.fire,
                      each_ball.fast_ball, each_ball.gold_ball)
         new_balls = new_balls + [ball1, ball2]
     board._balls = new_balls
def makeAgents(canvas, indensity, outdensity, size):

    for _ in range(indensity):
        xpos = random.randint(100, 350)
        ypos = random.randint(100, 700)
        t = 1
        agentList.append(ball.ball(xpos, ypos, size, canvas, 0, t))

    for _ in range(outdensity):
        xpos = random.randint(450, 700)
        ypos = random.randint(100, 700)
        t = 2
        agentList.append(ball.ball(xpos, ypos, size, canvas, 0, t))

    return agentList
Example #3
0
def update():
    global ct
    if (ct % 33 == 0):
        for i in range(2):
            xpos = random.randint(100, 350)
            ypos = random.randint(100, 700)
            agents.agentList.append(ball.ball(xpos, ypos, 10, c, 0, 1))
        for i in range(2):
            xpos = random.randint(450, 700)
            ypos = random.randint(100, 700)
            agents.agentList.append(ball.ball(xpos, ypos, 10, c, 0, 2))

    for i in agentsList:
        i.agentFun()
    ct += 1
    c.after(30, update)
Example #4
0
 def test_rotated_vectors(self):
     import keepAway
     keepAwayWorld = keepAway.keepAway(0)
     #intialize agent to position 25,25 with no noise/error, as a keeper, with (357/2, 550/2) as center of field,
     #and 2 as agent speed, and 3 as ball speed
     Agent = agent(keepAwayWorld,(25, 25), 0.0, "keeper", (357/2, 550/2), 2, 3)
     cos5 = math.cos(5.0 * math.pi / 180) #cosine of 3 degress. angle needs to be in radians
     #Agent.receiveListOfOtherPlayers(self.keeperArray, self.takerArray, i)
     testBall = ball.ball((25,25), 3, True)
     Agent.receiveBallReference(testBall)
     v = kUtil.getVector((25,25), (30, 30)) #a vector whose angle is 45 degrees
     answer = Agent.__getRotatedVectors(v, cos5)
     correctAnswer1 = [((math.cos(50 * math.pi / 180)), (math.sin(50 * math.pi/180))),
                       ((math.cos(40 * math.pi / 180)), (math.sin(40 * math.pi/180)))]
     """
     print "answer"
     print answer
     print "correct"
     print correctAnswer1
     """
     for i in range(len(correctAnswer1)):
         for j in range(len(correctAnswer1[i])):
             str1 = "failed at: i = %d "%i
             str2 = "j = %d" %j
             strend = str1 + str2
             self.assertAlmostEqual(answer[i][j], correctAnswer1[i][j], msg=strend)
Example #5
0
    def get_balls(self, number, positions, velocities, radii, masses, anchors):
        '''
        fills the ball list attribute with balls that are defined using the inputs to this function
        
        inputs:
        number = number of balls (int)
        positions = starting position of all of the balls (array_like)
        velocities = starting velocities of all of the balls (array_like)
        radii = radii of all of the balls (array_like)
        masses = mass of all of the balls (array_like)
        anchors = anchor points for all of the balls (array_like)
        '''
        self.number = number

        for i in np.arange(self.number):  #generate the correct number of balls
            spawnedBall = ball(position=np.array(positions[i], dtype=float),
                               velocity=np.array(velocities[i], dtype=float),
                               radius=np.array(radii[i], dtype=float),
                               mass=masses[i],
                               anchor=anchors[i])
            self.ball_list.append(
                spawnedBall
            )  #add the newly create ball object into the list of all balls in the system

        return self.ball_list
Example #6
0
    def __init__(self):
        mode = None #will be set to either monte carlo, q learning, sarsa, or manual control in the intro
        #RGB color
        self.white = (255,255,255) 
        self.black = (0,0,0)
        self.red = (255,0,0)
        self.green = (0,155,0)
        self.blue = (0,0,255)
            
        #give the game a title
        pygame.display.set_caption('Keepaway')
        self.keeperScore = 0
        self.displayGraphics = True
        
        #these are more or less global variables..
        #I'm not sure if this is bad or not. 
        self.worldImage = pygame.image.load('images/soccer_field.png')
        self.ballImage = pygame.image.load('images/ball.png')
        self.keeperImage = pygame.image.load('images/keeper.png')
        self.takerImage = pygame.image.load('images/taker.png')
        #block sizes are used for collision detection
        #only 1 size per element because all blocks are squares. block size = side length
        self.agent_block_size = 23
        self.ball_block_size = 12

        self.maxBallSpeed= 3
        self.maxPlayerSpeed = 2

        
        #dimensions of the game are the same as the soccer field image
        self.display_width = 550
        self.display_height = 357
        self.field_center = (self.display_width / 2 , self.display_height / 2)
        #gameDisplay is a pygame.surface object. it's your screen
        self.gameDisplay = pygame.display.set_mode((self.display_width,self.display_height))
        self.fps = 60 
        self.clock = pygame.time.Clock()
        
        types = ["keeper", "taker"]
        agentSigmaError = .01
        
        #start the ball kinda close to the keeper in the upper left corner
        self.fieldBall = ball.ball( (self.field_center[0]/4, self.field_center[1]/4), self.maxBallSpeed)
        
        #setup all the initial keepers and takers. They are all starting at different field positions, which is why
        #you can't have a for loop just iterate and declare all of them
        self.keeperArray = []
        self.keeperArray.append(agent.agent(self, (12.5, 12.5), agentSigmaError, types[0], self.field_center, self.maxPlayerSpeed, self.maxBallSpeed))
        self.keeperArray.append(agent.agent(self, (25,  self.display_width - 37.5), agentSigmaError, types[0], self.field_center, self.maxPlayerSpeed, self.maxBallSpeed))
        self.keeperArray.append(agent.agent(self, (self.display_height - 37.5,  self.display_width - 37.5), agentSigmaError, types[0], self.field_center, self.maxPlayerSpeed, self.maxBallSpeed))
        self.takerArray = []
        self.takerArray.append(agent.agent(self, (self.display_height - 25,  25), agentSigmaError, types[1], self.field_center, self.maxPlayerSpeed, self.maxBallSpeed))
        self.takerArray.append(agent.agent(self, (self.display_height - 37.5,  50), agentSigmaError, types[1], self.field_center, self.maxPlayerSpeed, self.maxBallSpeed))
        
        #3 different font sizes 
        self.smallfont = pygame.font.SysFont("comicsansms",25) #25 is font sizes
        self.medfont = pygame.font.SysFont("comicsansms",50) 
        self.largefont = pygame.font.SysFont("comicsansms",80) 
        self.verysmallfont = pygame.font.SysFont("comicsansms", 12)
Example #7
0
 def __init__(self, width, height):
     pygame.init()
     self.clock = pygame.time.Clock()
     self.screen = pygame.display.set_mode((width, height))
     self.width = width
     self.height = height
     self.blocks = self.spawnbrick(15,10)
     self.ball = ball.ball(self.width, self.height)
     self.paddle = paddle.paddle(self.width, self.height, self.ball)
Example #8
0
def makeAgents(canvas, num, size):

    for _ in range(num):
        xpos = random.randint(100, 700)
        ypos = random.randint(100, 700)
        t = (xpos + ypos) % 3
        agentList.append(ball.ball(xpos, ypos, size, canvas, 0, t))

    return agentList
Example #9
0
    def find_nearest_ball(self, nodes):
        closest_node = ball.ball(50, glm.vec3(5000,5000,5000))

        nearest = glm.distance(self.pos.center_pos , closest_node.pos.center_pos)
        for n in nodes:
            distance = glm.distance(self.pos.center_pos, n.pos.center_pos)
            if (distance < nearest):
                nearest = distance
                closest_node = n
        return closest_node 
Example #10
0
def create_objs(game_objs):
    new_ball = ball.ball(BALL_DIAMETER,WHITE,BALL_START_POSITION,BALL_MAX_VELOCITYX,BALL_VELOCITYY)
    paddle1 = paddle.paddle(PADDLE_WIDTH,PADDLE_HEIGHT,WHITE,PADDLE_START_POSITIONX,PADDLE1_START_POSITIONY)
    paddle2 = paddle.paddle(PADDLE_WIDTH,PADDLE_HEIGHT,WHITE,PADDLE_START_POSITIONX,PADDLE2_START_POSITIONY)
    screen = pygame.display.set_mode((WW,WH))
    game_objs['ball'] = new_ball
    game_objs['paddle1'] = paddle1
    game_objs['paddle2'] = paddle2
    game_objs['screen'] = screen
    return game_objs
Example #11
0
def init_balls():
    ball_game = ball(pygame, game_constants.ball_image)
    
    ball_game.rect.x = game_constants.game_size.width / 2
    
    
    ball_game.rect.y = game_constants.game_size.height - game_constants.pad_size.height \
                       - game_constants.ball_size.height / 2 
    
    ball_list.add(ball_game)
    
    return ball_game
Example #12
0
    def liveslost(self):
        self.remaining_lives-=1
        self.finish_powerups()
        if self.remaining_lives == 0:
            system('clear')
            self.game_on=-1

        else:
            posn=random.randint(int(self._paddle.y), int(self._paddle.y+self._paddle.length))
            dist_from_centre=self._paddle.get_left_coor()+(self._paddle.get_length())/2-posn
            factor_change=math.floor(dist_from_centre/2.5)
            y_vel=-factor_change*0.5
            self._balls = [ball(global_stuff.rows-2, posn, -1, y_vel)]
Example #13
0
 def __init__(self, genSize, walls = []):
     self.power = 10
     self.maxMoves = 100
     self.gen = 1
     self.genSize = genSize
     self.balls = [ball(self.randomMoves(), randomColor(), self.maxMoves) for x in range(self.genSize)]
     self.cutOff = 0.05
     self.mutationRate = 0.05
     self.delta = 0.5
     self.best = max([x.fitness for x in self.balls])
     self.average = self.averageFitness()
     self.screenHeight = 0
     self.screenWidth = 0
     self.walls = walls
Example #14
0
    def fire2_end(self, event, balls, bullet):
        """Выстрел мячом.

        Происходит при отпускании кнопки мыши.
        Начальные значения компонент скорости мяча vx и vy зависят от положения мыши.
        """
        new_ball = ball.ball(self.canv)
        new_ball.r += 5
        self.an = math.atan((event.y - new_ball.y) / (event.x - new_ball.x))
        new_ball.vx = self.force_power * math.cos(self.an)
        new_ball.vy = -self.force_power * math.sin(self.an)
        balls += [new_ball]
        bullet.append(1)
        self.force_on = 0
        self.force_power = 10
Example #15
0
    def __init__(self, _startX, _startY):

        self.xFieldStart = _startX
        self.yFieldStart = _startY
        self.xFieldSize=1598
        self.yFieldSize=821
        self.xsize=self.xFieldSize
        self.ysize=self.yFieldSize

        self.power_cells=[]
        self.power_cells_location =[]
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2)), (self.yFieldStart+70.48), 0))
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2))-91.44, (self.yFieldStart+70.48), 0))
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2))-182.88, (self.yFieldStart+70.48), 0))
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2)), (self.yFieldStart+self.yFieldSize-70.48), 0))
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2))+91.44, (self.yFieldStart+self.yFieldSize-70.48), 0))
        self.power_cells_location.append(glm.vec3((self.xFieldStart+(self.xFieldSize/2))+182.88, (self.yFieldStart+self.yFieldSize-70.48), 0))


        self.num_power_cells = 20
        for i in range(self.num_power_cells):
            if (i < len(self.power_cells_location)):
                self.power_cells.append(ball.ball(i, self.power_cells_location[i]))
            else:
                self.power_cells.append(ball.ball(i, glm.vec3(int(random.randrange(0,1500)),int(random.randrange(0,900)),0)))

        self.num_robots = 6
        self.robots=[]
        for j in range(self.num_robots):
            self.robots.append(robot.robot(j))

        red = sdl2.ext.Color(255,0,0);
        blue = sdl2.ext.Color(0,0,255);
        self.red_trench = trench.trench(self.xFieldStart+524.68, self.yFieldStart,red)
        self.blue_trench = trench.trench(self.xFieldStart+524.68, self.yFieldStart+self.yFieldSize-130.97,blue)
        self.generator = generator.generator(self.xFieldStart+((self.xFieldStart+self.xFieldSize)/2)-129.69, self.yFieldStart+self.yFieldSize-130.97-459.10)
Example #16
0
    def breed(self, a, b):

        babyColor = (((a.col[0]+b.col[0])/2)+random(-1*self.delta, self.delta), ((a.col[1]+b.col[1])/2)+random(-1*self.delta, self.delta), ((a.col[2]+b.col[2])/2)+random(-1*self.delta, self.delta))
        
        babyMoves = []
        for i in range(len(a.moves)):
            move = []
            if random(1) > 0.5 :
                move = a.moves[i]
            else:
                move = b.moves[i]
            if random(1) < self.mutationRate:
                move = self.mutate(move)
            
            babyMoves.append(move)
        
        return ball(babyMoves, babyColor, self.maxMoves)
Example #17
0
    def __init__(self, num_players, screen):
        info = pygame.display.Info()
        self.num_players = num_players

        # Set ball, player 1 position
        self.balls = [ball.ball(screen)]
        self.player1 = paddle.paddle(screen, 1)

        # Set player 2 positon
        self.__screen = screen
        self.player2 = paddle.paddle(screen, 2)
        self.p1_score = 0
        self.p2_score = 0

        self.ting_sound = pygame.mixer.Sound('reflect.wav')
        self.victory_sound = pygame.mixer.Sound('victory.wav')
        self.defeat_sound = pygame.mixer.Sound('loss.wav')
        self.joysticks = [
            pygame.joystick.Joystick(x)
            for x in range(pygame.joystick.get_count())
        ]
Example #18
0
 def attack(self, dt, character):
     ret = None
     if character.isAlive:
         aim = character.getBodyCenter()
     else:
         aim = [-0.06, 4.67, 0.711]  # gate
     if self.attackCurrTime > self.attackTotalTime:  # an attack end
         self.action = 2
         self.rotationY = self.getRotationYByCurrentPhase()
         self.attackCurrTime = 0
         self.generateAttackCD(False)
     else:
         if self.attackCurrTime > self.attackAimTime:
             if self.attackCurrTime - dt <= self.attackAimTime:  # push a ball out
                 self.rotationY = self.getRotationY(self.position[0],
                                                    self.position[2],
                                                    aim[0], aim[2])
                 ballId = self.id * self.attackMax + self.attackId
                 theta = self.rotationY * 0.0174532925199  # pi/180
                 c = math.cos(theta)
                 s = math.sin(theta)
                 startPoint = [
                     0.62 * c + 0.35 * s + self.position[0],
                     2.1 + self.position[1],
                     -0.62 * s + 0.35 * c + self.position[2]
                 ]
                 ret = ball.ball(ballId, startPoint, aim, self.scene)
                 print "Ghost(%d) Attack<%d>" % (self.id, ballId)
                 self.attackId += 1
             self.action = 2  # wait for animation end
         else:  # aiming
             if self.attackCurrTime == 0:  # animation begin
                 self.action = 3
             else:  # animation already begun
                 self.action = 2
             self.rotationY = self.getRotationY(self.position[0],
                                                self.position[2], aim[0],
                                                aim[2])
         self.attackCurrTime += dt
     return ret
    def ball_movement(self):

        ball_class = ball(self)

        ball_class.ball_bricks()
        ball_class.update_ball_pos()
        ball_class.ball_score()

        if self.get_element_type(global_vars.ball_xpos,
                                 global_vars.ball_ypos) == 'twall':
            ball_class.ball_collision("twall")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == 'lwall':
            ball_class.ball_collision("lwall")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == 'rwall':
            ball_class.ball_collision("rwall")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) in [
                                       "brick1", "brick2", "brick3", "brick4"
                                   ]:
            ball_class.ball_collision("brick")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == "brick5":
            self.add_to_board(global_vars.ball_xpos, global_vars.ball_ypos,
                              "B", dont_add_rainbow_brick())
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == 'bwall':
            ball_class.ball_collision("bwall")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == 'paddle':
            ball_class.ball_collision("paddle")
        elif self.get_element_type(global_vars.ball_xpos,
                                   global_vars.ball_ypos) == 'Boss':
            global_vars.boss_hit += 1
            os.system('aplay -q ./brick.wav&')
            global_vars.score += 20

        ball_class.add_ball_updated_pos()
Example #20
0
def main():
    ball = b.ball(x, y, crad, WIDTH, HEIGHT)
    # y = int(math.floor(FHEIGHT/2))#until i add vector movement
    #tester blurb for ball movement functions
    #black image. maybe add overlayed at some point. 2 ambitious 4 now.
    setwin()
    #ret, fimg = cap.read()
    bimg = np.zeros((HEIGHT, WIDTH, 3), np.uint8)

    while ((ball.xpos + crad) < WIDTH):
        ball.draw(bimg)
        ball.move()
        cv2.imshow(winname, bimg)  #need to see cam feed to debug hand finding

        bimg = np.zeros((HEIGHT, WIDTH, 3),
                        np.uint8)  #so the ball doesnt leave a trail
        cv2.waitKey(2)  #so ball moves at a reasonable speed

    cv2.waitKey(
        0)  #wait for keypress. for debug. will get removed at some point.
    #clean up
    cap.release()
    cv2.destroyAllWindows()
Example #21
0
 def __init__(self, rows, columns, score=0, strttime=0, lives_left=10):
     self._rows=rows
     self._columns=columns
     self._board = np.empty(shape=(rows+1, columns+1), dtype=np.object)
     self._paddle = paddle(rows-1,columns/2)
     posn=random.randint(int(self._paddle.y), int(self._paddle.y+self._paddle.length))
     dist_from_centre=self._paddle.get_left_coor()+(self._paddle.get_length())/2-posn
     factor_change=math.floor(dist_from_centre/2.5)
     y_vel=-factor_change*0.5
     self._balls = [ball(rows-2, posn, -1, y_vel)]
     self._powerups =[]
     self.score=score
     self.remaining_lives=lives_left
     if strttime==0:
         self.start_time=time.time()
     else:
         self.start_time=strttime
     self.game_on=1
     self.level_time=time.time()
     self._bullets=[]
     self.max_score=0
     self.ufo=None
     self.bombs=[]
     self.frame_no=0
Example #22
0
def run_game():

    pygame.init()

    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    screen.fill(ai_settings.bg_color)
    pygame.display.set_caption('Bricka')
    stats = GameStats(ai_settings)
    board = Rectangle(ai_settings, screen)
    target = target_rectangle(ai_settings, screen)
    targets = Group()
    gf.create_fleet(ai_settings, screen, board, targets)
    shoot = ball(ai_settings, screen, board)
    while True:
        gf.check_events(ai_settings, board, screen, targets, shoot, stats)
        board.update(shoot, screen)
        if stats.game_active:
            gf.move_circle(ai_settings, board, screen, targets, shoot, stats)
            gf.check_ball_collision(ai_settings, screen, board, targets, shoot,
                                    stats)
        gf.update_screen(ai_settings, screen, board, targets, shoot, stats)
        pygame.display.flip()
Example #23
0
#open window
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption("MarkPong")

#implementation of paddles
leftPaddle = paddle(WHITE, 10, 100)
leftPaddle.rect.x = 20
leftPaddle.rect.y = 200

rightPaddle = paddle(WHITE, 10, 100)
rightPaddle.rect.x = 670
rightPaddle.rect.y = 200

#create and add ball sprite
ball = ball(WHITE, 10, 10)
ball.rect.x = 345
ball.rect.y = 195

#list that contains all of the sprites
sprites_list = pygame.sprite.Group()

#add paddles to list
sprites_list.add(leftPaddle)
sprites_list.add(rightPaddle)
sprites_list.add(ball)

#loop to keep the game moving
continueGame = True

#update interval
 def __init__(self):
     self.robots = []
     self.our_bots = []
     self.their_bots = []
     self.ball = ball(Circle([0, 0], 0.3, fc="orange"))
Example #25
0
def play_game1():
    #create the mapping object
    mapping = Mapping_for_Tkinter(-300, 300, -300, 300, 600)
    #create window and canvas
    window = tkinter.Tk()
    canvas = tkinter.Canvas(window, width=600, height=600, bg="white")
    canvas.pack()

    # instantiate racket object
    racket_obj = racket(mapping, canvas, 0, mapping.get_ymin() + 5)
    #bind the action of clicking to the mouse with corresponding action
    canvas.bind("<Button-1>", lambda e: racket_obj.shift_left())
    canvas.bind("<Button-3>", lambda e: racket_obj.shift_right())

    # initial values for v and angle
    v = 200
    angle = 53 * math.pi / 180.0

    #create ball object
    ball1 = ball(mapping, canvas, 0, mapping.get_ymin() + 14, v, angle)

    ############################################
    ####### start simulation
    ############################################
    t = 0  # real time between event
    t_total = 0  # real total time

    while True:
        t = t + 0.01  #real time between events- in second
        t_total = t_total + 0.01  #real total time- in second
        side = ball1.update_xy(
            t)  # Update ball position and return collision event
        window.update()  # update the graphic (redraw)

        if side != 0:
            t = 0
            if (side == 2):  #top boundaries
                v = v * 125 / 100.0  #increase velocity by 25%
                angle = random.randrange(-170, -9) * math.pi / 180.0
                ball1.set_velocity(v)
                ball1.set_angle(angle)

        if (ball1.get_current_y() - 14 <= mapping.get_ymin()):

            if (((racket_obj.get_x_position()) - 30 >
                 (ball1.get_current_x() + 4))
                    or ((ball1.get_current_x() - 4) >
                        (racket_obj.get_x_position()) + 30)):
                print("Game over! Total time: %ss" % t_total)
                window.update()
                break
            else:
                angle = 0 - angle
                ball1.set_angle(angle)
                ball1.set_x0(ball1.get_current_x())
                ball1.set_y0(ball1.get_current_y())
                window.update()
                t = 0

        time.sleep(0.01)  # wait 0.01 second (simulation time)
    window.mainloop()  # wait until the window is closed
Example #26
0
def normalizeBallsToWalls(I, ballList):
	'''
	Receives an input of ball positions detected from an image and properly maps them to a pool image table based on wall positions
	'''
	return [ball(int(float(b.pos[0] - I.lr_walls[0]) / (I.lr_walls[1] - I.lr_walls[0]) * (walls['right'] - walls['left']) + walls['left']), int(float(b.pos[1] - I.tb_walls[0]) / (I.tb_walls[1] - I.tb_walls[0]) * (walls['bottom'] - walls['top']) + walls['top']), b.num) for b in ballList]
Example #27
0
from ball import ball
from paddle import paddle
import tensorflow as tf
import keras

pygame.init()

size = width, height = 250, 400
color = (0, 0, 255)
ballColor = (255, 0, 0)

bG = (0, 0, 0)

pygame.display.set_caption('Pong')

boll = ball()
paddleUp = paddle(120, 0)
paddleDown = paddle(100, 380)

print(paddleDown.getWidth())

screen = pygame.display.set_mode(size)
gameExit = False
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: gameExit = True
    screen.fill(bG)
    pygame.draw.rect(screen, color, [
        paddleUp.getWidth(),
        paddleUp.getHeight(),
        paddleUp.getwidth(),
Example #28
0
		for h in self.hits:
			h.join()
		self.totalRunTime = datetime.datetime.now() - self.begTime
		tSum = self.begTime - self.begTime
		suc = 0
		fails = 0
		print "thrashing finished"
		for h in self.hits:
			tSum = tSum + h.timeSpent
			if h.pas:
				suc = suc + 1
			else:
				fails = fails + 1
		ave = tSum/self.numberOfRuns
		self.report["ave"] = ave
		self.report["NumOfSuc"] = suc
		self.report["NumOfFails"] = fails
		self.report["totalTime"] = tSum
		self.report["realTime"] = self.totalRunTime

if __name__ == "__main__":
	ws = "http://127.0.0.1:9000/stressTest"
	da = ball()
	su = None
	su = "task"
	nu = 10000
	t = thrasher(ws, da, nu, su)
	t.start()
	t.join()
	print t.report
Example #29
0
    def __init__(self, inputAgentSigmaNoise=0.1):
        pygame.init()
        # RGB color
        self.__white = (255, 255, 255)
        self.__black = (0, 0, 0)
        self.__red = (255, 0, 0)
        self.__green = (0, 155, 0)
        self.__blue = (0, 0, 255)

        # give the game a title
        pygame.display.set_caption("Keepaway")
        self.keeperScore = 0

        # these are more or less global variables..
        # I'm not sure if this is bad or not.
        self.__worldImage = pygame.image.load("images/soccer_field.png")
        self.__ballImage = pygame.image.load("images/ball.png")
        self.__keeperImage = pygame.image.load("images/keeper.png")
        self.__takerImage = pygame.image.load("images/taker.png")
        self.__predictedImage = pygame.image.load("images/x.png")
        self.__debugYellowDotImage = pygame.image.load("images/yellow_dot.png")
        self.__debugRedDotImage = pygame.image.load("images/red_dot.png")
        # block sizes are used for collision detection
        # only 1 size per element because all blocks are squares. block size = side length
        self.__agent_block_size = 23
        self.ball_block_size = 12

        self.maxBallSpeed = 4
        self.maxPlayerSpeed = 2

        # dimensions of the game are the same as the soccer field image
        self.__display_width = 550
        self.display_height = 357
        self.__field_center = (self.__display_width / 2, self.display_height / 2)
        # gameDisplay is a pygame.surface object. it's your screen
        self.gameDisplay = pygame.display.set_mode((self.__display_width, self.display_height))
        self.test_fps = 60
        self.train_fps = 10000
        self.clock = pygame.time.Clock()

        # start the ball kinda close to the keeper in the upper left corner
        self.fieldBall = ball.ball((self.__field_center[0] / 4, self.__field_center[1] / 4), self.maxBallSpeed)

        # setup all the initial keepers and takers. They are all starting at different field positions, which is why
        # you can't have a for loop just iterate and declare all of them
        types = ["keeper", "taker"]
        self.agentSigmaError = inputAgentSigmaNoise
        self.keeperArray = []
        self.keeperTruePosArray = []
        self.keeperTruePosArray.append((12.5, 12.5))
        self.keeperTruePosArray.append((25, self.__display_width - 37.5))
        self.keeperTruePosArray.append((self.display_height - 37.5, self.__display_width - 37.5))
        self.keeperArray.append(
            agent.agent(
                self,
                0,
                kUtil.getNoisyVals(self.keeperTruePosArray[0], self.agentSigmaError),
                self.agentSigmaError,
                types[0],
                kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError),
                self.maxPlayerSpeed,
                self.maxBallSpeed,
            )
        )
        self.keeperArray.append(
            agent.agent(
                self,
                1,
                kUtil.getNoisyVals(self.keeperTruePosArray[1], self.agentSigmaError),
                self.agentSigmaError,
                types[0],
                kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError),
                self.maxPlayerSpeed,
                self.maxBallSpeed,
            )
        )
        self.keeperArray.append(
            agent.agent(
                self,
                2,
                kUtil.getNoisyVals(self.keeperTruePosArray[2], self.agentSigmaError),
                self.agentSigmaError,
                types[0],
                kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError),
                self.maxPlayerSpeed,
                self.maxBallSpeed,
            )
        )

        self.takerArray = []
        self.takerTruePosArray = []
        self.takerTruePosArray.append((self.display_height - 25, 25))
        self.takerTruePosArray.append((self.display_height - 37.5, 50))
        self.takerArray.append(
            agent.agent(
                self,
                0,
                self.takerTruePosArray[0],
                self.agentSigmaError,
                types[1],
                kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError),
                self.maxPlayerSpeed,
                self.maxBallSpeed,
            )
        )
        self.takerArray.append(
            agent.agent(
                self,
                1,
                self.takerTruePosArray[1],
                self.agentSigmaError,
                types[1],
                kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError),
                self.maxPlayerSpeed,
                self.maxBallSpeed,
            )
        )

        # 3 different font sizes
        self.smallfont = pygame.font.SysFont("comicsansms", 25)  # 25 is font sizes
        self.medfont = pygame.font.SysFont("comicsansms", 50)
        self.largefont = pygame.font.SysFont("comicsansms", 80)
        self.verysmallfont = pygame.font.SysFont("comicsansms", 12)
Example #30
0
def game():
    global count_score
    #-------------- part opencv --------------#
    camera = cv2.VideoCapture(0)
    face_detector = cv2.CascadeClassifier(r'C:\Users\User\workspace-software\Game\OpenCV\haarcascade_frontalface_default.xml')
    camera.set(3, 1280)
    camera.set(4, 720)
    #-----------------------------------------#

    surface1 = pygame.Surface( screen.get_size(), pygame.SRCALPHA )

    obj_ball = ball(surface1)             #สร้างบอลลูกแรก

    count_score = 0

    #Timer
    font = pygame.font.SysFont(None, 45)
    counter = 60
    text = font.render(str(counter), True, white)
    timer_event = pygame.USEREVENT+1
    pygame.time.set_timer(timer_event, 1000)
    text_rect = text.get_rect()
    text_rect.center = (150,15)

    running= True
    while running:

        #------------------- part openCV ----------------#
        ret, frame = camera.read()                                  #  อ่านภาพโดยกล้องเชื่อมกับ opencv
        frame = cv2.resize(frame, (1280, 720))                      # ตั้งขนาดภาพเป็น 1290x720
        frame = cv2.flip(frame,1)                                   #  ทำการกลับด้าน ซ้าย-ขวา

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)              # แปลงสีจากโหมด BGR เป็น RGB เพื่อนำภาพไปใช้ใน pygame ( สีใน opencv จะอยู่ในโหมด BGR และ สีใน pygame จะอยู่ในโหมด RGB)

        frame_show = cv2.transpose(frame)                          
        img = pygame.surfarray.make_surface(frame_show)

        # Convert to grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)              # แปลงสีจากโหมด BGR เป็น GRAY เพื่อนำภาพไปใช้สำหรับ face detection

        faces = face_detector.detectMultiScale(gray, 1.1, 4)        # ทำการ dectect หน้าโดยจะให้ ตำแหน่ง x y ความยาว ความสูง

        # Draw the rectangle around each face
        for (x, y, w, h) in faces:
            pygame.draw.rect(img, (0,255,0), (x,y,x+w, y+h), 3)  #(left,top,width,hight) 
            print((x,y))
            center_face_x, center_face_y  = x+w//2, y+h//2
            if obj_ball.is_collided(center_face_x, center_face_y):
                surface1 = pygame.Surface( screen.get_size(), pygame.SRCALPHA )          # เหมือนการรีเฟรชหน้า surface ใหม่เพื่อลบบอลออก
                count_score += 1                                                       # คะแนน +1
                pygame.time.wait(50)                                                #รอเวลาสักครู้เพื่อขึ้นลูกใหม่
                obj_ball = ball(surface1)

        #------------------------------------------------#

        screen.blit( img , (0,0) )                                  # วางภาพที่แปลงจาก opencv แล้วใน screen pygame

        pygame.draw.rect(screen, black , (0,0,1280,60))

        create_text('TIME : ' ,80,30)

        screen.blit(text, text_rect.center)

        create_text('SCORE :    ' + str(count_score) ,1150,30)

        mx2, my2 = pygame.mouse.get_pos()
        button_2 = pygame.Rect(1180,670,100,50) #(left,top,width,hight)

        pygame.draw.rect(screen, red , button_2)
        create_text('EXIT',1230,700)


        if button_2.collidepoint((mx2, my2)):
            if click:
                score()

        click = False
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == timer_event:
                counter -= 1
                text = font.render(str(counter), True, white)
                if counter == 0:
                    pygame.time.set_timer(timer_event, 0)
                    time_up()
                    camera.release()
                    cv2.destroyAllWindows()

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit() 
                    sys.exit()
                    camera.release()
                    cv2.destroyAllWindows()
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                if obj_ball.is_collided(mx2, my2):
                    surface1 = pygame.Surface( screen.get_size(), pygame.SRCALPHA )          #เหมือนการรีหน้า surface ใหม่เพื่อลบบอลออก
                    count_score += 1
                    pygame.time.wait(50)                                                #รอเวลาสักครู่เพื่อขึ้นลูกใหม่
                    obj_ball = ball(surface1)


        screen.blit( surface1 , (0,0) )

        pygame.display.update()
        clock.tick(60) 
Example #31
0
            h.join()
        self.totalRunTime = datetime.datetime.now() - self.begTime
        tSum = self.begTime - self.begTime
        suc = 0
        fails = 0
        print "thrashing finished"
        for h in self.hits:
            tSum = tSum + h.timeSpent
            if h.pas:
                suc = suc + 1
            else:
                fails = fails + 1
        ave = tSum / self.numberOfRuns
        self.report["ave"] = ave
        self.report["NumOfSuc"] = suc
        self.report["NumOfFails"] = fails
        self.report["totalTime"] = tSum
        self.report["realTime"] = self.totalRunTime


if __name__ == "__main__":
    ws = "http://127.0.0.1:9000/stressTest"
    da = ball()
    su = None
    su = "task"
    nu = 10000
    t = thrasher(ws, da, nu, su)
    t.start()
    t.join()
    print t.report
def ball_initialisation(position, velocity, radius, mass, anchor):
    test_ball = ball(position, velocity, radius, mass, anchor)
    return test_ball
from tkinter import *
from ball import ball

gui = Tk()
gui.geometry("800x800")
c = Canvas(gui, bg='white', width=800, height=800)
c.pack()
b1 = ball(100, 100, 20, c, 5, 400, 'blue', False, False, False, False, 100,
          100)
b1.agentFun()

gui.mainloop()
Example #34
0
# Simple Pong game using python 3
# Only for learning syntaxes
import turtle

import game_window as wnd
import paddles as paddle
import ball
import score_system

#Global
wd = wnd.window_settings(turtle)
paddle_a = paddle.paddle_a(turtle)
paddle_b = paddle.paddle_b(turtle)
ball = ball.ball(turtle)

#Score
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)


def paddle_a_up():
    y = paddle_a.ycor()
    y += 20
    paddle_a.sety(y)


def paddle_a_down():
Example #35
0
from ball import ball
from paddle import paddle

# Initilize
pygame.init()
pygame.display.set_caption("Pong game")
loop = True
clock = pygame.time.Clock()
BG_COLOR = (47, 62, 63)

# Set up game window
SIZE = (800, 600)
canvas = pygame.display.set_mode(SIZE)

# Create object
ball = ball(400, 300)
paddle1 = paddle(100, 300)
paddle2 = paddle(685, 300)
paddle_list = [paddle1, paddle2]

while loop:
    # Pooling
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            loop = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                paddle1.up_press = True
            if event.key == pygame.K_s:
                paddle1.down_press = True
import player
import random
import ball


players1 = list()
for i in range(0, 5):
    p = player.player(i, 0, 600, 150)
    players1.append(p)

players2 = list()
for i in range(0, 5):
    p = player.player(i, 1, 0, 150)
    players2.append(p)

b = ball.ball(300, 150, 300, 150, 300, 150)


def find_nearest_playerest_to_ball_1(bx, by):
    ls = list()
    for i in range(0, 5):
        d = (players1[i].pos_current_x - bx) ** 2.0
        d = d + (players1[i].pos_current_y - by) ** 2.0
        d = d ** 0.5
        ls.append((d, i))
    ls = sorted(ls)
    return ls[0]


def find_nearest_playerest_to_ball_2(bx, by):
    ls = list()
Example #37
0
    def __init__(self):

        self.display1 = display.display()
        self.ball1 = ball.ball(34, 61)
        self.slider = slider.slider(35, 57)
Example #38
0
					sys.exit()
	def initializeHitFromCue(cue1, cue2):
		'''Creates a hit on the cue ball from the cue in the event that the cue is aligned to hit the cue ball'''
		cueBall = self.ballList[0]
		dx = cue1[0] - cue2[0]
		dy = cue1[1] - cue2[1]
		xspace = np.linspace(cue1[0], cue2[0], max(int(dx), int(dy)))
		yspace = np.linspace(cue1[1], cue2[1], max(int(dx), int(dy)))
		for i in range(xspace): # double check this later to make sure these line up with points on the line
			if(math.sqrt((xspace[i] - cueBall.pos[0])**2 + (yspace[i] - cueBall.pos[1])**2) < (cueBall.radius)):
				t.initializeHit(dx, dy)
				break

if __name__ == '__main__':
	'''Sample running of the table class'''
	ball1 = ball(200, 300, 0)
	ball2 = ball(700, 290, 1)
	ball3 = ball(900, 250, 2)
	ball4 = ball(800, 250, 3)
	ball5 = ball(845, 150, 4)
	ball6 = ball(700, 790, 5)
	ball7 = ball(900, 150, 6)
	ball8 = ball(800, 650, 7)
	ball9 = ball(1245, 150, 8)
	t = Table([ball1, ball2, ball3, ball4, ball5, ball6, ball7, ball8, ball9])
	t.initializeHit(400, -250) # test collision between balls
	# t.initializeHit(100, 50) # test wall bouncing
	t.draw_table()
	t.draw_projection()

Example #39
0
	def __init__(self, inputAgentSigmaNoise = .1, alreadyTrained = True, bevCustomTileSize = None):
		pygame.init()
		#RGB color
		self.__white = (255,255,255) 
		self.__black = (0,0,0)
		self.__red = (255,0,0)
		self.__green = (0,155,0)
		self.__blue = (0,0,255)
		
		#give the game a title
		pygame.display.set_caption('Keepaway')
		self.keeperScore = 0
		
		#these are more or less global variables..
		#I'm not sure if this is bad or not. 
		self.__worldImage = pygame.image.load('images/soccer_field.png')
		self.__ballImage = pygame.image.load('images/ball.png')
		self.__keeperImage = pygame.image.load('images/keeper.png')
		self.__keeperGoldImage = pygame.image.load('images/keeperGold.png')
		self.__takerImage = pygame.image.load('images/taker.png')
		self.__predictedImage = pygame.image.load('images/x.png')
		self.__debugYellowDotImage = pygame.image.load('images/yellow_dot.png')
		self.__debugRedDotImage = pygame.image.load('images/red_dot.png')
		self.__debugBlackDotImage = pygame.image.load('images/black_dot.png')
		self.__debugWhiteDotImage = pygame.image.load('images/white_dot.png')
		self.__debugBlueDotImage = pygame.image.load('images/blue_dot.png')
		self.__debugTakerPathTile = pygame.image.load('images/takerPathSquare.png')
		self.__debugKeeperPathTile = pygame.image.load('images/keeperPathSquare.png')
		self.__debugKeeperTile = pygame.image.load('images/keeperSquare.png')
		self.__debugTakerTile = pygame.image.load('images/takerSquare.png')
		self.__debugEmptyTile = pygame.image.load('images/emptySquare.png')
		self.__debugTakerPathTileTwo = pygame.image.load('images/takerPathSquare2.png')
		self.__debugKeeperPathTileTwo = pygame.image.load('images/keeperPathSquare2.png')
		#block sizes are used for collision detection
		#only 1 size per element because all blocks are squares. block size = side length
		self.__agent_block_size = 23
		self.__ball_block_size = 12

		self.maxBallSpeed= 4
		self.maxPlayerSpeed = 2
		#self.rDecision = None

		
		#dimensions of the game are the same as the soccer field image
		self.__display_width = 550
		self.__display_height = 357
		self.displayGraphics = True
		self.__field_center = (self.__display_width / 2 , self.__display_height / 2)
		#gameDisplay is a pygame.surface object. it's your screen
		self.gameDisplay = pygame.display.set_mode((self.__display_width,self.__display_height))
		self.test_fps = 60
		self.train_fps = 10000
		self.clock = pygame.time.Clock()
		
		
		#start the ball kinda close to the keeper in the upper left corner
		self.fieldBall = ball.ball( (self.__field_center[0]/4, self.__field_center[1]/4), self.maxBallSpeed)
		
		#the simple state variables for agents like NEAT, novelty search, and maybe sarsa
		self.simpleStateVars = None
		
		self.alreadyTrained = alreadyTrained  #False if you want agent to learn and True if you want to demo
		
		#setup all the initial keepers and takers. They are all starting at different field positions, which is why
		#you can't have a for loop just iterate and declare all of them
		types = ["keeper", "taker"]
		self.agentSigmaError = inputAgentSigmaNoise
		self.keeperArray = []
		self.keeperTruePosArray = []
		self.keeperTruePosArray.append((12.5, 12.5))
		self.keeperTruePosArray.append((25,  self.__display_width - 37.5))
		self.keeperTruePosArray.append((self.__display_height - 37.5,  self.__display_width - 37.5))
		self.keeperArray.append(agent.agent(self, 0, kUtil.getNoisyVals( self.keeperTruePosArray[0], self.agentSigmaError), self.agentSigmaError, types[0], kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError), self.maxPlayerSpeed, self.maxBallSpeed))
		self.keeperArray.append(agent.agent(self, 1, kUtil.getNoisyVals( self.keeperTruePosArray[1], self.agentSigmaError), self.agentSigmaError, types[0], kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError), self.maxPlayerSpeed, self.maxBallSpeed))
		self.keeperArray.append(agent.agent(self, 2, kUtil.getNoisyVals( self.keeperTruePosArray[2], self.agentSigmaError), self.agentSigmaError, types[0], kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError), self.maxPlayerSpeed, self.maxBallSpeed))
		
		self.takerArray = []
		self.takerTruePosArray = []
		self.takerTruePosArray.append((self.__display_height - 25,  25))
		self.takerTruePosArray.append((self.__display_height - 37.5,  50))
		self.takerArray.append(agent.agent(self, 0, self.takerTruePosArray[0], self.agentSigmaError, types[1], kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError), self.maxPlayerSpeed, self.maxBallSpeed))
		self.takerArray.append(agent.agent(self, 1, self.takerTruePosArray[1], self.agentSigmaError, types[1], kUtil.getNoisyVals(self.fieldBall.trueBallPos, self.agentSigmaError), self.maxPlayerSpeed, self.maxBallSpeed))
		
		#3 different font sizes 
		self.smallfont = pygame.font.SysFont("comicsansms",25) #25 is font sizes
		self.medfont = pygame.font.SysFont("comicsansms",50) 
		self.largefont = pygame.font.SysFont("comicsansms",80) 
		self.verysmallfont = pygame.font.SysFont("comicsansms", 12)
		
		#birdsEyeView generator for agents like hyperNEAT:
		if bevCustomTileSize == None:
			bevCustomTileSize = self.__agent_block_size
		self.bev = birdsEyeView.birdsEyeView(self.__display_width, self.__display_height, bevCustomTileSize, self.__ball_block_size )
		self.bev_grid_as_grid = self.bev.getBirdsEyeView(self.keeperArray, self.takerArray);
		self.bev_grid_as_list = self.bev.getBirdsEyeViewAsList(self.keeperArray, self.takerArray);
		self.bev_substrate = self.bev.getSubstrate(self.keeperArray, self.takerArray);
		self.bev_keeper_sub_index = self.bev.getBallHolderTile(self.keeperArray)