コード例 #1
0
	def render(self, down):
		"Render store screen"
		self.surface.blit(self.bg, (0,0))
		self.surface.blit(self.arrow_left, (0,0))
		mx, my = mouse.get_pos()
		mb = mouse.get_pressed()
		#back button
		if Rect(0,0,80,80).collidepoint(mx,my) and mb[0]:
			self.running = False
		#move car carousel left
		if self.curCar > 0:
			self.surface.blit(self.arrow_left, (100,344))
			if Rect(100,344,80,80).collidepoint(mx,my) and down:
				self.curCar -= 1
		#move car carousel right
		if self.curCar < len(self.cars)-1:
			self.surface.blit(self.arrow_right, (844, 344))
			if Rect(844,344,80,80).collidepoint(mx,my) and down:
				self.curCar += 1
		#limit exceeding carousel cars
		if self.curCar >= len(self.cars):
			self.curCar = len(self.cars) - 1
		#move car angle for rotation
		self.angle += 1
		self.carImageRotated = transform.rotozoom(self.cars[self.curCar], self.angle, 1)
		self.boundingRect = self.carImageRotated.get_rect()
		self.surface.blit(self.carImageRotated, (self.x-self.boundingRect[2]/2,self.y-self.boundingRect[3]/2))
		#blit rotated car, and if car is unlocked, active, or available for purchase
		if str(self.curCar + 1) in self.unlocked:
			self.surface.blit(self.smallFont.render("Unlocked", 1, (255,255,255)), (550,200))
			if open("files/car.txt").read() == "res/car%s.png" % str(self.curCar + 1):
				self.surface.blit(self.already, (570, 275))
			else:
				self.surface.blit(self.use, (570, 275))
				if Rect(570,275,126,48).collidepoint(mx,my) and down:
					f = open("files/car.txt", "w").write("res/car%s.png" % str(self.curCar + 1))
		else:
			#blit cost
			self.surface.blit(self.buy, (570, 275))
			self.surface.blit(self.smallFont.render("Cost: ", 1, (255,255,255)), (550, 350))
			self.surface.blit(self.coinSmall, (660, 360))
			self.surface.blit(self.smallFont.render(self.prices[self.curCar], 1, (255,255,255)), (700, 350))
			if Rect(570,275,126,48).collidepoint(mx,my) and down:
				if int(self.coins) - int(self.prices[self.curCar]) < 0:
					self.errorTime = cTime()
				else:
					self.coins = str(int(self.coins)-int(self.prices[self.curCar]))
					f = open("files/cars_unlocked.txt", "a").write("\n%s" % str(self.curCar+1))
					f = open("files/coins.txt", "w").write(self.coins)
					self.unlocked = open("files/cars_unlocked.txt").read().split("\n")
				
		self.surface.blit(self.coin, (550, 50))
		self.surface.blit(self.mediumFont.render(self.coins, 1, (255,255,255)), (630, 45))

		#error message for not enough coins
		if cTime() - self.errorTime <= 3:
			self.surface.blit(self.smallFont.render("Not Enough Coins!", 1, (255,0,0)), (self.surface.get_width()//2-(font.Font.size(self.smallFont, "Not Enough Coins!")[0])//2, 600))
コード例 #2
0
 def render(self):
     "Blit clock to surface"
     self.surface.blit(
         self.timeFont.render(
             strftime(
                 '%M:%S',
                 gmtime(int(self.clockTimer -
                            (cTime() - self.clockTime))))[1:], 1,
             (255, 255, 255)), (170, 0))
     self.timeLeft = self.clockTimer - (cTime() - self.clockTime)
コード例 #3
0
ファイル: Host.py プロジェクト: ExPHAT/binding-of-isaac
	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy
		self.tearTextures = textures["tears"]
		self.tearSounds = sounds["tear"]
		self.frames = [textures["enemies"]["host"].subsurface(i*64, 0, 64, 128) for i in range(2)]

		self.texture = self.frames[0]

		self.sinceFull = cTime()
		self.sinceDown = cTime()
		self.shot = False
		self.canHurt = False
コード例 #4
0
ファイル: Host.py プロジェクト: wade1990/binding-of-isaac
    def __init__(self, xy, sounds, textures):
        self.x, self.y = xy
        self.tearTextures = textures["tears"]
        self.tearSounds = sounds["tear"]
        self.frames = [
            textures["enemies"]["host"].subsurface(i * 64, 0, 64, 128)
            for i in range(2)
        ]

        self.texture = self.frames[0]

        self.sinceFull = cTime()
        self.sinceDown = cTime()
        self.shot = False
        self.canHurt = False
コード例 #5
0
ファイル: Boil.py プロジェクト: wade1990/binding-of-isaac
	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy
		self.sounds = sounds

		# Split textures
		self.frames = [textures["enemies"]["boil"].subsurface(i*64-(i//4)*(64*4), (i//4)*64, 64, 64) for i in range(10)][::-1]

		# Record sound and textures for tears
		self.tearTextures = textures["tears"]
		self.tearSounds = sounds["tear"]

		# How long it takes to grow + current size
		self.size = 0
		self.advanceTime = 0.5

		# When the animation was started
		self.start = cTime()

		# Animation for grow
		self.animation = Animation(self.frames, 10, shouldLoop=False)

		# How long the boil has been full
		self.sinceFull = -1

		# How many tears the boil has active
		self.tears = []
コード例 #6
0
ファイル: Banner.py プロジェクト: wade1990/binding-of-isaac
	def __init__(self, text, textures):
		self.text = text # The text to show

		self.snap = loadCFont("banner.png", 12, 10, 26) # Load the font
		self.streak = textures["streak"] # The black background behind it

		self.start = cTime() # When the banner was created
		
		# Create a surface for the text
		self.drawText = write(text, self.snap, alph="abcdefghijklmnopqrstuvwxyz ", dark=0)
コード例 #7
0
ファイル: Banner.py プロジェクト: wade1990/binding-of-isaac
	def render(self, surface):
		self.slide = surface.copy()

		# Only allow it to show up for 3 seconds	
		if cTime() - self.start <= 3:
			self.draw(surface, self.drawText)
		else:
			return True

		return False
コード例 #8
0
def can_shoot(character):
    """
    Returns a boolean of whether the player can shoot or not
    :param character: character that wants to shoot
    :return: true if the player can shoot, false otherwise
    """
    current_time = cTime()
    time_until_shoot_again = character.last_shot_time + character.shot_wait_time
    if current_time > time_until_shoot_again:
        return True
    return False
コード例 #9
0
ファイル: main.py プロジェクト: wade1990/binding-of-isaac
def showSymbol(screen, length, index, textures):
	"Show loading screen symbol"

	start = cTime()
	texture = textures["loading"][index]
	w = texture.get_width()
	h = texture.get_height()
	running = True
	while running:
		for e in event.get():
			if e.type == QUIT or e.type == KEYDOWN and e.key == 27:
				quit()

		# Draw the centered texture
		screen.fill((0,0,0))
		screen.blit(texture, (WIDTH//2-w//2,HEIGHT//2-h//2))

		display.flip()

		# Only run for a certian ammount of time
		if cTime() - start >= length:
			running = False
コード例 #10
0
def show_random_powerup(last_powerup_time, all_sprites, powerups, luci, michael):
    """
    Calculate whether or not to display a powerups
    :param last_powerup_time: self-explanitory
    :param all_sprites: group of all the sprites
    :param powerups: group of all the powerups
    :param luci: luci object
    :param michael: michael object
    """
    current_time = cTime()

    if current_time > last_powerup_time[0] + random.randint(7, 13):
        last_powerup_time[0] = current_time
        display_powerup(all_sprites, powerups, luci, michael)
コード例 #11
0
	def __init__(self, frames, interval, shouldLoop=True):
		self.frames = frames
		self.frameCount = len(self.frames)
		self.interval = interval/self.frameCount # Wait between frames
		self.shouldLoop = shouldLoop

		self.lastFrame = cTime() # Creation time
		self.currentIndex = -1 # There will be an step right away, counter act it
		self.frame = self.frames[self.currentIndex] # Start off current frame
		self.looped = False # Has made a complete loop

		# Assume all images are the same size
		self.width = self.frames[0].get_width()
		self.height = self.frames[0].get_height()
コード例 #12
0
ファイル: Bomb.py プロジェクト: ExPHAT/binding-of-isaac
	def __init__(self, parent, variant, xy, sounds, textures, explode=False):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sounds = sounds
		self.textures = textures
		self.parent = parent # So we can stain the room floor

		if not explode:
			self.bounds = Rect(GRIDX+GRATIO*self.x,GRIDY+GRATIO*self.y, 32, 64)
		else:
			# You cant collide with a bomb that will explode
			self.bounds = Rect(0,0,0,0)

		# Should the bomb explode
		self.shouldExplode = explode
		self.placed = cTime()

		self.anim = Animation([textures[0].subsurface(0,0,64,64)], .2)
コード例 #13
0
ファイル: Bomb.py プロジェクト: wade1990/binding-of-isaac
    def __init__(self, parent, variant, xy, sounds, textures, explode=False):
        self.variant = variant
        self.x = xy[0]
        self.y = xy[1]
        self.sounds = sounds
        self.textures = textures
        self.parent = parent  # So we can stain the room floor

        if not explode:
            self.bounds = Rect(GRIDX + GRATIO * self.x,
                               GRIDY + GRATIO * self.y, 32, 64)
        else:
            # You cant collide with a bomb that will explode
            self.bounds = Rect(0, 0, 0, 0)

        # Should the bomb explode
        self.shouldExplode = explode
        self.placed = cTime()

        self.anim = Animation([textures[0].subsurface(0, 0, 64, 64)], .2)
コード例 #14
0
def shoot(character, all_sprites, all_projectiles):
    """
    Put the shot on the screen
    :param character: character that is shooting
    :param all_sprites: group of all the sprites
    :param all_projectiles: group of all the projectiles
    """

    # name, direction, ix, iy, speed, damage,  range, shot size
    shot = Shot(character.get_name(), character.get_direction(), character.get_vx(), character.get_vy(), character.get_shot_speed(), character.get_shot_damage(), character.get_shot_range(), character.get_shot_size())

    # set the shot so it is where the player is
    if character.get_direction() == "L":
        shot.rect.x = character.rect.x + (character.get_width()-90)
    elif character.get_direction() == "R":
        shot.rect.x = character.rect.x + (character.get_width()-60)
    else:
        shot.rect.x = character.rect.x + (character.get_width()-55)

    shot.rect.y = character.rect.y + (character.get_height() / 2)

    # add the shot to the lists
    all_sprites.add(shot)
    all_projectiles.add(shot)

    # update last_shot_time
    character.set_last_shot_time(cTime())

    # play shot sound
    global luci_shot_sounds
    global michael_shot_sounds

    if character.get_name() == "Luci":
        luci_shot_sounds[random.randint(0, 1)].play()
    else:
        michael_shot_sounds[random.randint(0, 1)].play()
コード例 #15
0
ファイル: Game.py プロジェクト: seenbeen/CS3244-Project
	def run(self, screen, sounds, textures, fonts, joystick=None):
		# Run the main loop
		animatingRooms = self.animatingRooms
		currentRoom = self.currentRoom

		# Setup controls and create character
		cn = self.controls
		self.isaac = isaac = Character(self.characterType, (WIDTH//2, (HEIGHT//4)*3), [[cn[3], cn[1], cn[2], cn[0]], [cn[7], cn[5], cn[6], cn[4]]], textures, sounds, fonts)

		# Setup special stats
		if self.characterType == 0:
			isaac.pill = Pill((0,0), textures["pills"])
		elif self.characterType == 2:
			isaac.speed = 3
			isaac.damage = 1
			del isaac.hearts[-1]

		self.sounds = sounds
		self.textures = textures
		self.setup()

		floor = self.floor
		floorIndex = self.floorIndex
		clock = time.Clock()

		# Create minimap
		self.minimap = Surface((textures["map"]["background"].get_width(), textures["map"]["background"].get_height())).convert_alpha()
		self.updateMinimap(self.currentRoom)
		self.minimap.set_clip(Rect(4, 4, 100, 86))
		mWidth = self.minimap.get_width()
		mHeight = self.minimap.get_height()
		
		# Define possible moves
		self.posMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]]
		posMoves = self.posMoves

		# Set the game (so we can modify stuff from the character class)
		self.isaac.game = self

		self.updateFloor()

		running = True
		while running:

			currTime = cTime()
			#k = key.get_pressed() # Current down keys

			for e in event.get():
				if e.type == QUIT:
					quit() 
				elif e.type == KEYDOWN and e.key == 27:
					# Pause the game
					running = pause(screen, self.seed, textures, fonts, [self.isaac.speed, self.isaac.shotSpeed, self.isaac.damage, self.isaac.luck, self.isaac.shotRate, self.isaac.range])

				elif e.type == KEYDOWN:
					# Update key value
					isaac.moving(e.key, True, False)
	
					if e.key == self.controls[-1]:
						# Bomb key pressed
						if isaac.pickups[1].use(1):
							self.floor[self.currentRoom].other.append(Bomb(self.floor[self.currentRoom], 0, ((isaac.x-GRIDX)/GRATIO, (isaac.y-GRIDY)/GRATIO), [sounds["explosion"]], textures["bombs"], explode=True))

					elif e.key == self.controls[-2]:
						# Pill key pressed
						isaac.usePill()

				elif e.type == KEYUP:
					# Update key value
					isaac.moving(e.key, False, False)

			# Draw animating rooms (The ones that are shifting in and out of frame)
			if len(animatingRooms) > 0:
				for r in animatingRooms[:]:
					r.render(screen, isaac, currTime)
					if not r.animating:
						animatingRooms.remove(r)
			else:
				screen.fill((0,0,0))

				# Render the room
				move = self.floor[self.currentRoom].render(screen, isaac, currTime)

				if move[0] != 0 or move[1] != 0:
					old = tuple(self.currentRoom[:])

					self.currentRoom = (move[0]+self.currentRoom[0], move[1]+self.currentRoom[1])
					try:
						# Animate the room
						self.floor[self.currentRoom].animateIn(move)
						self.floor[old].animateOut(move)

						# Animate the room
						animatingRooms.append(self.floor[self.currentRoom])
						animatingRooms.append(self.floor[old])

						# Animate isaac with the room
						isaac.x += 650*(-move[0])
						isaac.y += 348*(move[1])


						# Remove tears from an animating room
						isaac.clearTears()

						# Check if you enter a boss room
						if self.floor[self.currentRoom].variant == 2 and not self.floor[self.currentRoom].entered:
							sounds["bossIntro"].play()

							# Give the correct boss index
							bossIntro(screen, self.characterType, [Gurdy, Duke].index(type(self.floor[self.currentRoom].enemies[0])), self.floorIndex)

						self.floor[self.currentRoom].entered = True

						for m in posMoves:
							mx, my = m
							x, y = self.currentRoom
							newPos = (mx+x, my+y)

							try:
								self.floor[newPos].seen = True
							except:
								pass

						self.updateMinimap(self.currentRoom)

					except:
						# That room doesnt exist
						self.currentRoom = old

			if self.floor[self.currentRoom].variant == 2:
				# Its a boss room
				try:
					# Draw the boss bar
					bossbar(screen, self.floor[self.currentRoom].enemies[0].health/100)
				except:
					pass

				if not self.won and self.floorIndex == 6 and len(self.floor[self.currentRoom].enemies) == 0:
					self.banners.append(Banner("You won", self.textures))
					self.won = True


			# DRAW MAP
			screen.blit(self.minimap, (MAPX-mWidth//2, MAPY-mHeight//2))

			# Blit all banners
			for banner in self.banners:
				if banner.render(screen):
					self.banners.remove(banner)

			if joystick != None:
				joystick.update()

			if isaac.dead:
				running = False

			display.flip()
			clock.tick(60)
コード例 #16
0
    def __init__(self, characterType, controls, seed, screen, sounds, textures,
                 fonts):
        self.floor = {}
        self.floorIndex = 0
        self.currentRoom = (0, 0)
        self.animatingRooms = []
        self.won = False
        self.surface = surface
        self.characterType = characterType
        self.seed = seed
        self.controls = controls
        self.sounds = sounds
        self.textures = textures
        self.fonts = fonts

        self.banners = []

        # Feed the seed to the random module
        random.seed(self.seed)

        # ---------------------------------- Prep for main loop --------------------------------------
        animatingRooms = self.animatingRooms
        currentRoom = self.currentRoom

        # Setup controls and create character
        cn = self.controls
        self.isaac = isaac = Character(
            self.characterType, (WIDTH // 2, (HEIGHT // 4) * 3),
            [[cn[3], cn[1], cn[2], cn[0]], [cn[7], cn[5], cn[6], cn[4]]],
            self.textures, self.sounds, self.fonts)

        # Setup special stats
        if self.characterType == 0:
            isaac.pill = Pill((0, 0), textures["pills"])
        elif self.characterType == 2:
            isaac.speed = 3
            isaac.damage = 1
            del isaac.hearts[-1]

        self.setup()

        floor = self.floor
        floorIndex = self.floorIndex
        #clock = time.Clock()

        # Create minimap
        self.minimap = Surface(
            (textures["map"]["background"].get_width(),
             self.textures["map"]["background"].get_height())).convert_alpha()
        self.updateMinimap(self.currentRoom)
        self.minimap.set_clip(Rect(4, 4, 100, 86))

        # Define possible moves
        self.posMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]]

        # Set the game (so we can modify stuff from the character class)
        self.isaac.game = self

        self.updateFloor()
        self.currTime = cTime()
        self.status = 0
        self.isaac = isaac
        self.animatingRooms = animatingRooms
        self.screen = screen
        self.startingRoom = self.currentRoom
コード例 #17
0
ファイル: Game.py プロジェクト: ExPHAT/binding-of-isaac
	def run(self, screen, sounds, textures, fonts, joystick=None):
		# Run the main loop
		animatingRooms = self.animatingRooms
		currentRoom = self.currentRoom

		# Setup controls and create character
		cn = self.controls
		self.isaac = isaac = Character(self.characterType, (WIDTH//2, (HEIGHT//4)*3), [[cn[3], cn[1], cn[2], cn[0]], [cn[7], cn[5], cn[6], cn[4]]], textures, sounds, fonts)

		# Setup special stats
		if self.characterType == 0:
			isaac.pill = Pill((0,0), textures["pills"])
		elif self.characterType == 2:
			isaac.speed = 3
			isaac.damage = 1
			del isaac.hearts[-1]

		self.sounds = sounds
		self.textures = textures
		self.setup()

		floor = self.floor
		floorIndex = self.floorIndex
		clock = time.Clock()

		# Create minimap
		self.minimap = Surface((textures["map"]["background"].get_width(), textures["map"]["background"].get_height())).convert_alpha()
		self.updateMinimap(self.currentRoom)
		self.minimap.set_clip(Rect(4, 4, 100, 86))
		mWidth = self.minimap.get_width()
		mHeight = self.minimap.get_height()
		
		# Define possible moves
		self.posMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]]
		posMoves = self.posMoves

		# Set the game (so we can modify stuff from the character class)
		self.isaac.game = self

		self.updateFloor()

		running = True
		while running:

			currTime = cTime()
			k = key.get_pressed() # Current down keys

			for e in event.get():
				if e.type == QUIT:
					quit() 
				elif e.type == KEYDOWN and e.key == 27:
					# Pause the game
					running = pause(screen, self.seed, textures, fonts, [self.isaac.speed, self.isaac.shotSpeed, self.isaac.damage, self.isaac.luck, self.isaac.shotRate, self.isaac.range])

				elif e.type == KEYDOWN:
					# Update key value
					isaac.moving(e.key, True, False)
	
					if e.key == self.controls[-1]:
						# Bomb key pressed
						if isaac.pickups[1].use(1):
							self.floor[self.currentRoom].other.append(Bomb(self.floor[self.currentRoom], 0, ((isaac.x-GRIDX)/GRATIO, (isaac.y-GRIDY)/GRATIO), [sounds["explosion"]], textures["bombs"], explode=True))

					elif e.key == self.controls[-2]:
						# Pill key pressed
						isaac.usePill()

				elif e.type == KEYUP:
					# Update key value
					isaac.moving(e.key, False, False)

			# Draw animating rooms (The ones that are shifting in and out of frame)
			if len(animatingRooms) > 0:
				for r in animatingRooms[:]:
					r.render(screen, isaac, currTime)
					if not r.animating:
						animatingRooms.remove(r)
			else:
				screen.fill((0,0,0))

				# Render the room
				move = self.floor[self.currentRoom].render(screen, isaac, currTime)

				if move[0] != 0 or move[1] != 0:
					old = tuple(self.currentRoom[:])

					self.currentRoom = (move[0]+self.currentRoom[0], move[1]+self.currentRoom[1])
					try:
						# Animate the room
						self.floor[self.currentRoom].animateIn(move)
						self.floor[old].animateOut(move)

						# Animate the room
						animatingRooms.append(self.floor[self.currentRoom])
						animatingRooms.append(self.floor[old])

						# Animate isaac with the room
						isaac.x += 650*(-move[0])
						isaac.y += 348*(move[1])


						# Remove tears from an animating room
						isaac.clearTears()

						# Check if you enter a boss room
						if self.floor[self.currentRoom].variant == 2 and not self.floor[self.currentRoom].entered:
							sounds["bossIntro"].play()

							# Give the correct boss index
							bossIntro(screen, self.characterType, [Gurdy, Duke].index(type(self.floor[self.currentRoom].enemies[0])), self.floorIndex)

						self.floor[self.currentRoom].entered = True

						for m in posMoves:
							mx, my = m
							x, y = self.currentRoom
							newPos = (mx+x, my+y)

							try:
								self.floor[newPos].seen = True
							except:
								pass

						self.updateMinimap(self.currentRoom)

					except:
						# That room doesnt exist
						self.currentRoom = old

			if self.floor[self.currentRoom].variant == 2:
				# Its a boss room
				try:
					# Draw the boss bar
					bossbar(screen, self.floor[self.currentRoom].enemies[0].health/100)
				except:
					pass

				if not self.won and self.floorIndex == 6 and len(self.floor[self.currentRoom].enemies) == 0:
					self.banners.append(Banner("You won", self.textures))
					self.won = True


			# DRAW MAP
			screen.blit(self.minimap, (MAPX-mWidth//2, MAPY-mHeight//2))

			# Blit all banners
			for banner in self.banners:
				if banner.render(screen):
					self.banners.remove(banner)

			if joystick != None:
				joystick.update()

			if isaac.dead:
				running = False

			display.flip()
			clock.tick(60)
コード例 #18
0
    def render(self, down):
        "Render store screen"
        self.surface.blit(self.bg, (0, 0))
        self.surface.blit(self.arrow_left, (0, 0))
        mx, my = mouse.get_pos()
        mb = mouse.get_pressed()
        #back button
        if Rect(0, 0, 80, 80).collidepoint(mx, my) and mb[0]:
            self.running = False
        #move car carousel left
        if self.curCar > 0:
            self.surface.blit(self.arrow_left, (100, 344))
            if Rect(100, 344, 80, 80).collidepoint(mx, my) and down:
                self.curCar -= 1
        #move car carousel right
        if self.curCar < len(self.cars) - 1:
            self.surface.blit(self.arrow_right, (844, 344))
            if Rect(844, 344, 80, 80).collidepoint(mx, my) and down:
                self.curCar += 1
        #limit exceeding carousel cars
        if self.curCar >= len(self.cars):
            self.curCar = len(self.cars) - 1
        #move car angle for rotation
        self.angle += 1
        self.carImageRotated = transform.rotozoom(self.cars[self.curCar],
                                                  self.angle, 1)
        self.boundingRect = self.carImageRotated.get_rect()
        self.surface.blit(self.carImageRotated,
                          (self.x - self.boundingRect[2] / 2,
                           self.y - self.boundingRect[3] / 2))
        #blit rotated car, and if car is unlocked, active, or available for purchase
        if str(self.curCar + 1) in self.unlocked:
            self.surface.blit(
                self.smallFont.render("Unlocked", 1, (255, 255, 255)),
                (550, 200))
            if open("files/car.txt").read(
            ) == "res/car%s.png" % str(self.curCar + 1):
                self.surface.blit(self.already, (570, 275))
            else:
                self.surface.blit(self.use, (570, 275))
                if Rect(570, 275, 126, 48).collidepoint(mx, my) and down:
                    f = open("files/car.txt",
                             "w").write("res/car%s.png" % str(self.curCar + 1))
        else:
            #blit cost
            self.surface.blit(self.buy, (570, 275))
            self.surface.blit(
                self.smallFont.render("Cost: ", 1, (255, 255, 255)),
                (550, 350))
            self.surface.blit(self.coinSmall, (660, 360))
            self.surface.blit(
                self.smallFont.render(self.prices[self.curCar], 1,
                                      (255, 255, 255)), (700, 350))
            if Rect(570, 275, 126, 48).collidepoint(mx, my) and down:
                if int(self.coins) - int(self.prices[self.curCar]) < 0:
                    self.errorTime = cTime()
                else:
                    self.coins = str(
                        int(self.coins) - int(self.prices[self.curCar]))
                    f = open("files/cars_unlocked.txt",
                             "a").write("\n%s" % str(self.curCar + 1))
                    f = open("files/coins.txt", "w").write(self.coins)
                    self.unlocked = open(
                        "files/cars_unlocked.txt").read().split("\n")

        self.surface.blit(self.coin, (550, 50))
        self.surface.blit(
            self.mediumFont.render(self.coins, 1, (255, 255, 255)), (630, 45))

        #error message for not enough coins
        if cTime() - self.errorTime <= 3:
            self.surface.blit(
                self.smallFont.render("Not Enough Coins!", 1, (255, 0, 0)),
                (self.surface.get_width() // 2 -
                 (font.Font.size(self.smallFont, "Not Enough Coins!")[0]) // 2,
                 600))
コード例 #19
0
                gameCount = 1

    #render menu if menuscreen
    if menuScreen:
        menu.render(down)
        #end menu
        if not menu.isRunning():
            game = Game(screen)
            gameScreen = True
            menuScreen = False
    #render game if gamescreen
    elif gameScreen:
        screen.fill((140, 140, 140))
        #set time level started
        if gameCount:
            game.sTime(cTime())
            gameCount = 0
        game.run()
        #create new game with next level
        if game.isNextLevel():
            game = Game(screen)
            gameCount = 1
        #go back to menu
        if game.startMenu():
            gameScreen = False
            menuScreen = True
            menu = Menu(screen)
            gameCount = 1

    #mouse down
    if down:
コード例 #20
0
print("Calibrated \n\nBegin Compressions")

#Checks if user wants to quit the program
L = []
thread.start_new_thread(close_program, (L, sysVersion))

#Performs analysis on compressions every 2 seconds concurrent with compressions
iteration = 0
minIterations = 5
file = open("data.txt", "w+")

while True:
    data, sTime, accel = [], [], []

    currentTime = int(cTime())
    endTime = currentTime + compressionresetTime

    while currentTime < endTime:
        currentTime = int(cTime())

        comPort.cleanLine()
        rawData = comPort.readSerial(ser)
        file.write(rawData)
        rawArray = calibrate.formatData(rawData, numpy)

        data.append(rawArray)
        data = numpy.array(data)

        sTime = data[:, 0]
        accel = data[:, txyz]
コード例 #21
0
				gameCount = 1

	#render menu if menuscreen
	if menuScreen:
		menu.render(down)
		#end menu
		if not menu.isRunning():
			game = Game(screen)
			gameScreen = True
			menuScreen = False
	#render game if gamescreen
	elif gameScreen:
		screen.fill((140,140,140))
		#set time level started
		if gameCount:
			game.sTime(cTime())
			gameCount = 0
		game.run()
		#create new game with next level
		if game.isNextLevel():
			game = Game(screen)
			gameCount = 1
		#go back to menu
		if game.startMenu():
			gameScreen = False
			menuScreen = True
			menu = Menu(screen)
			gameCount = 1

	#mouse down
	if down:
コード例 #22
0
	def run(self):
		"Main game run function"
		self.mx, self.my = mouse.get_pos()
		self.mb = mouse.get_pressed()
		#end game and engine delay for 2 seconds
		if self.timer.gameOver():
			self.gameover = True
		if self.lifeCount == 0:
			self.gameover = True
		if cTime()-self.startTime > 2:
			self.timeDelay = True
		#blit heads up display
		self.HUD()
		#get keys pressed
		pressed = key.get_pressed()
		#change gear/speed
		if pressed[K_1]:
			self.shift(1)
		if pressed[K_2]:
			self.shift(2)
		if pressed[K_3]:
			self.shift(3)
		if pressed[K_4]:
			self.shift(4)
		if pressed[K_5]:
			self.shift(5)
		#get arrow/wasd keys for driving
		arrows = [pressed[K_UP], pressed[K_DOWN], pressed[K_RIGHT], pressed[K_LEFT]]
		if pressed[K_DOWN] and not self.gameover:
			self.gear.gearImage = image.load("res/gear_r.png")
		elif not self.gameover:
			self.gear.gearImage = image.load("res/gear_"+str(self.mainCar.speed)+".png")
		wasd = [pressed[K_w],pressed[K_s],pressed[K_d],pressed[K_a]]
		#if game is not ended, drive
		if not self.gameover:
			if pressed[K_e]:
				self.mainCar.brake()
				self.mainCar.drive()
			elif True in arrows and self.timeDelay:
				self.mainCar.drive(pressed[K_UP], pressed[K_DOWN], pressed[K_RIGHT], pressed[K_LEFT])
				self.mainCar.brakeSound.stop()
			elif True in wasd and self.timeDelay:
				self.mainCar.drive(pressed[K_w],pressed[K_s],pressed[K_d],pressed[K_a])
				self.mainCar.brakeSound.stop()
			else:
				self.mainCar.drive()
				self.mainCar.brakeSound.stop()
		#blit obstacle cars and check collisoin from main car
		for car in self.carObsctacles:
			if Rect((car.x-car.boundingRect[2]/2,car.y-car.boundingRect[3]/2, car.boundingRect[2], car.boundingRect[3])).colliderect(Rect(self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])):
				for pt in self.mainCar.outlineRotated:
					if (int(pt[0]),int(pt[1])) in car.outlineRotated and self.timeDelay:
						self.crash = True
						self.crashX, self.crashY = int(pt[0]),int(pt[1])
					self.crashObj = car
			car.render()
		#blit walls, cone, and grass
		yellow = False
		for wall in self.walls:
			if yellow:
				wall.render(self.wall_y)
				yellow = False
			else:
				wall.render(self.wall_b)
				yellow = True
			if wall.getBoundRect().colliderect((self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])):
				for pt in self.mainCar.outlineRotated:
					if wall.getBoundRect().collidepoint(pt) and self.timeDelay:
						self.crash = True
						self.crashX, self.crashY = int(pt[0]),int(pt[1])
						self.crashObj = wall
		for gr in self.grasses:
			self.surface.blit(self.grass, gr)
		for cone in self.cones:
			cone.render(self.coneImage)
			if cone.getBoundRect().colliderect((self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])):
				for pt in self.mainCar.outlineRotated:
					if cone.getBoundRect().collidepoint(pt) and self.timeDelay:
						self.crash = True
						self.crashX, self.crashY = int(pt[0]),int(pt[1])
						self.crashObj = wall

		#render parking spot and main car
		self.parkSpot.render()
		self.mainCar.render()

		#if car crashed restart car, remove life, and blit crash sign
		if self.crash:
			self.surface.blit(self.crashImage, (self.crashX-40,self.crashY-34))
			self.crash = False
			self.mainCar.crashed(self.crashObj, (self.crashX, self.crashY))
			self.lostLife()
			self.crashTime = cTime()
			self.timeDelay = False
			self.startTime = cTime()
			if self.lifeCount > 0:
				mixer.music.load("res/audio/start.mp3")
				mixer.music.play(0)
		#end game if gameover and write to files
		if self.gameover:
			if self.levelComplete:
				self.complete.setText(["Level completed in %s seconds" % str(self.timeLeft)])
				self.complete.render(self.stars)
				self.surface.blit(self.nextLevel, (550,500))
				self.surface.blit(self.menuButton, (350,470))
				newUnlock = open("files/unlocked_levels.txt").read()
				if int(newUnlock) == self.curLevel:
					newUnlock = str(int(newUnlock)+1)
				f1 = open("files/unlocked_levels.txt", "w")
				f1.write(newUnlock)
				f1.close()
				if self.curLevel < 15 and Rect(550,500,162,48).collidepoint(self.mx,self.my) and self.mb[0]:
					f2 = open("files/selected_level.txt", "w")
					f2.write(str(self.curLevel+1))
					f2.close()
					self.goNextLevel = True
				elif Rect(350,470,82,84).collidepoint(self.mx,self.my) and self.mb[0]:
					self.goMenu = True
			else:
				self.fail.render(0)
			self.surface.blit(self.restart, (480, 384))
			if Rect(480,384,64,64).collidepoint(self.mx,self.my) and self.mb[0]:
				self.goNextLevel = True

		#check if car is in parking and asign stars based on time and life
		if self.mainCar.checkPark(self.parkSpot):
			if not self.justEnded:
				self.justEnded = True
				self.timeLeft = int(ceil(self.levelTime - self.timer.end()))
				if self.timeLeft < self.levelTime/4 and self.lifeCount == 5:
					self.stars = 3
				elif self.timeLeft < self.levelTime/2 and self.lifeCount >= 3:
					self.stars = 2
				else:
					self.stars = 1
				coins = int(open("files/coins.txt").read()) + self.stars
				open("files/coins.txt", "w").write(str(coins))
				starF = open("files/stars.txt").read().split("\n")
				if int(starF[self.curLevel-1]) < self.stars:
					starF[self.curLevel-1] = str(self.stars)
				open("files/stars.txt", "w").write("\n".join(starF))
			self.levelComplete = True