class Menu(): def __init__(self, screen, settings): self.settings = settings self.screen = screen self.frame = pygame.Surface((700, 500)) self.frame.fill((7, 5, 9)) self.rect_frame = self.frame.get_rect() self.rect_frame.x = int( (self.settings.screen_width - self.rect_frame.width) / 2) self.rect_frame.y = int( (self.settings.screen_height - self.rect_frame.height) / 2) self.items = Group() # self.items.add(Item("MINER",70,self.frame,50)) # self.items.add(Item("NEW GAME",30,self.frame,135,"new_game")) # self.items.add(Item("High Score",30,self.frame,175,"high_score")) # self.items.add(Item("EXIT",30,self.frame,215,"")) # self.items.add(Item("Code by Cristhian Ferreira",15,self.frame,345)) # self.items.add(Item("Created with Pygame and Love",15,self.frame,380)) def draw(self): self.screen.blit(self.frame, self.rect_frame) for item in self.items.sprites(): item.draw() def check_item_clicked(self, x, y): for item in self.items.sprites(): if item.title_rect.collidepoint(x, y): print(item.title)
class Game(): def __init__(self): """Initialize game.""" self.settings = Settings() self.initScreen() self.ship = Ship(self.screen) self.bullets = Group() # Startup app sound pygame.mixer.music.load('sounds/start.mp3') #pygame.mixer.music.play(0) def draw(self): # Draw Background & a rectangle self.screen.fill(self.settings.bg_color) pygame.draw.rect(self.screen, (60, 60, 180), self.small_screen_rect) # Draw Ship self.ship.draw() for bullet in self.bullets.sprites(): bullet.draw() # Make the most recently Drawn screen visible. pygame.display.flip() def update(self): # Draw Background self.ship.update() for bullet in self.bullets.sprites(): bullet.update() for bullet in self.bullets.copy( ): # .copy() is used in order to use bullets.remove above if bullet.rect.bottom <= 0: self.bullets.remove(bullet) def processKeyDown(self, key): if key == pygame.K_RIGHT: self.ship.moveRight(True) elif key == pygame.K_LEFT: self.ship.moveLeft(True) elif key == pygame.K_SPACE: new_bullet = Bullet(self.settings, self.screen, self.ship) self.bullets.add(new_bullet) def processKeyUp(self, key): if key == pygame.K_RIGHT: self.ship.moveRight(False) elif key == pygame.K_LEFT: self.ship.moveLeft(False) def initScreen(self): self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) self.screen_rect = self.screen.get_rect() self.small_screen_rect = pygame.Rect(30, 30, self.settings.screen_width - 60, self.settings.screen_height - 60)
def run_game(): #Initialize game and create a screen object. pygame.init() #550 pixel wide and 550 pixel high screen = pygame.display.set_mode((550, 550)) pygame.display.set_caption("11X11 grid map") #make a ship ship = Ship(screen) print('initial position of the ship: ', '(0,0)') #make the goal key = Key(screen) # Set the background color. bg_color = (245, 245, 245) #make a brick bricks = Group() brick_coor = [(0, 5), (2, 5), (3, 5), (4, 5), (5, 0), (5, 1), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 10), (6, 6), (7, 6), (9, 6), (10, 6)] for (x, y) in brick_coor: brick = Wall_block(screen, 50 * x, 50 * y) bricks.add(brick) #Start the main loop for the game. while True: #Watch for keyboard and mouse events. step2(ship, key, bricks) #Redraw screen during each pass through the loop screen.fill(bg_color) drawGrid(screen) ship.blitme() key.blitme() for brick in bricks.sprites(): brick.draw() #Make the most recently drawn screen visible. pygame.display.flip()
def run_game(): pygame.init() screen = pygame.display.set_mode((800,600)) pygame.display.set_caption('MO') #bullet_rect = pygame.Rect(400, 300, 3, 15) bg_color = (230,230,230) #bullet_color = 60,60,60 bullets = Group() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: new_bullet = Bullet(screen) new_bullet.draw_bullet() bullets.add(new_bullet) #new_bullet1 = Bullet(screen) #bullets.add(new_bullet1) screen.fill(bg_color) bullets.update() for bullet in bullets.sprites(): bullet.draw_bullet() pygame.display.flip()
class UFOs: def __init__(self, game): self.settings = game.settings self.screen = game.screen self.game = game self.ufo_group = Group() self.last_ufo = pg.time.get_ticks() def create_ufo_if_time(self): now = pg.time.get_ticks() if now > self.last_ufo + self.settings.ufo_every * 1000: self.ufo_group.add(UFO(game=self.game, parent=self)) self.last_ufo = pg.time.get_ticks() def update(self): self.create_ufo_if_time() self.ufo_group.update() for ufo in self.ufo_group.sprites(): ufo.draw() if ufo.check_edges(): self.ufo_group.remove(ufo) bullet_ufo_collision = pg.sprite.groupcollide( self.ufo_group, self.game.ship.bullet_group_that_kill_aliens, True, True) if bullet_ufo_collision: for ufo in bullet_ufo_collision: print('UFO HIT') ufo.killed() def draw(self): for ufo in self.ufo_group: ufo.draw()
def run_game2(): global ch, dobollet, bulets forrand = 1000 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption('Alien Invasion') planets = Group() t = [0, 1, 1, 1] mars = Planet(ai_settings, screen, 0, 0, t) planets.add(mars) while True: for event in pygame.event.get(): #for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() for planet in planets.sprites(): if planet.rect.collidepoint(mouse_x, mouse_y): print(planet.libe) game.run_game(planet.libe) screen.fill(ai_settings.bg_color) planets.draw(screen) pygame.display.flip()
def update_screen(ai_settings: Settings, screen: Surface, game_stats: GameStats, score_board: Scoreboard, ship: Ship, aliens_group: Group, bullets_group: Group, button): """ Atualiza as imagens na tela, e gera/seta a mais recente \n\r Atualiza também todo os conteúdos que devem ir para a tela \n\r :param ai_settings: Configurações do jogo, objeto de Settings() :param screen: Tela/quadro do jogo, objeto de pygame.display.set_mode() :param ship: Espaçonave do jogo, objeto do tipo Ship() :param game_stats: possui dados estatisticos do jogo, do tipo GameStats() :param aliens_group: Grupo de aliens gerados na tela, objeto de pygame.sprite.Group() :param bullets_group: Grupo de projéteis disparados, objeto de pygame.sprite.Group() :param button: Objeto da classe Button() """ # redesenha a tela screen.fill(ai_settings.bg_color) # redesenha todos os projéteis antes de atualizar a tela = flip() for bullet in bullets_group.sprites(): bullet.draw_bullet() # desenha a nave e o alien ship.blitme() aliens_group.draw(screen) # desenha a pontuação score_board.show_score() # desenha o botão se o jogo não estiver ativo if not game_stats.game_active: button.draw_button() # a presenta a tela mais recente pygame.display.flip()
class BulletManager: def __init__(self, bullet_stats: BulletStats): self._bullets = Group() self._bullet_stats = bullet_stats def add(self, bullet): self._bullets.add(bullet) def update(self, elapsed): self._bullets.update(elapsed) # Get rid of bullets that have disappeared for bullet in self._bullets.copy(): if bullet.rect.bottom <= 0 or bullet.rect.top >= config.screen_height: self._bullets.remove(bullet) def empty(self): self._bullets.empty() def draw(self, screen): self._bullets.draw(screen) def sprites(self): return self._bullets.sprites() def __iter__(self): return self._bullets.__iter__()
def run(): pygame.init() screen = pygame.display.set_mode((500, 500)) class Bullet(Sprite): def __init__(self, screen): super(Bullet, self).__init__() self.screen = screen # 在(0,0)处创建一个表示子弹的矩形,再设置正确的位置 self.rect = pygame.Rect(0, 0, 10, 10) self.rect.x = randint(0, 500) self.color = 60, 60, 60 def update(self): """向上移动子弹""" # 更新表示子弹位置的小数值 self.rect.y -= 1 def draw_bullet(self): """在屏幕上绘制子弹""" pygame.draw.rect(self.screen, self.color, self.rect) bullets = Group() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() screen.fill((200, 200, 200)) pygame.display.flip() for bullet in bullets.sprites(): bullet = Bullet() bullet.draw_bullet()
def run_game(): """Main game program.""" pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Catch Game") # Game stats. stats = GameStats(ai_settings) # Catcher object. catcher = Group() # Ball object. #ball = Ball(ai_settings, screen) ball = Group() # Main game loop. while True: for c in catcher.sprites(): gf.catch_events(c) if stats.game_active: gf.update_catcher(ai_settings, screen, catcher) gf.update_ball(ai_settings, stats, screen, catcher, ball) gf.update_screen(ai_settings, screen, catcher, ball)
def run_game(): """runs game""" pygame.init() settings = Settings() screen = pygame.display.set_mode((settings.screen_width, settings.screen_height)) pygame.display.set_caption("Ball dropper") ship = Ship(settings, screen) balls = Group() create_ball(settings, screen, balls) while True: check_for_events(settings, screen, ship) ship.update() for ball in balls.sprites(): ball.update() check_collision(settings, screen, ship, ball, balls) #if ball: #ball.update() #else: #initialise_ball(settings, screen) update_screen(settings, screen, ship, ball)
def run_game(): pygame.init() screen_wid = 1200 screen_hei = 800 screen = pygame.display.set_mode((screen_wid, screen_hei)) #屏幕大小 pygame.display.set_caption("my first game") #标题 ship = Ship(screen) bullets = Group() monsters = Group() functions.creat_monsters(screen, ship, monsters, screen_wid, screen_hei) stats = Game() while True: functions.event_get(screen, ship, bullets) if stats.active: ship.update() functions.update_monsters(bullets, screen, ship, monsters, screen_wid, screen_hei, stats) functions.update_buttles(bullets, screen, ship, monsters, screen_wid, screen_hei, stats) '''update_screen''' functions.update_buttles(bullets, screen, ship, monsters, screen_wid, screen_hei, stats) screen.fill((230, 230, 230)) for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() monsters.draw(screen) pygame.display.flip()
def run(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Govnokod") bg_color = (30, 144, 255) ai_settings = Settings() bit = Group() b = Bit(ai_settings, screen) bit.add(b) a = Dog(screen) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, a) elif event.type == pygame.KEYUP: check_keyup_events(event, a) for b in bit.sprites(): if b.rect.bottom >= ai_settings.screen_height: sys.exit() a.update() screen.fill(bg_color) lov(ai_settings, screen, bit, a) bit.draw(screen) a.blitme() pygame.display.flip()
def sprites(self) : if(hasattr(self, 'spritedict')): return Group.sprites(self); else : return []; pass;
def run_snake_game(): global screen pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("snake game") clock = pygame.time.Clock() snakes = Group() settings = Settings() snake_body = [] snake1 = Snake_pcs(settings, screen) snake_body.append(snake1) snakes.add(snake1) food = Snake_pcs(settings, screen) while True: gf.check_events(snakes, settings) gf.snake_col_self(snake_body, snakes, settings) if settings.run_game: gf.create_food(settings, food, snakes) new_snake = Snake_pcs(settings, screen) gf.snake_food_collide(new_snake, settings, snake_body, snakes, food) if not settings.food_vis: gf.move_snake(snake_body, snakes, settings, new_snake) gf.wall_collide(snake_body, settings) screen.fill((169, 169, 169)) draw_grid() food.draw_food() for snake in snakes.sprites(): snake.draw_snake() pygame.display.flip() pygame.time.delay(100) clock.tick(50)
def generate_platforms(self): """Make groups of sprites that contain the blocks for the player to stand on""" # Every block is contained within the self.player_bounds_rect # Find each "row" of tiles that can contain blocks and add some # Eligible rows are every 3rd row starting from the 2nd to top, except the very bottom floor row_rect = pygame.Rect( (self.player_bounds_rect.left, self.player_bounds_rect.top + (self.settings.tile_height * 2)), (self.player_bounds_rect.width, self.settings.tile_width)) self.block_group.empty() for row in range(0, (self.settings.map_number_floors - 1)): new_group = Group() # Each column in the eligble row has 4 valid placements for a block # Note - there are more permutations, these are just the ones allowed # OO OO OO OO # XX OX OX OO for col in range(0, self.settings.map_playable_width): bounding_rect = pygame.Rect(0, 0, 0, 0) bounding_rect.top = row_rect.top bounding_rect.left = row_rect.left + col * self.settings.tile_width self.generate_blocks(bounding_rect, new_group, random.choice([True, False]), random.choice([True, False])) # Each row is its own group. This could limit collision checks later self.block_group.add(new_group.sprites()) # Shif the bounding rect down one floor row_rect = row_rect.move(0, self.settings.tile_height * 3)
def run_game(): #initialize background pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Ball catcher!") stats = GameStats(ai_settings) catcher = Group() baller = Group() #create an instance from store game statistics and create scoreboards sb = Scoreboard(ai_settings, screen, stats) while True: if stats.game_active: for c in catcher.sprites(): gf.check_events(c) #update catcher gf.update_catcher(ai_settings, screen, catcher) #update baller gf.update_baller(ai_settings, stats, sb, screen, catcher, baller) gf.update_screen(ai_settings, screen, stats, sb, baller, catcher)
def _create_image(self): grp = Group() for word in self.words: if len(grp.sprites()) == 0: word.scale(self.ratio+0.2) pm_w = word.rect.width pm_h = word.rect.height pm_x, pm_y = place_primary(pm_w, pm_h) word.rect.x, word.rect.y = pm_x, pm_y arch_x = pm_x + pm_w/2 arch_y = pm_y + pm_h/2 else: word.scale(self.ratio) for x, y in archimedean_spiral(False): if self.debug: rs = Surface((5, 5)) rs.fill((0, 0, 255)) rs.set_alpha(100) self.sf.blit(rs, (x + arch_x, y + arch_y)) word.set_position(x + arch_x, y + arch_y) x_out = CANVAS_WIDTH - CANVAS_PADDING < word.rect.x + word.rect.width or word.rect.x < CANVAS_PADDING y_out = CANVAS_HEIGHT - CANVAS_PADDING < word.rect.y + word.rect.height or word.rect.y < CANVAS_PADDING out_of_bound = x_out or y_out if spritecollideany(word, grp, collide_mask) is None and not out_of_bound: if self.debug: rs = Surface((5, 5)) rs.fill((0, 255, 0)) rs.set_alpha(100) self.sf.blit(rs, (x + arch_x, y + arch_y)) break self.sf.blit(word.image, word.rect) grp.add(word)
class ScroeBoard(): def __init__(self, screen, status, ai_setting): self.screen = screen self.status = status self.ai_setting = ai_setting self.screen_rect = screen.get_rect() self.text_color = (0, 0, 0) self.font = pygame.font.SysFont(None, 48) self.prep_score() self.prep_high_score() self.prep_level() self.prep_ship() def prep_score(self): round_score = int(round(self.status.score, -1)) score_str = "{:,}".format(round_score) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_setting.bg_color) self.score_image_rect = self.score_image.get_rect() self.score_image_rect.right = self.ai_setting.Screen_width - 10 self.score_image_rect.top = 10 def prep_high_score(self): high_score_str = "{:,}".format(self.status.high_score) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_setting.bg_color) self.high_score_image_rect = self.high_score_image.get_rect() self.high_score_image_rect.centerx = self.screen_rect.centerx self.high_score_image_rect.top = self.score_image_rect.top def prep_level(self): level_str = "{:,}".format(self.status.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_setting.bg_color) self.level_image_rect = self.level_image.get_rect() self.level_image_rect.right = self.score_image_rect.right self.level_image_rect.top = self.score_image_rect.bottom + 10 def prep_ship(self): self.ships = Group() for number in range(self.status.ship_left): ship = Ship(self.screen, self.ai_setting) ship.rect.left = 10 + number * ship.rect.width ship.rect.top = self.score_image_rect.top self.ships.add(ship) def blitme(self): self.screen.blit(self.score_image, self.score_image_rect) self.screen.blit(self.high_score_image, self.high_score_image_rect) self.screen.blit(self.level_image, self.level_image_rect) for ship in self.ships.sprites(): ship.blitme()
def update_screen(self, game_settings: Settings, character: Character, obstacles: Group, bombs: Group, character2: Character, bombs2: Group, hard_obstacles: Group, explosions: Group, treasures: Group): self.screen.fill(game_settings.bg_color) for bomb in bombs.sprites(): bomb.draw_bomb() for bomb in bombs2.sprites(): bomb.draw_bomb() character.blitme() character2.blitme() obstacles.draw(self.screen) for explosion in explosions.sprites(): explosion.drawme() hard_obstacles.draw(self.screen) treasures.draw(self.screen) pygame.display.flip()
def check_aliens_bottom(ai_settings: Settings, screen: Surface, stats: GameStats, sb: Scoreboard, ship: Ship, aliens: Group, bullets: Group): screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets) break
class SidewaysShooter: def __init__(self): pygame.init() self.screen = pygame.display.set_mode(DISPLAY_MODE) self.screen_rect = self.screen.get_rect() pygame.display.set_caption(PROGRAM_NAME) self.ship = Ship(self.screen) self.running = False self.bullets = Group() def process_keydown(self, event): if event.key == pygame.K_DOWN: self.ship.moving_down = True elif event.key == pygame.K_UP: self.ship.moving_up = True elif event.key == pygame.K_SPACE: self.fire_bullet() def process_keyup(self, event): if event.key == pygame.K_DOWN: self.ship.moving_down = False elif event.key == pygame.K_UP: self.ship.moving_up = False def fire_bullet(self): self.bullets.add(Bullet(self.ship.rect)) def process_events(self): events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: self.process_keydown(event) elif event.type == pygame.KEYUP: self.process_keyup(event) def update(self): self.ship.update() self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.left > self.screen_rect.right: self.bullets.remove(bullet) def draw(self): self.screen.fill(BACKGROUND_COLOR) for bullet in self.bullets.sprites(): bullet.draw(self.screen) self.ship.draw(self.screen) pygame.display.flip() def run(self): self.running = True while self.running: self.process_events() self.update() self.draw()
def run_game(): ai_settings = Settings() pygame.init() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) bullets = Group() # Group 存放是sprite的游戏对象 aliens = Group() # 存放外星人的group create_fleet(ai_settings, screen, ship, aliens) # 创建外星人群 # 游戏主循环 while True: # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: # pygame.QUIT:窗口的关闭按钮 sys.exit() elif event.type == pygame.KEYDOWN: # 按下事件 if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) elif event.type == pygame.KEYUP: # 抬起事件 if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False if ship.moving_right and ship.rect.right < screen.get_rect().right: ship.center += ai_settings.ship_speed_factor if ship.moving_left and ship.rect.left > screen.get_rect().left: ship.center -= ai_settings.ship_speed_factor # 绘制飞船 ship.rect.centerx = ship.center screen.fill(ai_settings.bg_color) ship.blitme() # 绘制子弹 for bullet in bullets.sprites(): if bullet.rect.bottom < 0: bullets.remove(bullet) continue bullet.y -= bullet.speed_factor # 计算子弹的y方向的位置 bullet.rect.y = bullet.y # 更新子弹这个Rect的位置 pygame.draw.rect(bullet.screen, bullet.color, bullet.rect) update_aliens(ai_settings, aliens) for alien in aliens: alien.bliteme() pygame.display.flip() # 绘制屏幕
class BlackLines(): """黑行组""" def __init__(self): self.line = Group() def drawme(self): """在屏幕上绘制黑行组""" for black_line in self.line.sprites(): black_line.drawme()
def run(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption('飞机大作战') ship = Ship(ai_settings, screen) bullets = Group() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: ship.moving_right = True if event.key == pygame.K_LEFT: ship.moving_left = True if event.key == pygame.K_UP: ship.moving_up = True if event.key == pygame.K_DOWN: ship.moving_down = True elif event.key == pygame.K_SPACE: if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: ship.moving_right = False if event.key == pygame.K_LEFT: ship.moving_left = False if event.key == pygame.K_UP: ship.moving_up = False if event.key == pygame.K_DOWN: ship.moving_down = False ship.update() bullets.update() for bullet in bullets.copy(): if bullet.rect.left > ai_settings.screen_width: bullets.remove(bullet) screen.fill(ai_settings.bg_color) for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() pygame.display.flip()
def check_fleet_bordas(ai_settings: Settings, aliens_group: Group): """ Verifica se algum alien do group encostou na borda \n\r :param ai_settings: Objeto da classe Settings() :param aliens_group: Objeto da class pygame.sprite.Group() """ for alien in aliens_group.sprites(): if alien.check_bordas(): mudar_direcao_fleet(ai_settings, aliens_group) break
def check_aliens_bottom(ai_settings: Settings, screen: Surface, stats: GameStats, scoreboard: Scoreboard, ship: Ship, aliens: Group, bullets: Group) -> None: """Check if any aliens have reached the bottom of the screen""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: ship_hit(ai_settings, screen, stats, scoreboard, ship, aliens, bullets) break
def run_simulator(): # 构建配置文件对象 settingInfo = Settings() # 需先初始化pygame pygame.init() # 创建主窗口 screen = pygame.display.set_mode( (settingInfo.screen_width, settingInfo.screen_height)) # 设置窗口标题 pygame.display.set_caption("VTS") # 初始化模拟人员数组 persons = Group() # 构建模拟人员(下面会给出函数实现) create_viruses(settingInfo, screen, persons) # 创建启动按钮(名字可自定义……) infect_button = Button(screen, "infect+1") # 该处是程序的主循环 while True: # 填充背景色 screen.fill(settingInfo.bg_color) # 检测消息(就是为了让我们按钮点了起作用,下面会做实现) check_events(settingInfo, screen, persons.sprites(), infect_button) # 绘制所有的模拟人员,包括被感染人员 for person in persons.sprites(): # 注意,该处会调用每个模拟人员的update函数,我之前自己实现的 person.update(settingInfo, persons) # 绘制按钮 infect_button.draw_button() # 控制刷新频率(FPS大家都懂吧…… frames per second 每秒帧数。 大多游戏都是有这个) fcclock.tick(settingInfo.screen_fps) # 调用pygame自己的update函数来刷新页面 pygame.display.update()
def run_game(): pygame.init() #get start time start_time = pygame.time.get_ticks() settings = Settings() settings.mode = 'human' screen = pygame.display.set_mode((settings.screen_width,settings.screen_height)) pygame.display.set_caption("Fill the bottle") conveyor_belt = gf.Conveyor_belt(screen,settings) tank = gf.Tank(screen,settings) #bottle = gf.Bottle(screen,conveyor_belt,tank,settings.color) #print(bottle) waterflow = Group() bottles = [] scoreboard = gf.Scoreboard(screen,settings) game_state = GameStats(settings) timeline = gf.Timeline(screen,settings) while True: seconds = (pygame.time.get_ticks() - start_time) / 1000 if seconds >= settings.time_limit: #if game_state.action_num >= settings.action_limit: print('Final score is %d'%sum(game_state.score_record[:])) if sum(game_state.score_record[:]) >= game_state.highest_score: game_state.highest_score = sum(game_state.score_record[:]) print('New highest score reaches %d'%game_state.highest_score) #flag done and reward, that can be used in further training game_state.done = True game_state.reward = sum(game_state.score_record[:]) #reset the game gf.reset(bottles,waterflow,game_state,tank,settings) game_state.round += 1 print('New round! round %d'%game_state.round) start_time = pygame.time.get_ticks() #update all components bottle = gf.add_bottle(screen,conveyor_belt,tank,settings.water_color,bottles,game_state) gf.check_event(bottle,screen,tank,waterflow,conveyor_belt,game_state,settings) gf.update_water(waterflow,conveyor_belt) timeline.update(game_state) #print('reward_fill is %f'%game_state.reward_fill) #show all components screen.fill(settings.bg_color) conveyor_belt.blitme() tank.blitme() scoreboard.show_score(game_state) timeline.draw() for bottle in bottles: bottle.update(settings.conveyor_speed) bottle.draw() for drop in waterflow.sprites(): drop.draw(settings.water_color) pygame.display.flip()
class Shield(): def __init__(self, screen, ai_settings, ship): """A class that defines a picked up shield.""" self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.ship = ship self.rect = pygame.Rect(0, 0, ship.rect.width + 2 * ai_settings.edge_width, ship.rect.height + 2 * ai_settings.edge_width) self.borders = Group() for edge_index in [0, 1, 3]: border = Border(self, edge_index) self.borders.add(border) self.strength_left = ai_settings.shield_strength self.color_change = [] for i in range(0, 3): self.color_change.append( int((ai_settings.edge_color[i] - ai_settings.bg_color[i]) / self.strength_left)) self.color_change = tuple(self.color_change) self.update() def shield_hit(self): """Decrease shield's strength once it's hit.""" self.strength_left -= 1 for b in range(0, len(self.borders)): color = [] for i in range(0, len(self.borders.sprites()[b].edge_color)): color.append(self.borders.sprites()[b].edge_color[i] - (self.color_change[i])) self.borders.sprites()[b].edge_color = tuple(color) def update(self): """Make the shield follow the ship.""" self.rect.center = self.ship.rect.center self.borders.update() def draw_shield(self): """Draw the edges of the shield.""" for border in self.borders: self.screen.fill(border.edge_color, border.rect)
def mudar_direcao_fleet(ai_settings: Settings, aliens_group: Group): """ Faz toda a tropa descer e muda a direção \n\r :param ai_settings: Objeto da classe Settings() :param aliens_group: Objeto da classe pygame.sprite.Group() """ # para cada alien desce a altura de settings for alien in aliens_group.sprites(): alien.rect.y += ai_settings.fleet_alien_drop_speed # muda a direção de config ai_settings.fleet_alien_direction *= -1
def shoot(self): """Chooses a random bottom enemy to shoot the bullet is added to the self.bullets group """ # pick a random living enemy, then make the bottom living enemy of that column shoot r = random.randint(0, len(self) - 1) ##print ("Random = ", r) ##print ("Enemies = ", len(self)) col = Group.sprites(self)[r].col shooter = self.bottom_sprite(col) new_bullet = Bullet(window_size, bullet_filename, bullet_speed, shooter.rect.center, SOUTH) new_bullet.add(self.bullets)
def update(self): """Instead of updating each sprite independently, this method is changed to move the enemies in unison movement happens once every <move_delay> frames New: a random bottom row enemy will shoot once every <shoot_delay> frames """ # movement self.move_delay_step += 1 if self.move_delay_step == self.move_delay: self.move_delay_step = 0 movement_vector = self.check_vector() for current_sprite in Group.sprites(self): current_sprite.move(movement_vector) self.shoot_delay_step += 1 if self.shoot_delay_step == self.shoot_delay: self.shoot_delay_step = 0 self.shoot()
class LumberjackGame(Microgame): def __init__(self): # TODO: Initialization code here Microgame.__init__(self) self.jack = Man() self.count = 0 self.mycount = pygame.font.SysFont("arial", 50, bold = True) self.left, self.left_rect = _load_image(join("games","Lumberjack","images","timberman_normalleft.png"), 105, 400) self.left_chop, self.leftc_rect = _load_image(join("games","Lumberjack","images","timberman_chopleft.png"), 130, 450) self.right, self.right_rect = _load_image(join("games","Lumberjack","images","timberman_normalright.png"), 500, 400) self.right_chop, self.rightc_rect = _load_image(join("games","Lumberjack","images","timberman_chopright.png"), 375, 450) self.stump = load(join("games","Lumberjack","images","stump.png")) self.sprites = Group(self.jack) self.background = load(join("games","Lumberjack","images","forest.png")) self.tree = Group(treeBlock(LEFT_POSITION, 550, 1)) def start(self): # TODO: Startup code here music.load(join("games","Lumberjack","music","tree_song.ogg")) music.play() self.generateTree() def stop(self): # TODO: Clean-up code here music.stop() def generateTree(self): _ , min_y = self.tree.sprites()[len(self.tree.sprites()) - 1].rect.topleft cur_tree = 0 for n in range(0, (len(self.tree.sprites()) - 1)): _ , y = self.tree.sprites()[n].rect.topleft if y < min_y: min_y = y cur_tree = n if min_y > 0 and min_y <= 550: tree_type = self.tree.sprites()[cur_tree].type if tree_type == 2: self.tree.add(treeBlock(LEFT_POSITION, (min_y - 140), randint(1,2))) elif tree_type == 0: self.tree.add(treeBlock(LEFT_POSITION, (min_y - 140), randint(0,1))) else: self.tree.add(treeBlock(LEFT_POSITION, (min_y - 140), randint(0,2))) def updateTree(self, side): max_y = locals.HEIGHT cur_tree = 0 for n in range(0, (len(self.tree.sprites()))): _ , y = self.tree.sprites()[n].rect.topleft if 550 == y: max_y = y cur_tree = n print max_y, self.tree.sprites()[cur_tree].type if self.tree.sprites()[cur_tree].type == side: self.lose() else: self.tree.remove(self.tree.sprites()[cur_tree]) #self.tree.update() for each in self.tree: each.update() def update(self, events): # TODO: Update code here self.sprites.update() self.generateTree() #Process user input sound_chop = pygame.mixer.Sound(join("games","Lumberjack","music","axe_chop.wav")) if self.jack.image == self.left_chop: self.jack.image = self.left self.jack.rect = self.left_rect elif self.jack.image == self.right_chop: self.jack.image = self.right self.jack.rect = self.right_rect for event in events: if event.type == KEYDOWN and event.key == K_LEFT: self.count += 1 sound_chop.play() self.jack.image = self.left_chop self.jack.rect = self.leftc_rect self.updateTree(2) elif event.type == KEYDOWN and event.key == K_RIGHT: self.count += 1 sound_chop.play() self.jack.image = self.right_chop self.jack.rect = self.rightc_rect self.updateTree(0) def render(self, surface): # TODO: Rendering code here surface.fill(Color(255, 255, 255)) surface.blit(self.background, (0, 0), area = None, special_flags = 0) self.tree.draw(surface) surface.blit(self.stump, (318, 690), area = None, special_flags = 0) self.sprites.draw(surface) label = self.mycount.render(str(self.count), 1, (255, 255, 255)) if self.count <= 9: surface.blit(label, (398, 200)) else: surface.blit(label, (385, 200)) def get_timelimit(self): # TODO: Return the time limit of this game (in seconds, 0 <= s <= 15) #raise NotImplementedError("get_timelimit") return 15
class Controller(object): def __init__(self, size, scene=None, **kw): pygame.init() self.width, self.height = self.size = size self.screen = pygame.display.set_mode(size, **kw) try: self.hard_reset() except Reset: pass self.load_scene(scene) def hard_reset(self): # This dict is where the game should keep # character and story data that persist across phaes, # like lifes, energy, inventory, encounters that happened, etc: self.inside_cut = False self.diary = {} return self.soft_reset() def soft_reset(self, raise_=True): self.actor_positions = {} self.old_top = -20 self.old_left = -20 self.old_tiles = {} self.dirty_tiles = {} self.force_redraw = False self.post_cut_action = None if raise_: raise SoftReset def load_scene(self, scene, skip_post_cut=False, skip_pre_cut=False): if getattr(self, "scene", None) and self.scene.post_cut and not skip_post_cut: post_cut_action = partial(self.load_scene, scene, skip_post_cut=True, skip_pre_cut=skip_pre_cut) return self.enter_cut(self.scene.post_cut, post_cut_action) self.scene = scene scene.set_controller(self) self.all_actors = Group() self.actors = {} self.load_initial_actors() self.messages = Group() if self.scene.pre_cut and not skip_pre_cut: return self.enter_cut(self.scene.pre_cut) def enter_cut(self, cut, post_action=None): self.post_cut_action = post_action self.inside_cut = True self.current_cut = cut(self) return self.update() def leave_cut(self): self.inside_cut = False if self.post_cut_action: action = self.post_cut_action self.post_cut_action = None action() def draw_cut(self): self.current_cut.update() def load_initial_actors(self): for x in range(self.scene.width): for y in range(self.scene.height): cls = self.scene.get_actor_at((x, y)) if not cls: continue name = cls.__name__.lower() actor = cls(self, pos=(x, y)) self.all_actors.add(actor) self.actors.setdefault(name, Group()) self.actors[name].add(actor) if getattr(actor, "main_character", False): self.set_main_character(actor) def set_main_character(self, actor): self.main_character = Group() self.main_character.add(actor) @property def protagonist(self): sprites = self.main_character.sprites() return sprites[0] if sprites else None @staticmethod def _touch(actor1, actor2): if actor1 is actor2: return False return actor1.rect.colliderect(actor2.rect) def update(self): if self.inside_cut: try: return self.draw_cut() except CutExit: self.leave_cut() try: self.scene.update() for actor in self.all_actors: if actor.off_screen_update or self.is_position_on_screen(actor.pos): actor.update() for collision in pygame.sprite.spritecollide(actor, self.all_actors, False, collided=self._touch): actor.on_over(collision) if isinstance(self.scene[actor.pos], GameObject): self.scene[actor.pos].on_over(actor) self.draw() except SoftReset: pass def draw(self): self.background() self.draw_actors() self.display_messages() scale = property(lambda self: self.scene.blocksize) # These hold the on-screen size of the game-scene in blocks blocks_x = property(lambda self: self.width // self.scale) blocks_y = property(lambda self: self.height // self.scale) def iter_blocks(self): for x in range(self.blocks_x): for y in range(self.blocks_y): yield x, y def background(self): if self.scene.overlay_image: self.overlay_background() else: self.block_background() self.old_left = self.scene.left self.old_top = self.scene.top self.force_redraw = False def block_background(self): scene = self.scene scale = self.scale for x, y in self.iter_blocks(): obj = scene[x + scene.left, y + scene.top] image = obj.image if hasattr(obj, "image") else obj self._draw_tile_at((x,y), image, self.force_redraw) def _draw_tile_at(self, pos, image, force=False): x, y = pos scale = self.scale if not force and self.old_tiles.get(pos, None) is image and not self.dirty_tiles.get(pos, False): return if isinstance(image, Color): pygame.draw.rect(self.screen, image, (x * scale, y * scale, scale, scale)) else: # image self.screen.blit(image, (x * scale, y * scale)) self.old_tiles[pos] = image self.dirty_tiles.pop(pos, False) def overlay_background(self): scene = self.scene if not self.force_redraw and self.old_left == scene.left and self.old_top == scene.top: return self._draw_overlay_tiles() pixel_left = scene.left * scene.blocksize pixel_top = scene.top * scene.blocksize self.screen.blit(scene.overlay_image, (0, 0), area=(pixel_left, pixel_top, self.width, self.height)) def _draw_overlay_tiles(self): scene = self.scene blocksize = scene.blocksize for pos, dirty in list(self.dirty_tiles.items()): if not dirty: continue pixel_left = (scene.left + pos[0]) * blocksize pixel_top = (scene.top + pos[1]) * blocksize local_left = blocksize * pos[0] local_top = blocksize * pos[1] self.screen.blit(scene.overlay_image, (local_left, local_top), area=(pixel_left, pixel_top, blocksize, blocksize)) self.dirty_tiles.pop(pos) def is_position_on_screen(self, pos): return (self.scene.left <= pos[0] < self.scene.left + self.blocks_x and self.scene.top <= pos[1] < self.scene.top + self.blocks_y) def to_screen(self, pos): return V((pos[0] - self.scene.left, pos[1] - self.scene.top)) def draw_actors(self): scale = self.scene.blocksize scene = self.scene self.actor_positions = {} for actor in self.all_actors: self.actor_positions[actor.pos] = actor if not self.is_position_on_screen(actor.pos): continue if not actor.image: continue x, y = pos = self.to_screen(actor.pos) if actor.speed: # import ipdb; ipdb.set_trace() old_pos = self.to_screen(actor.old_pos) ipos = old_pos + (pos - old_pos) * actor.speed * min((actor.tick - actor.move_direction_count), actor.base_move_rate) x, y = ipos self.dirty_tiles[old_pos] = True self.dirty_tiles[pos] = True self.dirty_tiles[V((old_pos.x, pos.y))] = True self.dirty_tiles[V((pos.x, old_pos.y))] = True else: self.dirty_tiles[pos] = True self.screen.blit(actor.image, (x * scale, y * scale)) def display_messages(self): scale = self.scene.blocksize for message in self.messages: if not self.is_position_on_screen(message.owner.pos): continue image = message.render() # Initially all message swill pop bellow the actors, at half-block-lenght to left # TODO: enhance message block display heuristics position = self.to_screen(message.owner.pos) x = position[0] + 0.5 y = position[1] + 1 self.screen.blit(image, (int(x * scale), y * scale)) for j in range(0, (image.get_width() // scale) + 2): for k in range(0, (image.get_height() // scale) + 1): self.dirty_tiles[int(x) + j, y + k] = True def __getitem__(self, pos): """ Position is relative to the scene """ if pos in self.actor_positions: return self.actor_positions[pos] return self.scene[pos] def quit(self): pygame.quit()
class SpaceGame(Microgame): def __init__(self): Microgame.__init__(self) # TODO: Initialization code here self.count = 0 self.spaceship = Spaceship() self.bg = Background() self.planet = Planet() self.monster = Group(Monster()) self.earth = Group(EarthExp()) self.background = Group(self.bg) self.sprites = Group(self.planet, self.spaceship) self.is_win = False self.is_lose = False def generate_asteroid(self): if self.count == 10: if randint(0,1) == 0: self.sprites.add(Asteroid(-10, randint(0, locals.HEIGHT - 400), 1)) else: self.sprites.add(Asteroid(locals.WIDTH + 10, randint(0, locals.HEIGHT - 400), -1)) self.count = 0 else: self.count += 1 def start(self): # TODO: Startup code here music.load(join("games","space","music","space_song.ogg")) music.play() def stop(self): # TODO: Clean-up code here music.stop() def update(self, events): # TODO: Update code here self.background.update() self.sprites.update() #Make asteroids self.generate_asteroid() #Check if spaceship hits sides of screen x_ship_left, _ = self.spaceship.rect.bottomleft x_ship_right, _ = self.spaceship.rect.bottomright if x_ship_left <= 0: self.spaceship.x_velocity = 0 elif x_ship_right >= locals.WIDTH - 14: self.spaceship.x_velocity = 0 #Check if spaceship hits top/bottom of screen sectioned to movement _, y_ship_top = self.spaceship.rect.topleft _, y_ship_bottom = self.spaceship.rect.bottomleft if y_ship_top <= locals.HEIGHT - 300: self.spaceship.y_velocity = 0 elif y_ship_bottom >= locals.HEIGHT - 20: self.spaceship.y_velocity = 0 #Process user input for event in events: if event.type == KEYDOWN and event.key == K_LEFT: if x_ship_left > 0: self.spaceship.x_velocity -= VELOCITY_INC elif event.type == KEYUP and event.key == K_LEFT: self.spaceship.x_velocity = 0 elif event.type == KEYDOWN and event.key == K_RIGHT: if x_ship_right < locals.WIDTH - 14: self.spaceship.x_velocity += VELOCITY_INC elif event.type == KEYUP and event.key == K_RIGHT: self.spaceship.x_velocity = 0 elif event.type == KEYDOWN and event.key == K_UP: if y_ship_top > locals.HEIGHT - 300: self.spaceship.y_velocity -= VELOCITY_INC elif event.type == KEYUP and event.key == K_UP: self.spaceship.y_velocity = 0 elif event.type == KEYDOWN and event.key == K_DOWN: if y_ship_bottom < locals.HEIGHT - 20: self.spaceship.y_velocity += VELOCITY_INC elif event.type == KEYUP and event.key == K_DOWN: self.spaceship.y_velocity = 0 #music.load(join("games","space","music","Powerup7.wav")) #music.play() #Make win when spaceship hits planet if self.planet.rect.colliderect(self.spaceship.rect): sound_planet = pygame.mixer.Sound(join("games","space","music","Powerup.wav")) sound_planet.play() self.is_win = True for each in self.sprites.sprites(): if isinstance(each, Asteroid): if each.rect.colliderect(self.spaceship.rect): sound_asteroid = pygame.mixer.Sound(join("games","space","music","Explosion.wav")) sound_asteroid.play() self.is_lose = True #Creates win scree if self.is_win: self.sprites.empty() self.background.empty() self.sprites.add(Monster()) #Creates lose screen elif self.is_lose: self.sprites.empty() self.background.empty() self.sprites.add(EarthExp()) def render(self, surface): # TODO: Rendering code here surface.fill(Color(0, 0, 0)) self.background.draw(surface) self.sprites.draw(surface) def get_timelimit(self): # TODO: Return the time limit of this game (in seconds, 0 <= s <= 15) #raise NotImplementedError("get_timelimit") return 15
class Main(object): """ creates and recieves input from the GUI """ SCREEN_SIZE = 800,600 FPS = 30 def __init__(self): """ no gui stuff yet, finishing the core components """ self.ROOT_DIR = os.path.dirname(sys.argv[0]) self.IMG_DIR = os.path.join(self.ROOT_DIR, "images") self.DATA_DIR = os.path.join(self.ROOT_DIR, "database") self.dbm = DataBaseManager(self.DATA_DIR) pygame.init() pygame.font.init() self.MAIN_SCREEN = pygame.display.set_mode(self.SCREEN_SIZE) self.MAIN_SCREEN_RECT = self.MAIN_SCREEN.get_rect() self.openingImage,self.openingImageRect = loadImage(self.IMG_DIR, "GrocerySpy.jpg") self.MAIN_SCREEN.blit(self.openingImage, (self.MAIN_SCREEN_RECT.centerx - self.openingImageRect.width /2, self.MAIN_SCREEN_RECT.centery - self.openingImageRect.height /2)) ## make button here startButton = Button(self.IMG_DIR, "textButton", (300,475), "menu", -1) startButton.addText("Start Here") # add that button to the list self.buttonGroup = Group(startButton) self.windowGroup = Group() self.state = "prestart" self.stateChanged = False # set key repeats for scrolling windows pygame.key.set_repeat(20, 20) self.groceryList = GroceryList() # variable for storing the state of the browseAll window if it is left self.toggledRecipeNames = [] self.controlHeld = False self.pasteDelayReset = 1000 self.pasteDelay = self.pasteDelayReset def run(self): done = False while not done: ## input loop for event in pygame.event.get(): if event.type == QUIT: done = True elif event.type == KEYDOWN and event.key == K_ESCAPE: done = True ## right click anything to have a pop up window # appear at the cursor with more information about the thing elif event.type == MOUSEBUTTONDOWN and event.button == 1: self.handleLeftMouseClick(pygame.mouse.get_pos()) ## arrow keys elif event.type == KEYDOWN and event.key == K_DOWN: self.attemptScroll(-3) elif event.type == KEYDOWN and event.key == K_UP: self.attemptScroll(3) elif event.type == KEYDOWN and (event.key == K_RCTRL or event.key == K_LCTRL): self.controlHeld = True elif event.type == KEYUP and (event.key == K_RCTRL or event.key == K_LCTRL): self.controlHeld = False elif event.type == KEYDOWN and event.key == K_v: if self.controlHeld: if self.pasteDelay < 10: self.doPaste() self.pasteDelay = self.pasteDelayReset ## end input if self.pasteDelay > 0: self.pasteDelay -= 1 ## change screen if self.stateChanged: ## clear everything on the screen first self.buttonGroup.empty() self.windowGroup.empty() self.MAIN_SCREEN.fill((0,0,0)) self.stateChanged = False if self.state == "menu": self.createMenu() elif self.state == "browseAll": self.setUpViewAll() elif self.state == "viewGroceryList": self.setUpViewGroceryList() elif self.state == "addRecipe": #print "here" self.setUpRecipeAdder() elif self.state == "search": self.setUpSearchTextBox() elif self.state == "deleteRecipe": self.setUpDelete() elif self.state == "exit": done = True ## do stuff to update the new state # after updates, draw self.buttonGroup.draw(self.MAIN_SCREEN) self.windowGroup.draw(self.MAIN_SCREEN) pygame.display.flip() pygame.quit() def setUpViewAll(self): x,y = self.SCREEN_SIZE x-=100 viewAllWindow = ScrollableWindow(self.IMG_DIR, (x,y),self.SCREEN_SIZE, "recipeViewer") viewAllWindow.addText(self.dbm.getAllRecipes()) #viewAllWindow.addText(self.dbm.getRandomRecipe()) viewAllWindow.updateState(self.toggledRecipeNames) self.windowGroup.add(viewAllWindow) backButton = Button(self.IMG_DIR, "backButton", (705,30), "menu", -1) self.buttonGroup.add(backButton) ## in one command, we call getAllRecipes() on the DBM, returning # a string list of all the names, and pass that to the # scrollable window to add that text to the thing # this returns the expandButtons for each row, which we add # to the buttonGroup def setUpDelete(self): x,y = self.SCREEN_SIZE x-=100 viewAllWindow = ScrollableWindow(self.IMG_DIR, (x,y),self.SCREEN_SIZE, "recipeDeleter") viewAllWindow.addText(self.dbm.getAllRecipes()) self.windowGroup.add(viewAllWindow) backButton = Button(self.IMG_DIR, "backButton", (705,30), "menu", -1) self.buttonGroup.add(backButton) def setUpViewGroceryList(self): x,y = self.SCREEN_SIZE x-=100 viewAllWindow = ScrollableWindow(self.IMG_DIR, (x,y),self.SCREEN_SIZE, "groceryListViewer") self.windowGroup.add(viewAllWindow) backButton = Button(self.IMG_DIR, "backButton", (705,30), "menu", -1) self.buttonGroup.add(backButton) viewAllWindow.addGroceryList(self.groceryList.getAllIngredients()) writeDesktopButton = Button(self.IMG_DIR, "writeToDesktop", (705,80), "writeToDesktop", -1) self.buttonGroup.add(writeDesktopButton) def setUpRecipeAdder(self): ingParser = IngredientParser()#self.dbm.loadParserDataFields()) recipeAdderWindow = RecipeReciever("addRecipePage",self.IMG_DIR, ingParser) self.windowGroup.add(recipeAdderWindow) backButton = Button(self.IMG_DIR, "backButton", (705,30), "menu", -1) self.buttonGroup.add(backButton) """def setUpSearch(self): self.windowGroup.add(TextBox( #def setUpSearchTextBox(self):""" def doPaste(self): if self.state == "addRecipe": (self.windowGroup.sprites())[0].recieveClipboardPaste(pyperclip.paste()) def attemptScroll(self, dy): for sprite in self.windowGroup.sprites(): sprite.scroll(dy) def handleLeftMouseClick(self, xy): for button in self.buttonGroup.sprites(): if button.getRect().collidepoint(xy): ## stupid organization leads to hacky solutions... # in groceryList viewer, the writeToDesktop button must be stored in the main # class. So thats whats going on here, we call writeToDesktop # in the scrollable window and grab the grocery list there and send that to # dbm to write it to desktop if button.getIdentity() == "writeToDesktop": theString = self.windowGroup.sprites()[0].writeToDesktop() #print #print #print theString self.dbm.writeStringToDesktop(self.windowGroup.sprites()[0].writeToDesktop(), "Grocery List") self.state = "menu" self.stateChanged = True #print "got here!" return ## we want to store the state of the stuff people are looking at # whether that is a grocery list they have increased or recipes they have added to cart # we call the "grabState()" method of the scrollableWindow to get the information #### keep in mind, this is the previous state # so if self.state == "browseAll" it means we are coming from browseAll state # to the menu if self.state == "browseAll": ## this one is tricky. We need to store a list of toggled rows, and then # if the user goes back to the viewAllBrowser we need to call "updateState()" # with this list, to ensure those buttons are toggled to reflect that they are # still in the groceryList # keep in mind this is a list of the names of the recipes that are already added # so we will need to search for them in "updateState()" allWindows = self.windowGroup.sprites() if allWindows: self.toggledRecipeNames = allWindows[0].grabState() elif self.state == "viewGroceryList": ## this one is simple, we just grabState() and store the returns in self.groceryList # all the changes the user has made will be in the new list # and new changes will happen to that list allWindows = self.windowGroup.sprites() if allWindows: self.groceryList.empty() self.groceryList.addIngredientList(allWindows[0].grabState()) self.state = button.getIdentity() self.stateChanged = True command = None if self.state == "browseAll" or self.state == "deleteRecipe": for scrollableWindow in self.windowGroup.sprites(): if scrollableWindow.getRect().collidepoint(xy): command = scrollableWindow.isClicked(xy) break if not command == None: ## command is a string, meaning there is a change of state # from the button press #print "command recieved!" #print " ", command if isinstance(command, str): self.state = command self.stateChanged = True #print "this thing" else: if len(command) == 2: #print "entered here" #print "command[0]:", command[0] if command[0] == "expand": recipeInfo = self.dbm.loadRecipe(command[1]).toReadableString() scrollableWindow.addTextBlock(command[1], recipeInfo) elif command[0] == "addToGroceryList": self.groceryList.addRecipe(self.dbm.loadRecipe(command[1])) elif command[0] == "removeFromGroceryList": self.groceryList.removeRecipe(self.dbm.loadRecipe(command[1])) elif command[0] == "writeToDesktop": #print "got into this" self.dbm.writeRecipeToDesktop(command[1]) if command[0] == "delete": #print "got here" self.dbm.deleteRecipe(command[1]) elif self.state == "menu" or self.state=="prestart": for sprite in self.buttonGroup.sprites(): if sprite.rect.collidepoint(xy): parseID = sprite.getIdentity().split() # no extra info, just an ID for the new state # if this is not true there is something wrong if len(parseID) == 1: spriteID = parseID[0] if not spriteID == self.state: self.state = spriteID self.stateChanged = True else: raise GUIError("button gives too much data") elif self.state == "addRecipe": for recipeReciever in self.windowGroup.sprites(): recipeData = recipeReciever.isClicked(xy) if not recipeData == None: #for k in recipeData.keys(): #print k, recipeData[k] self.dbm.addRecipeToDataBase(Recipe.fromDictionary(recipeData)) self.state = "menu" self.stateChanged = True elif self.state == "viewGroceryList": for scrollableWindow in self.windowGroup.sprites(): command = scrollableWindow.isClicked(xy) elif self.state == "search": ## search has 2 states, the first is a text box where the user # enters what the search ingredient is # the second the window where the results are displayed # we determine which state by what is in self.windowGroup.sprites() # a TextBox is the first state, a ScrollableWindow is the second for sprite in self.windowGroup.sprites(): pass#command = sprite.isClicked def createMenu(self): browseButton = Button(self.IMG_DIR, "textButton", (10,75), "browseAll", -1) browseButton.addText("Browse All") self.buttonGroup.add(browseButton) #searchButton = Button(self.IMG_DIR, "textButton", (210,75), "search", -1) #searchButton.addText("Search") #self.buttonGroup.add(searchButton) addRecipeButton = Button(self.IMG_DIR, "textButton", (410,75), "addRecipe", -1) addRecipeButton.addText("Add Recipe") self.buttonGroup.add(addRecipeButton) deleteRecipeButton = Button(self.IMG_DIR, "textButton", (10,275), "deleteRecipe", -1) deleteRecipeButton.addText("Delete Recipe") self.buttonGroup.add(deleteRecipeButton) groceryListButton = Button(self.IMG_DIR, "textButton", (210,275), "viewGroceryList", -1) groceryListButton.addText("View Cart") self.buttonGroup.add(groceryListButton) exitButton = Button(self.IMG_DIR, "textButton", (410, 275), "exit", -1) exitButton.addText("Exit") self.buttonGroup.add(exitButton)