def action(self, bk): screen = pygame.display.get_surface() s = Spaceship(1, 320) asteroid = Asteroid(500, 100) asteroid2 = Asteroid(800, 200) asteroid3 = Asteroid(1200, 350) asterow = [asteroid, asteroid2, asteroid3] air = [s] asteroids = pygame.sprite.RenderPlain(asterow) ss = pygame.sprite.RenderPlain(air) timer = pygame.time.Clock() while 1: timer.tick(600) if self.input(pygame.event.get()) == 1: return 1, -1 blocks_hit_list = pygame.sprite.spritecollide(s, asteroids, False) if len(blocks_hit_list) > 0: self.score -= len(blocks_hit_list) asteroids.draw(screen) ss.draw(screen) if self.score < 1: return 3, self.total_score // 100 s.rect.x = self.x_coord s.rect.y = self.y_coord asteroid.rect.x = asteroid.rect.x - 1 asteroid2.rect.x = asteroid2.rect.x - 1 asteroid3.rect.x = asteroid3.rect.x - 1 if asteroid.rect.x < 0: asteroid.rect.x = 500 asteroid.rect.y = 100 if asteroid2.rect.x < 0: asteroid2.rect.x = 800 asteroid2.rect.y = 200 if asteroid3.rect.x < 0: asteroid3.rect.x = 1200 asteroid3.rect.y = 350 if self.shag > 300: # self.shag = 0 self.go1 = random.randint(-1, 1) self.go2 = random.randint(-1, 1) self.go3 = random.randint(-1, 1) asteroid.rect.y += self.go1 asteroid2.rect.y += self.go2 asteroid3.rect.y += self.go3 self.shag += 1 screen.blit(bk, (0, 0)) font = pygame.font.Font(None, 25) white = (255, 255, 255) life = int(self.score / 10) text = font.render("Health: " + str(life), True, white) screen.blit(text, [10, 10]) text = font.render("Score: " + str(self.total_score // 100), 1, white) screen.blit(text, (475, 10)) asteroids.update() ss.update() asteroids.draw(screen) ss.draw(screen) pygame.display.flip() self.total_score += timer.get_time()
def new_player(player_ship_name, i): p = Player(str(i)) # create player obj ship_data = gA.get_ship_data(player_ship_name) # get ship data ship = Spaceship(ship_data[0], ship_data[1]) # create ship obj p.load_ship(ship) # load ship obj to player obj return p # return player obj
def main(argv: List[str]) -> None: """Main function to initialize objects and start game loop""" aesthetics.clear() # Clear screen on game start # Process command-line arguments argvProcessing(argv) # Instantiate Spaceship spaceShip = Spaceship( health=100, energy=100, ) # Instantiate Environment environment = Environment(dangerLevel=1, daysLeft=20, dayCount=1, spaceShip=spaceShip) # Start main game loop environment.normalDayEnd()
def init(self): #get joystick controller self.num_joysticks = pygame.joystick.get_count() if self.num_joysticks == 0: print("No joysticks found!") #done = True else: #use joystick 0 print(self.num_joysticks, "joystick(s) found!") self.joystick = pygame.joystick.Joystick(0) self.joystick.init() #pygame.key.set_repeat(CONST.SCREEN_UPDATE_RATE, CONST.SCREEN_UPDATE_RATE) #load and setup background image self.background_image = pygame.image.load( "pix/background.bmp").convert() #setup sprite lists #list of all actors self.actors = pygame.sprite.Group() #list of phasers self.phasers = pygame.sprite.Group() #list of boulders self.boulders = pygame.sprite.Group() #create a spaceship object self.spaceship = Spaceship() #add to the actors sprite list self.actors.add(self.spaceship) self.spaceship.set_image("pix/spaceship_idle.bmp", CONST.BLACK) self.spaceship.border_policy[Spaceship.TOP_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.RIGHT_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.LEFT_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.BOTTOM_BORDER] = 'Wrap' #setup sound files self.spaceship_sound = pygame.mixer.Sound('sound/ship_idle.ogg') self.spaceship_sound_channel = self.spaceship_sound.play(loops=-1, maxtime=0, fade_ms=0) self.spaceship_sound_channel.set_volume(CONST.SOUND_SHIP_IDLE_VOLUME) self.phaser_sound = pygame.mixer.Sound('sound/laser.ogg') self.spaceship.location = Vect2(CONST.SCREEN_X_SIZE / 2.0, CONST.SCREEN_Y_SIZE / 2.0) self.spaceship.max_velocity = 0.3 #pixels/ms self.spaceship_angle = 0 self.keyboard_dx = 0.0 self.keyboard_dy = 0.0 self.old_dy = 0 #used to check when dy changes #free_running_counter = 0 #find every image file in the boulders folder self.boulder_files = self.findFilesInDir('pix/asteroids', '.bmp') #for f in boulder_files: # print(f) self.old_collision_status = False
class Game(object): def __init__(self, screen): super().__init__() self.screen = screen #the game's background image self.backgroundimage = None def __str__(self): return 'Game' def findFilesInDir(self, directory, extension): '''function that searches the specified 'directory' for files with the supplied extention. The function returns a list of these files.''' foundFiles = [] filenames = os.listdir(directory) for filename in filenames: if filename[-len(extension):] == extension: foundFiles.append(directory + '/' + filename) #print ('===>' + filename) return foundFiles def init(self): #get joystick controller self.num_joysticks = pygame.joystick.get_count() if self.num_joysticks == 0: print("No joysticks found!") #done = True else: #use joystick 0 print(self.num_joysticks, "joystick(s) found!") self.joystick = pygame.joystick.Joystick(0) self.joystick.init() #pygame.key.set_repeat(CONST.SCREEN_UPDATE_RATE, CONST.SCREEN_UPDATE_RATE) #load and setup background image self.background_image = pygame.image.load( "pix/background.bmp").convert() #setup sprite lists #list of all actors self.actors = pygame.sprite.Group() #list of phasers self.phasers = pygame.sprite.Group() #list of boulders self.boulders = pygame.sprite.Group() #create a spaceship object self.spaceship = Spaceship() #add to the actors sprite list self.actors.add(self.spaceship) self.spaceship.set_image("pix/spaceship_idle.bmp", CONST.BLACK) self.spaceship.border_policy[Spaceship.TOP_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.RIGHT_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.LEFT_BORDER] = 'Wrap' self.spaceship.border_policy[Spaceship.BOTTOM_BORDER] = 'Wrap' #setup sound files self.spaceship_sound = pygame.mixer.Sound('sound/ship_idle.ogg') self.spaceship_sound_channel = self.spaceship_sound.play(loops=-1, maxtime=0, fade_ms=0) self.spaceship_sound_channel.set_volume(CONST.SOUND_SHIP_IDLE_VOLUME) self.phaser_sound = pygame.mixer.Sound('sound/laser.ogg') self.spaceship.location = Vect2(CONST.SCREEN_X_SIZE / 2.0, CONST.SCREEN_Y_SIZE / 2.0) self.spaceship.max_velocity = 0.3 #pixels/ms self.spaceship_angle = 0 self.keyboard_dx = 0.0 self.keyboard_dy = 0.0 self.old_dy = 0 #used to check when dy changes #free_running_counter = 0 #find every image file in the boulders folder self.boulder_files = self.findFilesInDir('pix/asteroids', '.bmp') #for f in boulder_files: # print(f) self.old_collision_status = False def run(self, elapsed_time): done = False # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: #print(event.key) if event.key == pygame.K_LEFT: self.keyboard_dx = -CONST.JOYSTICK_X_SCALE / 2 elif event.key == pygame.K_RIGHT: self.keyboard_dx = CONST.JOYSTICK_X_SCALE / 2 elif event.key == pygame.K_UP: self.keyboard_dy = -CONST.JOYSTICK_Y_SCALE / 2 #print(dy) elif event.key == pygame.K_DOWN: self.keyboard_dy = CONST.JOYSTICK_Y_SCALE / 2 #print(dy) elif event.key == pygame.K_q: done = True elif event.key == pygame.K_d: print(self.spaceship, elapsed_time, len(self.phasers)) elif event.key == pygame.K_SPACE: self.phaser_sound.play() new_phaser = Phaser( self.spaceship.location, self.spaceship.heading * CONST.PHASER_SPEED, CONST.PHASER_DISTANCE) self.phasers.add(new_phaser) self.actors.add(new_phaser) elif event.key == pygame.K_b: #location, velocity, angular_velocity_dps, image boulder_filename = self.boulder_files[random.randint( 0, len(self.boulder_files) - 1)] new_boulder = Boulder( Vect2(320, 240), Vect2(0.2 * random.random() - 0.1, 0.2 * random.random() - 0.1), 60.0 * random.random() - 30, boulder_filename) #new_boulder = Boulder( Vect2(320, 240), Vect2(0.2, 0.1), 20.0, "pix/asteroids/boulder1_120.bmp" ) new_boulder.border_policy[Spaceship.TOP_BORDER] = 'Wrap' new_boulder.border_policy[Spaceship.RIGHT_BORDER] = 'Wrap' new_boulder.border_policy[Spaceship.LEFT_BORDER] = 'Wrap' new_boulder.border_policy[Spaceship.BOTTOM_BORDER] = 'Wrap' self.boulders.add(new_boulder) self.actors.add(new_boulder) print("#boulders = ", len(self.boulders)) if event.type == pygame.KEYUP: #print(event.key) if event.key == pygame.K_LEFT: self.keyboard_dx = 0.0 elif event.key == pygame.K_RIGHT: self.keyboard_dx = 0.0 elif event.key == pygame.K_UP: self.keyboard_dy = 0.0 #print(dy) elif event.key == pygame.K_DOWN: self.keyboard_dy = 0.0 #print(dy) dx = self.keyboard_dx dy = self.keyboard_dy # --- Game logic goes here # --- Collision detection with asteroids # See if the spaceship has collided with any of the asteroids blocks_hit_list = pygame.sprite.spritecollide( sprite=self.spaceship, group=self.boulders, dokill=False, collided=pygame.sprite.collide_mask) #dokill=False means do not remove colliding boulder from the boulder list # Check the list of collisions. if blocks_hit_list == []: collision = False else: collision = True if self.num_joysticks != 0: dx += CONST.JOYSTICK_X_SCALE * self.joystick.get_axis( CONST.JOYSTICK_X_AXIS) dy += CONST.JOYSTICK_Y_SCALE * self.joystick.get_axis( CONST.JOYSTICK_Y_AXIS) if self.joystick.get_button(5): self.phaser_sound.play() self.phasers.add( Phaser(self.spaceship.location, self.spaceship.heading * CONST.PHASER_SPEED, CONST.PHASER_DISTANCE)) #only respond when the joystick is more than 10% of full scale if abs(dx) >= 0.1 * CONST.JOYSTICK_X_SCALE: self.spaceship_angle += dx self.spaceship.heading = Vect2(math.cos(-self.spaceship_angle), math.sin(self.spaceship_angle)) if abs(dy) >= 0.1 * (-CONST.JOYSTICK_Y_SCALE): self.spaceship.acceleration = self.spaceship.heading * dy else: dy = 0 self.spaceship.acceleration = Vect2(0, 0) self.spaceship.velocity *= 0.99 #if the value of dy has changed, (i.e., the ship has accelerated) then change the spaceship image if dy != self.old_dy or collision != self.old_collision_status: if dy == 0: #when idling, the ship has no fire behind it if collision == True: self.spaceship.set_image("pix/hit_spaceship_idle.bmp", CONST.BLACK) else: self.spaceship.set_image("pix/spaceship_idle.bmp", CONST.BLACK) self.spaceship_sound_channel.set_volume( CONST.SOUND_SHIP_IDLE_VOLUME) else: #when the ship is accelerating, there is fire behind it if collision == True: self.spaceship.set_image("pix/hit_spaceship_idle.bmp", CONST.BLACK) else: self.spaceship.set_image("pix/spaceship.bmp", CONST.BLACK) self.spaceship_sound_channel.set_volume( CONST.SOUND_SHIP_VOLUME) self.old_dy = dy self.old_collision_status = collision self.spaceship.update_position(elapsed_time) # --- Drawing code goes here #First, draw the background. Place all other drawing code AFTER this command. self.screen.blit(self.background_image, [0, 0]) for phaser in self.phasers: phaser.update_position(elapsed_time) #draw the phaser #phaser.blit_to_screen(self.screen) if phaser.end_of_life == True: self.phasers.remove(phaser) for boulder in self.boulders: boulder.update_position(elapsed_time) #boulder.blit_to_screen(self.screen) #draw the spaceship #spaceship.blit_to_screen(self.screen) #draw all sprites self.actors.draw(self.screen) return done def quit(self): self.spaceship_sound.fadeout(2000) if self.num_joysticks != 0: self.joystick.quit()
pygame.init() backgroundImage = pygame.transform.scale(pygame.image.load("images/stars.png"), (900, 600)) SCREEN_WIDTH = backgroundImage.get_width() SCREEN_HEIGHT = backgroundImage.get_height() FPS = 60 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Asteroid - CS301 - Jimenez") screen.blit(backgroundImage, (0, 0)) gameLoop = False timer = pygame.time.Clock() spaceshipSprite = Spaceship(["images/rocket2a.png", "images/rocket2b.png"], screen.get_size(), "images/rocket1.png") instruction = Label("Press the arrow keys to move!", 30, (SCREEN_WIDTH // 2, 30), (255, 255, 255)) collisionLabel = Label("Collisions: 0", 30, (80, SCREEN_HEIGHT - 30), (255, 255, 255)) scoreLabel = Label("Score: 0", 30, (SCREEN_WIDTH - 60, SCREEN_HEIGHT - 30), (255, 255, 255)) gameOverLabel = Label("GAME OVER!", 80, (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2), (255, 255, 255)) spriteGroup = pygame.sprite.Group(spaceshipSprite, instruction, collisionLabel, scoreLabel) iteration = 0 asteroids = [] collisions = 0 gameOver = False score = 0
def action(self, bk): screen = pygame.display.get_surface() s = Spaceship(1, 320) ''' asteroid = Asteroid(500, 100) asteroid2 = Asteroid(800, 200) asteroid3 = Asteroid(1200, 350) asterow = [asteroid, asteroid2, asteroid3] ''' asterow = [] # An: eliminated code duplicate for point in Game.ASTEROIDS_SPAWN_COORDINATES: asterow.append(Asteroid(point[0], point[1])) air = [s] asteroids = pygame.sprite.RenderPlain(asterow) ss = pygame.sprite.RenderPlain(air) timer = pygame.time.Clock() while 1: timer.tick(600) if self.input(pygame.event.get()) == 1: return 1, -1 self.move() self.check_border_intersection() blocks_hit_list = pygame.sprite.spritecollide(s, asteroids, False) if len(blocks_hit_list) > 0: self.score -= len(blocks_hit_list) asteroids.draw(screen) ss.draw(screen) if self.score < 1: return 3, self.total_score // 100 s.rect.x = self.x_coord s.rect.y = self.y_coord # An: eliminated code duplicate for aster in asterow: aster.rect.x = aster.rect.x - Game.ASTEROID_SPEED ''' asteroid.rect.x = asteroid.rect.x - Game.ASTEROID_SPEED asteroid2.rect.x = asteroid2.rect.x - Game.ASTEROID_SPEED asteroid3.rect.x = asteroid3.rect.x - Game.ASTEROID_SPEED ''' # An : eliminated code diplicate(below this for-loop) for i in range(len(asterow)): if asterow[i].rect.x < 0: asterow[i].rect.x = Game.ASTEROIDS_SPAWN_COORDINATES[i][0] asterow[i].rect.y = Game.ASTEROIDS_SPAWN_COORDINATES[i][1] ''' if asteroid.rect.x < 0: asteroid.rect.x = 500 asteroid.rect.y = 100 if asteroid2.rect.x < 0: asteroid2.rect.x = 800 asteroid2.rect.y = 200 if asteroid3.rect.x < 0: asteroid3.rect.x = 1200 asteroid3.rect.y = 350 ''' if self.shag > 300: # An : eliminated code duplicate for i in range(len(self.asteroid_shifts)): self.asteroid_shifts[i] = random.randint(-1, 1) # self.go1 = random.randint(-1, 1) # self.go2 = random.randint(-1, 1) # self.go3 = random.randint(-1, 1) # An : eliminated code duplicate for i in range(len(self.asteroid_shifts)): asterow[i].rect.y += self.asteroid_shifts[i] # asteroid.rect.y += self.go1 # asteroid2.rect.y += self.go2 # asteroid3.rect.y += self.go3 self.shag += 1 screen.blit(bk, (0, 0)) font = pygame.font.Font(None, 25) white = (255, 255, 255) life = int(self.score / 10) text = font.render("Health: " + str(life), True, white) screen.blit(text, [10, 10]) text = font.render("Score: " + str(self.total_score // 100), 1, white) screen.blit(text, (475, 10)) asteroids.update() ss.update() asteroids.draw(screen) ss.draw(screen) pygame.display.flip() self.total_score += timer.get_time()
".png") showLives = canvas.create_image(canvas.winfo_reqwidth() - imgLives[0].width() + 5, 50, image=imgLives[lives - 1]) #text showing points showPoints = canvas.create_text(30, 10, text='Spacebar', font="neuropol.ttf 30", fill="orange", anchor="nw") background_timer() #background animation timer player = Spaceship(canvas) #create a player spaceship object lasers = [Laser(canvas)] * 10 #list of laser objects asteroids = [Asteroid(canvas)] * 20 #list of asteroid objects spawnasteroid() root.bind("<Motion>", onmousemove) #event handling for cursor movement and keyboard clicks root.bind("<KeyRelease>", shoot) hit_asteroid() #collision detection and health loss detection hit_ship() lose_health() root.mainloop() #loop the game window to keep it on