def __resolve_collisions(self):
		old_pos = vector2.vector2(self.position.x,self.position.y)
		old_speed = vector2.vector2(self.speed.x,self.speed.y)
		
		for tiles in self.__get_colliding_tiles():
			if tiles.collidable:
				depth = cl.AABB_intersection_depth(self.position.x,self.position.y,self.image.get_width(),self.image.get_height(),
											tiles.x,tiles.y,tiles.image.get_width(),tiles.image.get_height())
				if(fabs(depth.x) > 0.05 or fabs(depth.y) > 0.05):
					absDepthX = fabs(depth.x)
					absDepthY = fabs(depth.y)
					if(absDepthY < absDepthX):
						self.position = vector2.vector2(self.position.x,self.position.y + depth.y)
					else:
						#if under your feet
						if fabs(tiles.y - (self.position.y + self.image.get_height() - self.speed.y)) < 0.05:
							#if depth.x > 0.05 or tiles.y > self.position.y + self.image.get_height():
							None
						#not under your feet
						else:
							self.position = vector2.vector2(self.position.x + depth.x, self.position.y)
		
		if(fabs(old_pos.x - self.position.x) > 0.05):
			#print "stopped x because resolved %f" % (old_pos.x - self.position.x)
			self.speed.x = 0
			self.acceleration.x = 0
		if(fabs(old_pos.y - self.position.y) > 0.05):
			self.speed.y = 0
		if(old_speed.y > 0 and fabs(self.speed.y) < 0.05 and self.in_air):
			self.__on_hit_floor()
Exemple #2
0
    def draw(self, screen):
        #Change color if its hiding the figure
        default_color = self.color
        if (self.shape_visible == True):
            self.outline = 2
            self.color = self.shape_color
        else:
            self.outline = 0

        super().draw(screen)
        self.color = default_color

        if self.shape_visible == False:
            return

        #Draw figure
        size = self.size.x
        if self.size.x > self.size.y:
            size = self.size.y
        size *= 0.7
        size = int(size // 2)

        center = vector2(self.position.x, self.position.y)
        center += vector2(self.size.x / 2, self.size.y / 2)

        #Select the figure to draw
        if self.shape == FigureButton.shape_circle:
            pygame.draw.circle(screen, self.shape_color,
                               center.as_int().as_tuple(), size)
        elif self.shape == FigureButton.shape_triangle:
            figure = FigureButton.get_polygon(3, center, size, -90)
            pygame.draw.polygon(screen, self.shape_color, figure)
        elif self.shape == FigureButton.shape_square:
            figure = FigureButton.get_polygon(4, center, size, -45)
            pygame.draw.polygon(screen, self.shape_color, figure)
Exemple #3
0
    def test_find_entities(self):
        test_guy = TestPosHaver(pos=vector2.vector2(0,0))
        test_guy_2 = TestPosHaver(pos=vector2.vector2(3,3))
        test_guy_3 = TestPosHaver(pos=vector2.vector2(7,7))

        def selector(ent):
            return True

        nearest = self.engine.metagrid.find_nearest(3,3,0,max_dist=5,selector=selector)

        self.assertEqual(nearest, test_guy_2)
Exemple #4
0
    def get_position(self, text):
        pos = self.rect.position

        # OFFSET
        pos += self.offset
        size  = self.rect.size


        # ALIGN
        if(self.align == Text.align_center):
            pos += vector2(size.x // 2, 0)
            pos -= vector2(text.get_width() // 2, 0)
        elif(self.align == Text.align_right):
            pos += vector2(size.x, 0)
            pos -= vector2(text.get_width(), 0)
        
        #JUSTIFY
        if(self.justify == Text.justify_center):
            pos += vector2(0, size.y // 2)
            pos -= vector2(0, text.get_height() // 2)
        elif(self.justify == Text.justify_bottom):
            pos += vector2(0, size.y)
            pos -= vector2(0, text.get_height())

        return pos
Exemple #5
0
def gen_shape(x, y):
    pts = []
    num_pts = randint(4, 10)
    col_r = randint(10, 255)
    col_g = randint(10, 255)
    col_b = randint(10, 255)
    colour = pygame.Color(col_r, col_g, col_b)
    for i in range(0, num_pts/2):
         pts.append(vector2(randint(-vex.radius, 0), 
             randint(-vex.radius, vex.radius)))
    pts_rev = pts[:]
    pts_rev.reverse()
    for i in pts_rev:
        pts.append(vector2(-i.x, i.y))
    return vex(x, y, colour, pts, 2)
Exemple #6
0
def spring_force(obj1, obj2, k, l):
    r = obj1.pos - obj2.pos
    rmag = r.mag()
    if rmag > obj1.radius + obj2.radius:
        return -k * (rmag - l) * r.hat()
    else:
        return vector2(0, 0)
 def __init__(self):
     self.__tilemap = list()
     self.__tileset = dict()
     self.spawnpos = vector2.vector2(0, 0)
     self.map_enemies = list()
     # no-op tile
     self.add_tile(None, ".")
Exemple #8
0
    def __init__(self, pos, points, color=(0, 0, 0)):
        super().__init__(0, pos)
        self.normals = []
        self.color = color
        self.points = []
        for p in points:
            self.points.append(vector2(p))
        for i in range(len(points)):
            self.normals.append(
                (self.points[i] - self.points[i - 1]).perp().hat())
#            print(self.normals[i])

        for i in range(len(self.normals)):
            for p in self.points:
                positive = 0
                negative = 0
                d = (p - self.points[i]) * self.normals[i]
                if d > 0:
                    positive += 1
                elif d < 0:
                    negative += 1
                if positive > 0:
                    if negative == 0:
                        self.normals[i] *= -1
                    else:
                        print("This is a Non-convex polygon")
	def restart_level(self):
		print "respawning at %f %f" % (self.tile_map_for_data.spawnpos.x,self.tile_map_for_data.spawnpos.y)
		self.position = vector2.vector2(self.tile_map_for_data.spawnpos.x,self.tile_map_for_data.spawnpos.y)
		bullet.bullet_list = list()
		self.bullet_ammo = self.bullet_reload_ammo
		self.bullet_reload_time = 0
		enemy.spawn_enemies(self.tile_map_for_data)
Exemple #10
0
def hole_force(obj1, obj2, G):
    r = obj1.pos - obj2.pos
    rmag = r.mag()
    if rmag > obj1.radius + obj2.radius and rmag != 0 and r != 0:
        return -G / (obj1.invmass * obj2.invmass * r.mag2()) * r.hat()
    else:
        return vector2(0, 0)
Exemple #11
0
def gravity_force(obj1, obj2, G):
    r = obj1.pos - obj2.pos
    rmag = r.mag()
    if rmag > obj1.radius + obj2.radius:
        return -G / (obj1.invmass * obj2.invmass * r.mag2()) * r.hat()
    else:
        return vector2(0, 0)
Exemple #12
0
def makeYummys():
    enemys = 10
    yumLIST.add(
        Yummy(vector2(randrange(100, 1300), 0), DISPLAYSURF, vector2(0, 1),
              1.5, 30))

    while enemys > 0:
        randx = randrange(50, 650)
        randy = randrange(-1000, 0)

        if randx > 10 and randx < WINDOWWIDTH - 40:
            v1 = vector2(randx, randy)
            v2 = vector2.fromPoints((randx, randy), (randx, WINDOWHEIGHT - 1))
            v2 = v2.normalizeV2()
            enemyList.add(
                Yummy(v1, DISPLAYSURF, v2, randint(1, 2), randint(35, 50)))
            enemys -= 1
Exemple #13
0
    def __init__(self, screen, rows=0, columns=0):
        super().__init__()
        self.cards = []
        self.screen = screen
        self.cards_offset = 10
        self.card_size = vector2(70, 100)
        self.selected_cards = []
        self.on_exit = None
        self.score = 0
        self.wrong_attempts = 0

        # SCORE TEXT
        self.score_text = Text(Rect(vector2(20, 20), vector2(150, 50)),
                               Game.defaultScoreText + str(self.score))
        self.score_text.justify = Text.justify_up
        self.score_text.align = Text.align_left
        self.childs.append(self.score_text)

        # EXIT BUTTON
        x, y = screen.get_size()
        exit_button = TextButton(vector2(20, y - 70), vector2(150, 50), "Exit")
        exit_button.on_click = lambda game=self: game.on_exit_game()
        self.childs.append(exit_button)

        # WIN TEXT
        self.win_text = Text(Rect(vector2(0, 0), vector2(x, y)),
                             "Congratulations!")
        self.childs.append(self.win_text)

        if rows != 0 and columns != 0:
            self.new_game(rows, columns)
        else:
            self.is_visible = False
Exemple #14
0
 def __init__(self,
              mass,
              pos,
              vel,
              radius,
              color=(0, 0, 0),
              gravity=vector2(0, 0)):
     super().__init__(mass, pos, vel, gravity)
     self.radius = radius
     self.color = color
Exemple #15
0
 def __init__(self, rect, text = "Button", size = 25, color = (255,255,0)):
     super().__init__()
     self.rect = rect
     self.text = text
     self.size = size
     self.color = color
     self.justify = Text.justify_center
     self.align = Text.align_center
     self.offset = vector2()
     self.font = pygame.font.Font("NotoSans-Regular.ttf", 20)
Exemple #16
0
    def __init__(self, screen, game):
        super().__init__()
        
        self.game = game

        #BUTTONS SETTINGS
        size = vector2(150, 50)
        gameModes = [(4,3),(4,4),(5,4),(6,5),(6,6)]
        rows = len(gameModes)
        dist_offset = 10
        #offset to center on screen
        offset = vector2()
        offset.x = (screen.get_width() - size.x)/2
        offset.y = (screen.get_height() - ((rows - 1) * dist_offset + rows * size.y)) / 2
        #offset to move a bit manually
        offset += vector2(0, 30)

        #CREATE LEVEL BUTTONS
        for y in range(rows):
            mode = gameModes[y]
            pos = vector2(offset.x, (y * (dist_offset + size.y) + offset.y))
            b = TextButton(pos, size, str(mode[0]) + " x " + str(mode[1]))
            b.on_click = lambda menu=self, mode=mode : menu.start_game(mode)
            self.childs.append(b)

        #CREATE EXIT BUTTON
        pos = vector2(offset.x, ((rows +1) * (dist_offset + size.y) + offset.y))
        exit_button = TextButton(pos, size, "Exit")
        exit_button.on_click = lambda : sys.exit()
        self.childs.append(exit_button)

        #CREATE IMAGE
        img = Image("shuffle.png", offset + vector2(50, -100))
        self.childs.append(img)
Exemple #17
0
    def get_polygon(sides, position, radius=1, rotation=0):
        points = []
        angle = 360 / sides

        for i in range(sides):
            a = i * angle + rotation
            a = math.radians(a)
            v = vector2(math.cos(a), math.sin(a))
            v *= radius
            v += position
            points.append(v.to_int().as_tuple())

        return points
	def __shoot_bullet(self):
		bullet_offset = 10
		if ((self.bullet_ammo > 0) and (self.bullet_reload_time is 0)):
			new_bullet_position = vector2.vector2(self.position.x - bullet_offset,self.position.y + self.image.get_height()/2)
			print ("spawned bullet at %d %d") % (new_bullet_position.x, new_bullet_position.y)
			#if player facing right, offset bullet spawn position to his right side
			if(self.direction == 1):
				new_bullet_position.x += self.image.get_width() + 2*bullet_offset
				
			self.bullet_ammo -= 1
		
			#spawn bullet at new_bullet_position with speed left or right depending on facing direction	
			bullet.bullet_list.append(bullet.bullet(new_bullet_position.x,new_bullet_position.y,bullet.bullet_speed * self.direction,0))
Exemple #19
0
    def test_move_entity(self):

        test_guy = TestPosHaver(pos=vector2.vector2(3,3))
        self.assertEqual(self.engine.get_entities(3,3)[0], test_guy)


        num_cells = metagrid.GRID_SIZE*metagrid.METAGRID_SIZE
        new_pos = None
        for x in range(num_cells):
            while not new_pos or new_pos == test_guy.pos:
                new_pos =   vector2.vector2(random.randint(0,num_cells-1),
                                              random.randint(0,num_cells-1))

            old_pos = test_guy.pos

            test_guy.move(new_pos)
            self.engine.update()

            self.assertEqual(self.engine.get_entities(new_pos.x,new_pos.y)[0], test_guy)
            self.assertEqual(self.engine.get_entities(old_pos.x,old_pos.y),{}) 

        test_guy.die()
        self.engine.update()
        self.assertEqual(self.engine.get_entities(new_pos.x,new_pos.y),{}) 
def AABB_intersection_depth(x1,y1,w1,h1,x2,y2,w2,h2):
	halfw1 = w1/2.0
	halfh1 = h1/2.0
	halfw2= w2/2.0
	halfh2 = h2/2.0
	center1 = vector2.vector2(x1 + halfw1, y1 + halfh1)
	center2 = vector2.vector2(x2 + halfw2, y2 + halfh2)
	distX = center1.x - center2.x
	distY = center1.y - center2.y
	minDistX = halfw1 + halfw2
	minDistY = halfh1 + halfh2
	
	if(fabs(distX) >= minDistX or fabs(distY) >= minDistY):
		return vector2.vector2(0,0)
	if(distX > 0):
		depthX = minDistX - distX
	else:
		depthX = -minDistX - distX
	if(distY > 0):
		depthY = minDistY - distY
	else:
		depthY = -minDistY - distY
	
	return vector2.vector2(depthX,depthY)
Exemple #21
0
 def __init__(self, mass, pos, vel=vector2(0, 0), gravity=vector2(0, 0)):
     if mass == 0:
         self.invmass = 0
     else:
         self.invmass = 1.0 / mass
     self.pos = vector2(pos)
     self.vel = vector2(vel)
     self.gforce = mass * vector2(gravity)
     self.force = vector2(self.gforce)
     self.interactions = []
     self.contacts = []
Exemple #22
0
    def load(self, filename):
        try:
            mapdata = open(filename + ".map", "r").read()
            current_character = 0
            row = 0
            while current_character < len(mapdata):
                self.__tilemap.append([])
                while True:
                    if current_character >= len(mapdata):
                        break
                    if mapdata[current_character] == "\n":
                        break
                        # prototype for the tile as predetermined in the tileset
                    proto = self.__tileset[mapdata[current_character]]
                    print "creating tile %s at %d %d" % (
                        proto.name,
                        len(self.__tilemap[row]) * tile_size,
                        row * tile_size,
                    )
                    new_tile = tile(
                        proto.image, proto.name, proto.collidable, len(self.__tilemap[row]) * tile_size, row * tile_size
                    )
                    self.__tilemap[row].append(new_tile)
                    current_character += 1

                current_character += 1
                row += 1

            mappointfile = open(filename + ".dat", "r")
            if mappointfile:
                mappointfile = mappointfile.read()
            mappointfile = mappointfile.split("\n")
            for row in range(len(mappointfile)):
                curr_line = mappointfile[row].split(" ")
                if curr_line[0] == "spawn":
                    self.spawnpos = vector2.vector2(float(curr_line[1]), float(curr_line[2]))
                elif curr_line[0] == "enemy":
                    self.map_enemies.append([curr_line[1], int(curr_line[2]), int(curr_line[3])])
        except:
            None
Exemple #23
0
 def __init__(self, pos, normal, color=(0, 0, 0), length=1000):
     super().__init__(0, pos, vector2(0, 0), vector2(0, 0))
     self.normal = normal.hat()
     self.color = color
     self.length = length
Exemple #24
0
def main():

    pygame.init()
    mixer.init()
    mixer.music.load('musiz.wav')
    mixer.music.play(loops=-1, start=0)
    pygame.mixer.music.set_volume(.35)

    score = 0
    lives = 5
    tillNextLife = 1

    numEnemies = 1

    backgroundImageName = 'BG2.jpg'

    BGImage = pygame.image.load(backgroundImageName)

    BGImage = pygame.transform.scale(BGImage, (WINDOWWIDTH, WINDOWHEIGHT))

    ##### vector 1 creation
    ##TEMPvector = vector2.fromPoints(())

    shipx = WINDOWWIDTH // 2
    shipy = WINDOWHEIGHT - 75

    check = True

    currentDirection = "left"

    makeYummys()
    makeEnemy()

    movex, movey = 0, 0

    # main game loop
    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
                elif event.key == K_RIGHT or event.key == K_d:
                    movex += 10
                    currentDirection = "right"
                elif event.key == K_LEFT or event.key == K_a:
                    movex -= 10
                    currentDirection = "left"
                elif event.key == K_UP or event.key == K_w:
                    movey -= 10
                    currentDirection = "up"
                elif event.key == K_DOWN or event.key == K_s:
                    movey += 10
                    currentDirection = "down"

            elif event.type == KEYUP:

                if event.key == K_DOWN or event.key == K_s:
                    movey -= 10

                elif event.key == K_UP or event.key == K_w:
                    movey += 10
                elif event.key == K_LEFT or event.key == K_a:
                    movex += 10
                elif event.key == K_RIGHT or event.key == K_d:
                    movex -= 10
                elif event.key == K_SPACE:
                    check = True
                    ##bulletLIST.add(bullet(ssPOS, DISPLAYSURF, vector1, 30, 30))

        DISPLAYSURF.blit(BGImage, (0, 0))
        shipx += movex
        shipy += movey

        ssPOS = vector2(shipx, shipy)

        playa = makePlayer(ssPOS)
        w = playa.WIDTH
        h = playa.HEIGHT

        if len(yumLIST) < 6:
            makeYummys()

        if len(enemyLIST) < numEnemies:
            makeEnemy()

        ## calculating how many till the next life
        if score < 50:
            tillNextLife = 50 - score
        elif score == 50:
            tillNextLife = 0
        elif score > 50 and score < 120:
            tillNextLife = 120 - score
        elif score == 120:
            tillNextLife = 0
        elif score > 120 and score < 200:
            tillNextLife = 200 - score
        elif score == 200:
            tillNextLife = 0

        ## defining the amount of enemies based on score
        if score > 20 and score < 50:
            numEnemies = 5

        if score > 50 and score < 100:
            numEnemies = 8

        if score > 100 and score < 120:
            numEnemies = 12

        if score > 120 and score < 150:
            numEnemies = 15

        if score > 150 and score < 180:
            numEnemies = 20

        if score > 180 and score < 220:

            numEnemies = 25

        if score > 220 and score < 250:
            numEnemies = 35

        if score > 250 and score < 280:
            numEnemies = 40

        if score > 280 and score < 300:
            numEnemies = 50

        if score > 300:
            numEnemies = 1

        ### boundaries
        if shipx <= w // 2:
            shipx = w // 2
        if shipy <= h // 2:
            shipy = h // 2
        if shipx >= WINDOWWIDTH - w // 2:
            shipx = WINDOWWIDTH - w // 2
        if shipy >= WINDOWHEIGHT - h // 2:
            shipy = WINDOWHEIGHT - h // 2

        meteorBulletHitList = pygame.sprite.groupcollide(
            bulletLIST, enemyLIST, True, True)
        for meteor in meteorBulletHitList:
            enemyLIST.remove(meteor)
            score += 1

        for x in meteorBulletHitList:
            bulletLIST.remove(x)

        for B in bulletLIST:
            if B.rect.x > 0 and B.rect.y > 0 and B.rect.x < WINDOWWIDTH and B.rect.y < WINDOWHEIGHT:
                B.displayBullet()
            elif check == True:
                bulletLIST.remove(B)

        ## delete yums and enemies if they are outside boundaries
        for yum in yumLIST:
            if yum.rect.x > WINDOWWIDTH or yum.rect.y > WINDOWHEIGHT:

                if check == True:
                    yumLIST.remove(yum)

        for enemy in enemyLIST:
            if enemy.rect.x > WINDOWWIDTH or enemy.rect.y > WINDOWHEIGHT:
                if check == True:
                    enemyLIST.remove(enemy)

        ## collision between player and apples
        if (pygame.sprite.spritecollide(playa, yumLIST, True)):
            score += 1
            splat.play()

        ## collision between player and enemy
        if (pygame.sprite.spritecollide(playa, enemyLIST, True)):
            lives -= 1
            bomb.play()

        ## return the score and exit main loop when all out of lives
        if lives <= 0:
            return (score, None, tillNextLife)

        if score >= 200:
            return (score, lives)

        ## give player lives based on their score
        if score >= 50 and score <= 52:
            if lifeUp50(score) == True:

                lives += 1
            lifeUpShow()

        if score >= 120 and score <= 122:
            if lifeUp120(score) == True:
                lives += 1
            lifeUpShow()

        if score >= 200 and score <= 202:
            if lifeUp200(score) == True:
                lives += 2
            lifeUpShow()

        ## desplay all the yums and the enemies
        for EX in yumLIST:
            EX.displayYum()

        for EX in enemyLIST:
            EX.displayEnemy()

        ### blitting
        displayscore(score, lives, tillNextLife)
        playa.displaySpaceShip()

        pygame.display.update()
        FPSCLOCK.tick(FPS)
Exemple #25
0
def main2(skore, livez):

    pygame.init()
    mixer.init()
    mixer.music.load('07-rounds-6-12-16.mp3')
    mixer.music.play(loops=-1, start=0)
    pygame.mixer.music.set_volume(.35)

    score = skore
    lives = livez

    numEnemies = 2

    backgroundImageName = 'BG.jpg'

    BGImage = pygame.image.load(backgroundImageName)

    BGImage = pygame.transform.scale(BGImage, (WINDOWWIDTH, WINDOWHEIGHT))

    shipx = WINDOWWIDTH // 2
    shipy = WINDOWHEIGHT - 75

    check = True

    makeYummys()
    makeEnemy()

    movex, movey = 0, 0

    # main game loop
    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == KEYDOWN:

                if event.key == K_ESCAPE:
                    terminate()
                elif event.key == K_RIGHT or event.key == K_d:
                    movex += 10
                elif event.key == K_LEFT or event.key == K_a:
                    movex -= 10
                elif event.key == K_UP or event.key == K_w:
                    movey -= 10
                elif event.key == K_DOWN or event.key == K_s:
                    movey += 10

            elif event.type == KEYUP:

                if event.key == K_DOWN or event.key == K_s:
                    movey -= 10

                elif event.key == K_UP or event.key == K_w:
                    movey += 10
                elif event.key == K_LEFT or event.key == K_a:
                    movex += 10
                elif event.key == K_RIGHT or event.key == K_d:
                    movex -= 10

        DISPLAYSURF.blit(BGImage, (0, 0))
        shipx += movex
        shipy += movey

        ssPOS = vector2(shipx, shipy)

        playa = makePlayer(ssPOS)
        w = playa.WIDTH
        h = playa.HEIGHT

        if len(yumLIST) < 6:
            makeYummys()

        if len(enemyLIST) < numEnemies:
            makeEnemy()

        ## defining the amount of enemies based on score

        if score > 200 and score < 250:
            numEnemies = 10

        if score > 250 and score < 280:
            numEnemies = 15

        if score > 280 and score < 300:
            numEnemies = 20

        if score > 300:
            numEnemies = 30

        ### boundaries
        if shipx <= w // 2:
            shipx = w // 2
        if shipy <= h // 2:
            shipy = h // 2
        if shipx >= WINDOWWIDTH - w // 2:
            shipx = WINDOWWIDTH - w // 2
        if shipy >= WINDOWHEIGHT - h // 2:
            shipy = WINDOWHEIGHT - h // 2

        ## delete yums and enemies if they are outside boundaries
        for yum in yumLIST:
            if yum.rect.x > WINDOWWIDTH or yum.rect.y > WINDOWHEIGHT:

                if check == True:
                    yumLIST.remove(yum)

        for enemy in enemyLIST:
            if enemy.rect.x > WINDOWWIDTH or enemy.rect.y > WINDOWHEIGHT:
                if check == True:
                    enemyLIST.remove(enemy)

        ## collision between player and apples
        if (pygame.sprite.spritecollide(playa, yumLIST, True)):
            score += 1
            splat.play()

        ## collision between player and enemy
        if (pygame.sprite.spritecollide(playa, enemyLIST, True)):
            lives -= 1
            bomb.play()

        ## return the score and exit main loop when all out of lives
        if lives <= 0:
            return (score, None)

        ## give player lives based on their score
        if score == 50:
            if lifeUp50(score) == True:

                lives += 1

        if score == 100:
            if lifeUp120(score) == True:
                lives += 1

        if score == 150:
            if lifeUp200(score) == True:
                lives += 2

        ## desplay all the yums and the enemies
        for EX in yumLIST:
            EX.displayYum()

        for EX in enemyLIST:
            EX.displayEnemy()

        ### blitting
        displayscore(score, lives)
        playa.displaySpaceShip()

        pygame.display.update()
        FPSCLOCK.tick(FPS)
Exemple #26
0
    def __changePOS(self, pos):

        self.POS = vector2(pos.vX, pos.vY)
        self.rect.x = pos.vX
        self.rect.y = pos.vY
	def set_speed(self, xspeed, yspeed):
		self.speed = vector2.vector2(xspeed, yspeed)
	def set_acceleration(self, xaccel, yaccel):
		self.acceleration = vector2.vector2(xaccel, yaccel)
	def set_position(self, xpos, ypos):
		self.position = vector2.vector2(xpos, ypos)
Exemple #30
0
    def new_game(self, columns, rows):
        #RESET GAME
        self.cards.clear()
        self.score = 0
        self.selected_cards.clear()
        self.wrong_attempts = 0
        self.score_text.text = Game.defaultScoreText + "0"
        self.win_text.is_visible = False

        #get window size
        sHeight = self.screen.get_height()
        sWidth = self.screen.get_width()

        #set cards size relative to screen
        self.card_size.y = (sHeight * 0.8) / rows
        self.card_size.x = (sHeight * 0.6) / columns

        #offset to center all cards
        offset = vector2()
        offset.x = (sWidth - ((columns - 1) * self.cards_offset +
                              columns * self.card_size.x)) / 2
        offset.y = (sHeight - (
            (rows - 1) * self.cards_offset + rows * self.card_size.y)) / 2

        #instantiate cards
        for x in range(columns):
            for y in range(rows):
                #card position
                p = vector2()
                p.x = x * (self.cards_offset + self.card_size.x) + offset.x
                p.y = y * (self.cards_offset + self.card_size.y) + offset.y
                #instantiate
                c = FigureButton(p, self.card_size, str(y * columns + x))
                #define onclick
                # call select card as routine to prevent locking the application with a thread.sleep()
                # and have a nice delay before hiding back or removing the cards
                c.on_click = lambda c=c: Routine.start_coroutine(
                    self.select_card(c))
                self.cards.append(c)

        #mix them
        random.shuffle(self.cards)
        random.shuffle(self.cards)  #twice to get a better mix

        #define available figures and colors
        colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255),
                  (255, 255, 0), (0, 255, 255)]
        figures = [0, 1, 2]

        total = rows * columns

        #add colors and figures
        i = 0
        while i // 6 < total:
            for x in range(3):  #for each shape
                for y in range(2):  #do it twice to have pairs
                    if (i >= total):
                        return
                    self.cards[i].shape_color = colors[(i // 6) % len(
                        colors
                    )]  # if it exceed the amount of collors start to repeat
                    self.cards[i].shape = figures[x]
                    i += 1
Exemple #31
0
def main():
    pygame.init()
    SCREEN_WIDTH = 400
    SCREEN_HEIGHT = 800
    screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
    pygame.display.set_caption("Mini Golf")
    gravity = vector2(0, 0)  # Downward uniform gravity, set to zero

    #    drag = 1.5
    power = 3
    stroke = 0
    inSandPit = False
    inSandPit2 = False
    inGrassPit = False
    inGrassPitRight = False
    inGrassPitLeft = False
    inHill = False
    youWin = False

    grassCoeff = 2
    sandCoeff = 5

    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    GREEN = (0, 128, 0)

    LIGHT_GREY = (128, 128, 128)
    DARK_GREEN = (11, 102, 35)
    LIGHT_BROWN = (225, 196, 161)

    # list of objects in world
    objects = []
    #Handles Collisions
    collisions = []
    #Holds the ball and hold
    hole_ball = []

    # list of forces active
    forces = []

    # list of contact generators
    contact_generators = []
    # list of contacts to be resolved
    contacts = []

    #    Hole = (Circle(0, vector2(100,100), vector2(0,0), 6, BLACK, gravity))
    DetectionCircle = Circle(0, vector2(150, 100), vector2(0, 0), 8)

    objects.append(
        Polygon(vector2(350, 100),
                ((300, 0), (400, 0), (400, 200), (300, 200)), LIGHT_GREY))
    collisions.append(
        Polygon(vector2(350, 100),
                ((300, 0), (400, 0), (400, 200), (300, 200)), LIGHT_GREY))

    objects.append(
        Polygon(vector2(300, 350),
                ((200, 200), (400, 200), (400, 500), (200, 500)), LIGHT_GREY))
    collisions.append(
        Polygon(vector2(300, 350),
                ((200, 200), (400, 200), (400, 500), (200, 500)), LIGHT_GREY))

    objects.append(
        Polygon(vector2(50, 400), ((0, 200), (100, 200), (100, 600), (0, 600)),
                LIGHT_GREY))
    collisions.append(
        Polygon(vector2(50, 400), ((0, 200), (100, 200), (100, 600), (0, 600)),
                LIGHT_GREY))

    objects.append(
        Polygon(vector2(150, 700),
                ((0, 600), (300, 600), (300, 800), (0, 800)), LIGHT_GREY))
    collisions.append(
        Polygon(vector2(150, 700),
                ((0, 600), (300, 600), (300, 800), (0, 800)), LIGHT_GREY))

    #Triangle1
    objects.append(
        Polygon(vector2(525, 375), ((300, 500), (400, 500), (400, 600)),
                LIGHT_GREY))
    collisions.append(
        Polygon(vector2(525, 375), ((300, 500), (400, 500), (400, 600)),
                LIGHT_GREY))
    #    Triangle2
    objects.append(
        Polygon(vector2(125, 575), ((100, 600), (100, 500), (200, 600)),
                LIGHT_GREY))
    collisions.append(
        Polygon(vector2(125, 575), ((100, 600), (100, 500), (200, 600)),
                LIGHT_GREY))

    ball = Circle(1, vector2(350, 775), vector2(0, 0), 5, WHITE, gravity)
    objects.append(ball)
    objects.append(Hole(0, vector2(150, 100), vector2(0, 0), 0))

    hole_ball.append(ball)
    hole_ball.append(Hole(0, vector2(150, 100), vector2(0, 0), 0))

    collisions.append(ball)

    #Top Wall
    objects.append(Wall(vector2(0, 0), vector2(0, 1), LIGHT_GREY))
    collisions.append(Wall(vector2(0, 0), vector2(0, 1), LIGHT_GREY))

    #left Wall
    objects.append(Wall(vector2(0, 0), vector2(1, 0), LIGHT_GREY))
    collisions.append(Wall(vector2(0, 0), vector2(1, 0), LIGHT_GREY))

    #Right Wall
    objects.append(Wall(vector2(SCREEN_WIDTH, 0), vector2(-1, 0), LIGHT_GREY))
    collisions.append(
        Wall(vector2(SCREEN_WIDTH, 0), vector2(-1, 0), LIGHT_GREY))

    #Bottom Wall
    objects.append(Wall(vector2(0, SCREEN_HEIGHT), vector2(0, -1), LIGHT_GREY))
    collisions.append(
        Wall(vector2(0, SCREEN_HEIGHT), vector2(0, -1), LIGHT_GREY))

    #Hill Normals
    hill_force = vector2(0, 150)
    hill_force2 = vector2(0, -150)

    #Start adding forces
    sandForce = force.SingleForce(objects,
                                  lambda o1: force.linear_drag(o1, sandCoeff))
    sandForce2 = force.SingleForce(objects,
                                   lambda o1: force.linear_drag(o1, sandCoeff))

    grassForce = force.SingleForce(
        objects, lambda o1: force.linear_drag(o1, grassCoeff))
    grassForceLeft = force.SingleForce(
        objects, lambda o1: force.linear_drag(o1, grassCoeff))
    grassForceRight = force.SingleForce(
        objects, lambda o1: force.linear_drag(o1, grassCoeff))
    holeForce = force.PairForce(
        hole_ball, lambda o1, o2: force.spring_force(o1, o2, 100, 0))
    hillForce = force.SingleForce(objects,
                                  lambda o1: force.hill_drag(hill_force))
    hillForce2 = force.SingleForce(objects,
                                   lambda o1: force.hill_drag(hill_force2))

    forces.append(
        force.SingleForce(objects, lambda o1: force.constant_drag(o1)))

    contact_generators.append(contact.ContactGenerator(collisions, 0.5))

    sandPit = (300, 650, 100, 20)
    sandPit2 = (100, 340, 100, 20)
    grassPit = (0, 0, 300, 50)
    grassPitRight = (250, 50, 50, 200)
    grassPitLeft = (0, 50, 50, 200)
    hillArea = (100, 200, 100, 100)
    hillArea2 = (100, 400, 100, 100)

    # Main Loop
    done = False
    frame_rate = 60
    dt = 1.0 / frame_rate

    clock = pygame.time.Clock()
    while not done:
        # --- Main event loop
        for event in pygame.event.get():  # User did something
            if (event.type == pygame.QUIT  # If user clicked close
                    or (event.type == pygame.KEYDOWN
                        and event.key == pygame.K_ESCAPE)):  # or pressed ESC
                done = True  # Flag that we are done so we exit this loop
            elif event.type == pygame.MOUSEBUTTONDOWN:  # If user clicked
                if event.button == 1:
                    # Move the player
                    if ball.vel.mag() <= 1 and youWin != True:
                        stroke = stroke + 1
                        x = pygame.mouse.get_pos()[0] - ball.pos.x
                        y = pygame.mouse.get_pos()[1] - ball.pos.y
                        direc = vector2(x, y)
                        ball.vel = direc * power
                # Reset the game
                elif event.button == 3:
                    ball.pos.x = 350
                    ball.pos.y = 775
                    stroke = 0
                    ball.vel = vector2(0, 0)
                    youWin = False

        distanceToHole = ball.pos - DetectionCircle.pos
        #Hole force creater
        if distanceToHole.mag() < DetectionCircle.radius:
            if (forces[-1] != holeForce):
                forces.append(holeForce)
        else:
            if (forces[-1] == holeForce):
                forces.remove(holeForce)
        # In sand pit
        if ((ball.pos[0] >= sandPit[0])
                and (ball.pos[0] <= sandPit[0] + sandPit[2])):
            if ((ball.pos[1] >= sandPit[1])
                    and (ball.pos[1] <= sandPit[1] + sandPit[3])):
                inSandPit = True
            else:
                inSandPit = False
        else:
            inSandPit = False

        if (inSandPit is True):
            if (forces[-1] != sandForce2):
                forces.append(sandForce2)
        else:
            if (forces[-1] == sandForce2):
                forces.remove(sandForce2)
        #In sand pit 2
        if ((ball.pos[0] >= sandPit2[0])
                and (ball.pos[0] <= sandPit2[0] + sandPit2[2])):
            if ((ball.pos[1] >= sandPit2[1])
                    and (ball.pos[1] <= sandPit2[1] + sandPit2[3])):
                inSandPit2 = True
            else:
                inSandPit2 = False
        else:
            inSandPit2 = False

        if (inSandPit2 is True):
            if (forces[-1] != sandForce):
                forces.append(sandForce)
        else:
            if (forces[-1] == sandForce):
                forces.remove(sandForce)
        #Grass Pit
        if ((ball.pos[0] >= grassPit[0])
                and (ball.pos[0] <= grassPit[0] + grassPit[2])):
            if ((ball.pos[1] >= grassPit[1])
                    and (ball.pos[1] <= grassPit[1] + grassPit[3])):
                inGrassPit = True
            else:
                inGrassPit = False
        else:
            inGrassPit = False

        if (inGrassPit is True):
            if (forces[-1] != grassForce):
                forces.append(grassForce)
        else:
            if (forces[-1] == grassForce):
                forces.remove(grassForce)
        #Grass Pit Right
        if ((ball.pos[0] >= grassPitRight[0])
                and (ball.pos[0] <= grassPitRight[0] + grassPitRight[2])):
            if ((ball.pos[1] >= grassPitRight[1])
                    and (ball.pos[1] <= grassPitRight[1] + grassPitRight[3])):
                inGrassPitRight = True
            else:
                inGrassPitRight = False
        else:
            inGrassPitRight = False

        if (inGrassPitRight is True):
            if (forces[-1] != grassForceRight):
                forces.append(grassForceRight)
        else:
            if (forces[-1] == grassForceRight):
                forces.remove(grassForceRight)
        #Grass Pit Left
        if ((ball.pos[0] >= grassPitLeft[0])
                and (ball.pos[0] <= grassPitLeft[0] + grassPitLeft[2])):
            if ((ball.pos[1] >= grassPitLeft[1])
                    and (ball.pos[1] <= grassPitLeft[1] + grassPitLeft[3])):
                inGrassPitLeft = True
            else:
                inGrassPitLeft = False
        else:
            inGrassPitLeft = False

        if (inGrassPitLeft is True):
            if (forces[-1] != grassForceLeft):
                forces.append(grassForceLeft)
        else:
            if (forces[-1] == grassForceLeft):
                forces.remove(grassForceLeft)
        # Hill
        if ((ball.pos[0] >= hillArea[0])
                and (ball.pos[0] <= hillArea[0] + hillArea[2])):
            if ((ball.pos[1] >= hillArea[1])
                    and (ball.pos[1] <= hillArea[1] + hillArea[3])):
                inHill = True
            else:
                inHill = False
        else:
            inHill = False

        if (inHill is True):
            if (forces[-1] != hillForce):
                forces.append(hillForce)
        else:
            if (forces[-1] == hillForce):
                forces.remove(hillForce)

        # Hill2
        if ((ball.pos[0] >= hillArea2[0])
                and (ball.pos[0] <= hillArea2[0] + hillArea2[2])):
            if ((ball.pos[1] >= hillArea2[1])
                    and (ball.pos[1] <= hillArea2[1] + hillArea2[3])):
                inHill = True
            else:
                inHill = False
        else:
            inHill = False

        if (inHill is True):
            if (forces[-1] != hillForce2):
                forces.append(hillForce2)
        else:
            if (forces[-1] == hillForce2):
                forces.remove(hillForce2)

        # Add forces
        for f in forces:
            f.force_all()

        # Move objects
        for o in objects:
            o.integrate(dt)

        # Get contacts
        niterations = 0
        max_iterations = 10
        while niterations < max_iterations:
            niterations += 1
            contacts = []
            for g in contact_generators:
                contacts.extend(g.contact_all())

            if len(contacts) == 0:
                break

            # Resolve contacts
            contacts.sort(key=lambda x: x.penetration)
            for c in contacts:
                c.resolve()

        # Draw objects to screen
        screen.fill(GREEN)  # clears the screen

        pygame.draw.rect(screen, DARK_GREEN, grassPit, 0)
        pygame.draw.rect(screen, DARK_GREEN, grassPitRight, 0)
        pygame.draw.rect(screen, DARK_GREEN, grassPitLeft, 0)
        pygame.draw.rect(screen, (0, 255, 0), hillArea, 0)
        pygame.draw.rect(screen, (0, 200, 0), (100, 300, 100, 100), 0)
        pygame.draw.rect(screen, (0, 255, 0), hillArea2, 0)
        pygame.draw.rect(screen, LIGHT_BROWN, sandPit, 0)
        pygame.draw.rect(screen, LIGHT_BROWN, sandPit2, 0)
        pygame.draw.circle(screen, BLACK, vector2(150, 100), 6)  #Hole

        for o in objects:
            o.draw(screen)

        if ball.vel.mag(
        ) <= 1 and ball.pos.x > 145 and ball.pos.x < 155 and ball.pos.y > 95 and ball.pos.y < 105:
            if youWin == False:
                print("You win!!!")
                youWin = True
        elif ball.vel.mag() <= 1:
            pygame.draw.aaline(screen, BLACK,
                               (int(ball.pos.x), int(ball.pos.y)),
                               (int(pygame.mouse.get_pos()[0]),
                                int(pygame.mouse.get_pos()[1])))
        #Screen Text
        myfont = pygame.font.SysFont('arial', 30)

        stroke_text = myfont.render("Stroke: " + str(stroke), False, BLACK)
        text_rect = stroke_text.get_rect(center=(60, 20))

        screen.blit(stroke_text, text_rect)

        # Update the screen
        pygame.display.update()

        # --- Limit to 60 frames per second
        clock.tick(60)

    pygame.quit()
Exemple #32
0
 def integrate(self, dt):
     self.vel += self.invmass * self.force * dt
     self.pos += self.vel * dt
     self.force = vector2(self.gforce)
Exemple #33
0
    def __getRotation(self, vec1):

        vec2 = vector2(0.0, -1.0)
        angle = acos(vec2.dotProductV2(vec1))

        return angle
Exemple #34
0
def main():
    global count, shapes, screen, clock
    screen = pygame.display.set_mode((800, 600))
    shapes = []
    arrow_pts = [vector2(60, 0), vector2(20, 40), vector2(20, 20), 
            vector2(-60, 20), vector2(-60, -20), vector2(20, -20), 
            vector2(20, -40)]
    player = vex_player(50, 50, Color(255, 255, 255), arrow_pts, 2)
    shapes.append(player)
    rotate_done = False
    while True:
        screen.fill(0)
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                if e.key == K_q:
                    return
                elif e.key == K_SPACE:
                    rotate_done = not rotate_done
                elif e.key == K_r:
                    del shapes[:]
                elif e.key == K_w:
                    #move up
                    player.move_up = True
                elif e.key == K_s:
                    #move down
                    player.move_down = True
                elif e.key == K_a:
                    #move left
                    player.move_left = True
                elif e.key == K_d:
                    #move right
                    player.move_right = True
                elif e.key == K_UP:
                    #rotate 90deg
                    player.rotate_by_radians(math.pi/2)
                elif e.key == K_DOWN:
                    #rotate -90deg
                    player.rotate_by_radians(-math.pi/2)
            elif e.type == KEYUP:
                if e.key == K_w:
                    #move up
                    player.move_up = False
                elif e.key == K_s:
                    #move down
                    player.move_down = False
                elif e.key == K_a:
                    #move left
                    player.move_left = False
                elif e.key == K_d:
                    #move right
                    player.move_right = False

            elif e.type == MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if e.button == 1:
                    if len(shapes) >= 2:
                        shapes.append(shapes[-1].reproduce(shapes[-2], 
                            pos[0], pos[1]))
                    else:           
                        shapes.append(gen_shape(pos[0], pos[1]))
                elif e.button == 3:
                    shapes.append(gen_shape(pos[0], pos[1]))
                count += 1
            elif e.type == MOUSEMOTION and not rotate_done:
                #player.rotate(e.pos[0], e.pos[1])
                for sh in [player]:
                    sh.rotate_to_face_point(e.pos[0], e.pos[1])
                    pygame.draw.line(screen, pygame.Color(0, 255, 0),
                            (e.pos[0], e.pos[1]), (sh.x, sh.y), 2) 
                    pygame.draw.line(screen, pygame.Color(0, 0, 255),
                            (sh.x, sh.y), (sh.direction_vector().x,
                                sh.direction_vector().y), 1)
                    pygame.draw.line(screen, pygame.Color(255, 255, 0),
                            (sh.direction_vector().x, 
                                sh.direction_vector().y), 
                            (e.pos[0], e.pos[1]), 1)
                #rotate_done = True
        for s in shapes:
            if s.x < 0 or s.x > 800:
                #shapes.remove(s)
                s.xMod = -s.xMod
            elif s.y < 0 or s.y > 600:
                #shapes.remove(s)
                s.yMod = -s.yMod
            s.update(screen)
            s.draw(screen)
        pygame.display.update()
        clock.tick(30)
Exemple #35
0
 def __init__(self, **kwargs):
     kwargs['pos'] = kwargs.get('pos') or vector2.vector2(0,0)
     entity.Entity.__init__(self, **kwargs)
     self.updated = False