def __init__(self): # Define all game state variables self.welcome_screen = WelcomeScreen() self.game_screen = GameScreen() self.game_over_screen = GameOverScreen() self.difficulty = Difficulty(self.setOptions) self.points = 0 self.done = False self.alert_loss = False self.settings = Settings() self.settings.set('hTime', 0.3) # Define all the Curses stuff curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) self.screen = curses.newwin(0, 0) self.screen.keypad(1) self.screen.nodelay(1) curses.noecho() curses.cbreak() curses.curs_set(0)
def __init__(self): '''init the game screen''' pygame.init() # 游戏设置 self.settings = Settings() # 屏幕 self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() # 难度选项按钮 self.difficulty = Difficulty(self) self.gaming = False self._create_fleet() # 标题设置 pygame.display.set_caption("Alien Invasion") self.stats = GameStats(self) self.play_button = Button(self, "Play") self.sb = Scoreboard(self) self.fire_sound = pygame.mixer.Sound("music/Explosion_Cannon_Fire_02.wav") self.ship_hit_sound = pygame.mixer.Sound("music/Explosion_With_Debris_01.wav") self.game_over_sound = pygame.mixer.Sound("music/Gameover.wav")
class Score(): def __init__(self, filename): self.time = datetime.datetime.now() self.filename = filename self.score = {"correct": 0, "count": 0} self.difficulty = Difficulty("difficultWords.json") def get_avgScore(self): with open(self.filename, "r") as pointsfile: pointsreader = csv.DictReader(pointsfile) totalGamesPlayed = 0 totalCount = [] totalCorrect = [] for line in pointsreader: totalGamesPlayed += 1 totalCount.append(int(line["wordCount"])) totalCorrect.append(int(line["correct"])) return str( math.ceil((sum(totalCorrect) + self.score["correct"]) / (sum(totalCount) + self.score["count"]) * 100)), str(totalGamesPlayed) def get_score(self): return str(safeDivision(self.score["correct"], self.score["count"])) def recordScore(self, msg, wordID): self.score["correct"] += self.difficulty.record(msg, wordID) self.score["count"] += 1 return f"{msg}\nYour new score is {self.get_score()}%" def save(self): if self.score["count"] != 0: with open(self.filename, "a") as csvfile: csvfile.write( f"{self.time}, {self.get_score()}, {self.score['count']}, {self.score['correct']}\n" )
class AlienInvasion: '''docstring''' def __init__(self): '''init the game screen''' pygame.init() # 游戏设置 self.settings = Settings() # 屏幕 self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() # 难度选项按钮 self.difficulty = Difficulty(self) self.gaming = False self._create_fleet() # 标题设置 pygame.display.set_caption("Alien Invasion") self.stats = GameStats(self) self.play_button = Button(self, "Play") self.sb = Scoreboard(self) self.fire_sound = pygame.mixer.Sound("music/Explosion_Cannon_Fire_02.wav") self.ship_hit_sound = pygame.mixer.Sound("music/Explosion_With_Debris_01.wav") self.game_over_sound = pygame.mixer.Sound("music/Gameover.wav") def run_game(self): '''start game''' while True: # 辅助方法, 注意命名以_开头 self._check_events() if self.stats.game_active and self.stats.mode_selection_active: self.ship.update() self._update_bullet() self._update_aliens() self._update_screen() def _check_events(self): # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: self._store_highscore() sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if not self.stats.game_active: self._check_play_button(mouse_pos) elif not self.stats.mode_selection_active: self._check_mode_button(mouse_pos) def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: # 向右移动, 增大center_x self.ship.moving_right = True elif event.key == pygame.K_LEFT: # 向左移动, 更新标记 self.ship.moving_left = True elif event.key == pygame.K_q: self._store_highscore() sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() elif event.key == pygame.K_p and not self.stats.game_active: self._start_game() self.settings.initialize_dynamic_settings() def _check_keyup_events(self, event): '''响应松开按键''' if event.key == pygame.K_RIGHT: # 松开右键, 取消标记 self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def _check_play_button(self, mouse_pos): '''在玩家单击play时开始新游戏''' if self.gaming or self.stats.mode_selection_active: return button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self.stats.game_active = True self.stats.mode_selection_active = False return def _check_mode_button(self, mouse_pos): if self.gaming or not self.stats.game_active: return mode_selected = "" mode_clicked = False for mode, mode_rect in self.difficulty.mode_rects.items(): mode_clicked = mode_rect.collidepoint(mouse_pos) # print(mode, mode_clicked) if mode_clicked and self.stats.game_active and not self.stats.mode_selection_active: mode_selected = mode self.stats.mode_selection_active = True break if self.stats.game_active and self.stats.mode_selection_active: self._start_game() self.settings.initialize_dynamic_settings(mode_selected) self.sb.prep_score() self.sb.prep_level() self.sb.prep_ships() def _start_game(self): self.stats.reset_stats() self.stats.game_active = True self.stats.mode_selection_active = True self.gaming = True self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() pygame.mouse.set_visible(False) def _update_screen(self): # 每一次循环都重新绘制 self.screen.fill(self.settings.bg_color) self.ship.blitme() # 画出子弹图形 for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) self.sb.show_score() if not self.stats.game_active and not self.stats.mode_selection_active: self.play_button.draw_button() elif self.stats.game_active and not self.stats.mode_selection_active: self.difficulty.draw_modes() # 让最近绘制的屏幕可见 pygame.display.flip() def _update_bullet(self): self.bullets.update() # 删除子弹 for bullet in self.bullets.copy(): #注意循环一个列表时必须保证其长度不变,所以需要对它的副本进行遍历 if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collisions() def _check_bullet_alien_collisions(self): collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: self.bullets.empty() self._create_fleet() self.settings.increase_speed() self.stats.level += 1 self.sb.prep_level() def _fire_bullet(self): if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) self.fire_sound.play(loops=0, maxtime=500) def _create_fleet(self): '''创建外星人群''' alien = Alien(self) alien_width, alien_height = alien.rect.size ship_height = self.ship.rect.height available_space_x = self.settings.screen_width - (2 * alien_width) available_space_y = self.settings.screen_height - \ (3 * alien_width) - ship_height number_rows = available_space_y // (2 * alien_height) number_aliens_x = available_space_x // (2 * alien_width) for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _create_alien(self, alien_number, row_number): '''创建一个外星人并放在当前行''' alien = Alien(self) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.y = alien_height + 2 * alien_height * row_number alien.rect.y = alien.y self.aliens.add(alien) def _check_fleet_edges(self): '''''' for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): '''''' for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _update_aliens(self): '''更新外星人群中所有外星人的位置''' self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom() def _ship_hit(self): if self.stats.ships_left > 0: self.stats.ships_left -= 1 self.sb.prep_ships() self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() self.ship_hit_sound.play(loops=0, maxtime=1000) sleep(0.5) else: self.stats.game_active = False self.stats.mode_selection_active = False self.gaming = False self.game_over_sound.play() pygame.mouse.set_visible(True) # print(self.stats.game_active, self.stats.mode_selection_active) def _check_aliens_bottom(self): screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: self._ship_hit() break def _store_highscore(self): with open("score.txt", 'w') as f: f.write(str(self.stats.high_score))
from pygame.time import Clock from menu import Menu from play import Play from fps import Fps from rank import Rank from difficulty import Difficulty import GVar window = Window(GVar.WIDTH, GVar.HEIGHT) window.set_title("Space Invaders") window.set_background_color((0, 0, 0)) keyboard = Keyboard() menu = Menu(window) play = Play(window, "./assets/lvl/level_1.txt") difficulty_menu = Difficulty(window) rank = Rank(window) clock = Clock() fps = Fps(window) window.update() while GVar.STATE != 4: window.set_background_color((0, 0, 0)) if keyboard.key_pressed("esc"): GVar.STATE = 0 play.__init__(window, "./assets/lvl/level_1.txt") if GVar.STATE == 0: menu.run() if GVar.STATE == 1: if GVar.DIFC_CHOSEN == True: play.__init__(window, "./assets/lvl/level_1.txt")
# https://www.google.com/fbx?fbx=minesweeper - target website from time import sleep from difficulty import Difficulty from board import Board from ai import AI # let user switch to the page sleep(2) diff = Difficulty().get_diff() # width, height = 1440, 900 # changable board_size = {'hard': (20, 24), 'medium': (14, 18), 'easy': (8, 10)} piece_length = {'hard': 25, 'medium': 30, 'easy': 45} bombs_number = {'hard': 99, 'medium': 40, 'easy': 10} # change this starting_position = (0, 160) board = Board(board_size[diff], piece_length[diff], bombs_number[diff], starting_position) AI(board).play()
counter_starting_value = 3 counter = counter_starting_value ### Game Script Starting Point ### screen = pygame.display.set_mode(settings.SIZE) font = pygame.font.Font(None, 36) clock = pygame.time.Clock() clock.tick(60) pygame.time.set_timer(pygame.USEREVENT, 1000) hf.game_bootloader() hf.load_splash_screen(screen, font) difficulty = Difficulty(screen, font, counter_starting_value) savefile = Savefile(settings.SAVE_LOCATION[difficulty.mode]) hf.ready_to_start(screen, font) counter = counter_starting_value hf.start_music() current_letter = Letter() current_letter.randomize_attributes(difficulty.letters) backGround = BackGround(settings.BACKGROUND_IMAGE, settings.BACKGROUND_IMAGE_STARTING_POINT) while True: for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
class App(object): def __init__(self): # Define all game state variables self.welcome_screen = WelcomeScreen() self.game_screen = GameScreen() self.game_over_screen = GameOverScreen() self.difficulty = Difficulty(self.setOptions) self.points = 0 self.done = False self.alert_loss = False self.settings = Settings() self.settings.set('hTime', 0.3) # Define all the Curses stuff curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) self.screen = curses.newwin(0, 0) self.screen.keypad(1) self.screen.nodelay(1) curses.noecho() curses.cbreak() curses.curs_set(0) def setOptions(self): self.settings.set('hTime', self.difficulty.getHTime()) self.settings.set('obsWidth',10) self.settings.set('obsHoleHeigth', 7) self.settings.set('obsSpacing',15) self.game_screen.initGame(self.settings) def deinit(self): self.screen.nodelay(0) self.screen.keypad(0) curses.nocbreak() curses.echo() curses.curs_set(1) curses.endwin() sys.exit(1) # Event Loop Functions def events(self): # Global Events key = self.screen.getch() if key == K_ESCAPE or key is K_Q: self.deinit() # State-depent events if not self.difficulty: self.difficulty.set(self.welcome_screen.events(key)) else: self.game_screen.events(key) def update(self): if self.difficulty and not self.done: self.done, self.points = self.game_screen.update(self.screen, self.settings) if self.done: # Alert Loss Once if not self.alert_loss: curses.flash() curses.beep() curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) self.alert_loss = True def render(self): self.screen.erase() # Render Current State if not self.difficulty: self.welcome_screen.screen(self.screen) else: self.game_screen.screen(self.screen, self.settings) if self.done: self.game_over_screen.screen(self.screen, self.points) # Refresh and Loop self.screen.refresh() time.sleep(self.settings.get('hTime')) def loop(self): while True: self.events() self.update() self.render()
def __init__(self): self.game_view = None self.difficulty = Difficulty() self.height = self.difficulty.height() self.width = self.difficulty.width()
class Ui: def __init__(self): self.game_view = None self.difficulty = Difficulty() self.height = self.difficulty.height() self.width = self.difficulty.width() def start(self): self.game_view = ViewGrid(self.difficulty) self.play_game() def play_game(self): print() print("miinaharava") print(f"size of grid: {self.width} x {self.height}") self.main_loop() def print_game_viewgrid(self): first_line = " |" for i in range(self.width): first_line += f" {i} |" print(first_line) line = "---" + "----" * self.width print(line) for i in range(self.height): row = f"{i} |" for j in range(self.width): content = self.game_view.coordinates(i, j) row += f" {content} |" print(row) print(line) def main_loop(self): while True: print() print("1: new game") print("0: quit") command = input("command: ") if command == "0": break if command == "1": self.game_loop() def ask_coordinates(self): try: row = int(input("give an index of a row: ")) seg = int(input("give an index of a column: ")) return (row, seg) except TypeError: print("invalid command") def game_loop(self): while True: print() print("flags left:", self.game_view.give_flags()) print("unopened squares:", self.game_view.give_unopened()) print() self.print_game_viewgrid() if self.status() is False: break print() print("1: open a square") print("2: place/displace a flag") print("0: exit") command = input("command: ") if command == "0": return coord_x, coord_y = self.ask_coordinates() if command == "1": self.game_view.push_left_button(coord_x, coord_y) if command == "2": self.game_view.push_right_button(coord_x, coord_y) def status(self): status = self.game_view.give_game_status() if status == "game_over": print("game over") return False if status == "victory": print("victory!") return False return True
def __init__(self, filename): self.time = datetime.datetime.now() self.filename = filename self.score = {"correct": 0, "count": 0} self.difficulty = Difficulty("difficultWords.json")