def main(): """Main method containing initialization and game loop""" pygame.init() Screen.display_surface.fill(Color.WHITE) pygame.display.set_caption('PyRPG') #Music starts pygame.mixer.init() Music.play_music(Music.background_music, True, 0.4) #Draw the main menu Menu.main_menu() replay = True #Main Game loop while replay: game_object = Game() game_object.game_setup() events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_y: pass elif event.key == pygame.K_n: replay = False break
def play_game(): field = Field(field_size) players = (PlayerRandom(0, field_size), PlayerRandom(1, field_size)) game = Game(field, players, stdout=False) _, x, y = game.start() return x, y
def game(): player1 = request.form["player1"] player1_gesture = request.form["player1gesture"] new_player1 = Player(player1, player1_gesture) player2 = request.form["player2"] player2_gesture = request.form["player2gesture"] new_player2 = Player(player2, player2_gesture) rock_paper_scissors = Game(new_player1, new_player2) return render_template('result.html', title='Game Result', result=rock_paper_scissors.play_game( new_player1, new_player2))
class TestGame(unittest.TestCase): def setUp(self): self.player_1 = Player("Matt Lucas", "paper") self.player_2 = Player("Bruce Lee", "scissors") self.player_3 = Player("Steve Buscemi", "paper") self.game = Game(self.player_1, self.player_2) self.game_2 = Game(self.player_1, self.player_3) def test_playing_rps(self): self.assertEqual("Bruce Lee wins by playing scissors", self.game.play_rps()) def test_matching_choice_returns_none(self): self.assertIsNone(self.game_2.play_rps())
def play_game(): """ ゲームを開始する。 :param players: 使用したいプレイヤープログラムを格納する。 :return: """ field = Field(field_size) players = (PlayerRandom(0, field_size), PlayerRandom(1, field_size)) game = Game(field, players) winner, _, _ = game.start() return winner
async def debugload(self, ctx): """ Tells xyzzy to load a [filename] from the test folder in the current channel. The game will not count towards any statistics. """ # Don't do DMs kids. if ctx.is_dm(): return await ctx.send("```accesslog\nSorry, but games cannot be played in DMs. Please try again in a server.```") if ctx.msg.channel.id in self.xyzzy.channels: return await ctx.send('```accesslog\nSorry, but #{} is currently playing "{}". Please try again after the game has finished.\n```'.format(ctx.msg.channel.name, self.xyzzy.channels[ctx.msg.channel.id].game.name)) if not ctx.args: return await ctx.send("```diff\n-Please provide a game to play.\n```") file_dir = "./tests/" + ctx.raw if not os.path.isfile(file_dir): return await ctx.send("```diff\n-File not found.\n```") print("Now loading test file {} for #{} (Server: {})".format(ctx.raw, ctx.msg.channel.name, ctx.msg.guild.name)) chan = GameChannel(ctx.msg, Game(ctx.raw, {"path":file_dir, "debug":True})) self.xyzzy.channels[ctx.msg.channel.id] = chan await ctx.send('```py\nLoaded "{}"\n```'.format(ctx.raw)) await chan.init_process() await chan.game_loop() if ctx.msg.channel.id in self.xyzzy.channels: del self.xyzzy.channels[ctx.msg.channel.id]
def parse_game(self, game, include_completed=True) -> (Game, GameStatus): game_details = game.find(class_='status-detail').text if not game_details: return None, GameStatus.unknown elif game_details.startswith("End of"): game_details = game_details.replace("End of", "0:00 -") elif game_details.startswith("Start of"): game_details = game_details.replace("Start of", "12:00 -") elif game_details == "Halftime": game_details = "0:00 - 2nd" elif game_details == "Postponed": return None, GameStatus.postponed elif game_details == "Final": if not include_completed: return None, GameStatus.ended game_details = "0:00 - 4th" game_details = game_details.split(" - ") time_left = game_details[0] quarter = game_details[1] teams = [self.parse_team(team) for team in self.get_teams(game)] return Game({ "teams": teams, "quarter": quarter, "time_left": time_left }), GameStatus.running
def play_game(): """ Starts tetris game in terminal. """ board_instance = Board(20) current_piece = Piece(board_instance) board_instance.print(current_piece) game = Game() player_move = input() while (game.status): msg = move.make_move(player_move, board_instance, current_piece) board_instance.print(current_piece, msg) game.is_over(board_instance, current_piece) player_move = input() print("GAME OVER!")
def main(): size = c.SCREEN_SIZE board = Board(*size) screen = pygame.display.set_mode(size) # load bg block_bg = pygame.transform.scale( pygame.image.load(os.path.join('static', 'block_bg.png')), board.get_block_size() ) myfont = pygame.font.SysFont("monospace", 16) end_game = EndGame(myfont, c.WHITE, size, screen, board) game = Game(board, pygame, screen, end_game, block_bg, myfont) screen.fill(c.GRAY) while True: game.flow()
def new_game(self): """ Create a new game instance. @return host_id: the unique ID of the game's host. @return game_id: the unique ID of the game. """ new_game = Game(uuid4().hex, self._generate_game_id()) self.games.add(new_game) return new_game.host_id, new_game.game_id
def btn_run_clicked(self): maze = self.windowSt.mazes[self.cb_mazes.currentIndex()]['mask'] algorithm = self.windowSt.algorithms[ self.cb_algorithms.currentIndex()]['name'] heuristic = self.cb_heuristic.currentText() pacman_speed = self.sb_pacman_speed.value() feed_density = self.sb_feed_density.value() / 100. game_params = GameParameters(maze, algorithm, heuristic, pacman_speed, feed_density) game = Game(game_params) path = game.solve() # path = [] game_app = GameApp( game.maze, self.windowSt.mazes[self.cb_mazes.currentIndex()]['path'], path, self.chb_path.isChecked(), pacman_speed, f"{self.windowSt.algorithms[self.cb_algorithms.currentIndex()]['title']},{heuristic}", self.windowSt.icon, self.windowSt.title, self.img_maze.rect().width(), self.img_maze.rect().height()) game_app.run()
def __init__(self, logAll=True): # конструктор self.logAll = logAll self.yandexStuff = YandexStuff() self.loop = True # создаем модули self.radio = Radio() self.anekdot = Anekdot() self.game = Game() self.weather = Weather() self.citygame = city_game() self.recognizer = speech.Recognizer() self.iamToken, self.iamTokenExpires = self.yandexStuff.create_token() self.play('audio/powerup.wav') time.sleep(0.5) # todo uncomment self.play('audio/jarvisHi.wav') time.sleep(0.5) self.playLowBeep()
async def on_ready(): """On ready event.""" print(f'{BOT.user} has connected\n') total_user = 0 for guild in BOT.guilds: print( f'{guild.name:20} by + {str(guild.owner):20} {len(guild.members)} users' ) if guild.name != "Discord Bot List": total_user += len(guild.members) GAMES[guild.id] = load_file_to_game(guild.id) if GAMES[guild.id] is not None: GAMES[guild.id].clear_undecided_reacted() # print(f"The file from data/{guild.id}.data was correctly loaded.") else: GAMES[guild.id] = Game(guild.id) print(f'\n\n{total_user} users in total, with {len(BOT.guilds)} guilds') await BOT.change_presence(activity=discord.Game( name=f"{len(BOT.guilds)} guilds with {total_user} users"))
def test_client_commands(): """Check the list of commands and actual methods in the Game class align""" methods = [ m[0] for m in inspect.getmembers(Game("", ""), predicate=inspect.ismethod) ] host_commands = [m for m in methods if m[0:2] == "hc"] player_commands = [m for m in methods if m[0:2] == "pc"] assert all([ hc in WebsocketHandler.host_commands.values() for hc in host_commands ]) assert all([ pc in WebsocketHandler.player_commands.values() for pc in player_commands ]) assert all([ hc in host_commands for hc in WebsocketHandler.host_commands.values() ]) assert all([ pc in player_commands for pc in WebsocketHandler.player_commands.values() ])
from modules.game import Game Game().play()
#!/usr/bin/env python # encoding: utf-8 import pygame from modules.game import Game pygame.init() # game window pygame.display.set_caption("MacGyver Escape") pygame.display.set_icon(pygame.image.load('assets/MacGyver.png')) screen = pygame.display.set_mode((600, 600)) # load the game game = Game() # loop running running = True while running: screen.blit(game.guard.image, game.guard.rect) screen.blit(game.ether.image, game.ether.rect) for x in range(0, 15): for y in range(0, 15): objectToDisplay = my_level[x][y] if objectToDisplay == "x": pygame.rect.draw(Wall) # update screen pygame.display.flip()
from modules.scale import Scale from modules.window import Window from modules.game import Game from modules.thread import Thread # Set textures src src = 'textures/texture.png' # Set textures coord textures = {'GRASS': [(1, 0), (0, 1), (0, 0)], 'SAND': [(1, 1), (1, 1), (1, 1)], 'BRICK': [(2, 0), (2, 0), (2, 0)], 'STONE': [(2, 1), (2, 1), (2, 1)]} # Music Thread(lambda:Audio('audios/background.wav').play(recycle=True)) # Window Window(fullscreen=False, caption='MiniCraft', model=Game(Scale(src, textures))) # Global settings glClearColor(0.5, 0.69, 1.0, 1) glEnable(GL_CULL_FACE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # Setup fog glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 20.0) glFogf(GL_FOG_END, 60.0)
def __init__(self): print(ConsoleColours.HEADER + "Welcome to Xyzzy, v2.0." + ConsoleColours.END) if not os.path.exists("./saves/"): print('Creating saves directory at "./saves/"') os.makedirs("./saves/") self.config = {} self.timestamp = 0 print('Reading "options.cfg".') parser = ConfigParser() with open("./options.cfg") as cfg_data: parser.read_string(cfg_data.read()) self.config = dict(parser._sections["Config"]) for opt, msg in REQUIRED_CONFIG_OPTIONS.items(): if opt not in self.config: raise Exception(msg) else: self.__setattr__(opt, self.config[opt]) for opt in OPTIONAL_CONFIG_OPTIONS: if opt in self.config: self.__setattr__(opt, self.config[opt]) else: self.__setattr__(opt, None) if self.home_channel_id: self.home_channel_id = int(self.home_channel_id) self.owner_ids = [] if not self.owner_ids else [ x.strip() for x in self.owner_ids.split(",") ] self.home_channel = None self.gist_data_cache = None self.gist_game_cache = None print("Reading game database...") with open("./games.json") as games: games = json.load(games) self.games = {} for name, data in games.items(): if not os.path.exists(data["path"]): print("Path for {} is invalid. Delisting.".format(name)) else: self.games[name] = Game(name, data) if not os.path.exists("./bot-data/"): print('Creating bot data directory at "./bot-data/"') os.makedirs("./bot-data/") if not os.path.exists("./save-cache/"): print('Creating save cache directory at "./save-cache/"') os.makedirs("./save-cache/") try: print("Loading user preferences...") with open("./bot-data/userprefs.json") as pref: self.user_preferences = json.load(pref) if "unprefixed" not in self.user_preferences: with open("./bot-data/userprefs.json", "w") as pref: print( ConsoleColours.OK_BLUE + 'Adding "unprefixed" array to user preferences file...' + ConsoleColours.END) json.dump({ **self.user_preferences, "unprefixed": [] }, pref) self.user_preferences["unprefixed"] = [] except FileNotFoundError: print( ConsoleColours.WARNING + "User preferences not found. Creating new user preferences file..." + ConsoleColours.END) with open("./bot-data/userprefs.json", "w") as pref: pref.write('{"version": 1, "backticks": [], "unprefixed": []}') self.user_preferences = { "version": 1, "backticks": [], "unprefixed": [] } try: print("Loading blocked user list...") with open("./bot-data/blocked_users.json") as blk: self.blocked_users = json.load(blk) except FileNotFoundError: print( ConsoleColours.WARNING + "Blocked user list not found. Creating new blocked user list..." + ConsoleColours.END) with open("./bot-data/blocked_users.json", "w") as blk: blk.write("{}") self.blocked_users = {} try: print("Loading server settings...") with open("./bot-data/server_settings.json") as srv: self.server_settings = json.load(srv) except FileNotFoundError: print( ConsoleColours.WARNING + "Server settings not found. Creating new server settings file.." + ConsoleColours.END) with open("./bot-data/server_settings.json", "w") as srv: srv.write("{}") self.server_settings = {} self.process = None self.thread = None self.queue = None self.channels = {} self.content_regex = re.compile(r"`{}.+`".format(self.invoker)) self.session = aiohttp.ClientSession() self.commands = Holder(self) if os.listdir("./saves"): print("Cleaning out saves directory after reboot.") for s in os.listdir("./saves"): shutil.rmtree("./saves/" + s) print(ConsoleColours.OK_GREEN + "Initialisation complete! Connecting to Discord..." + ConsoleColours.END) super().__init__()
def main(): game = Game() while game.running: game.currentMenu.displayMenu()
def main(): game = Game() # initialize the Game object human = Player() # initialize the Player object ai = AiPlayer() # initialize the AiPlayer object (player_data, ai_data, game_data, loaded) = game.load_game( ) # ask to load the previous game (load_game() returns a tuple of 4 elements) if loaded == True: # only load data if game.load_game() ran succesfully human.name = player_data['name'] human.wins = player_data['wins'] human.win_rate = player_data['win_rate'] ai.name = ai_data['name'] ai.wins = ai_data['wins'] ai.win_rate = ai_data['win_rate'] game.sessions = game_data['sessions'] print('Loaded succesfully') while (game.get_state() == True): # keep looping if the game state is True human.set_choice() # set human choice if human.choice not in game.options: # check the input and break the loop if the input is not what we want print('Error 1: Incorrect input') continue elif human.choice == 'exit': game.close() continue ai.set_choice() # set the ai choice print(f'{human.name} selected: {human.choice}' ) # display the human choice print(f'{ai.name} selected: {ai.choice}') # display the ai choice # compare the choices and display the winner print('------------------------') if ai.choice == human.choice: print('[Draw]') elif ai.choice == 'rock' and human.choice == 'scissors': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 elif ai.choice == 'paper' and human.choice == 'rock': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 elif ai.choice == 'scissors' and human.choice == 'paper': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 else: print(f'[{human.name} won]') human.wins += 1 # increment player win by 1 print('------------------------') game.sessions += 1 # track game sessions ai.win_rate.append(ai.wins / game.sessions) # track the ai win rate human.win_rate.append(human.wins / game.sessions) # track the human win rate print(f'SCORES ---- Humans: {human.wins} AI: {ai.wins}' ) # display the individual wins print(f'AI Win Rate: {ai.get_win_rate()}%') # display the ai win rate print(f'HUMAN Win Rate: {human.get_win_rate()}%' ) # display the human win rate # player, ai and game data is saved in dictionaries for the purpose of saving player_data = { "name": human.name, "wins": human.wins, "win_rate": human.win_rate } ai_data = {"name": ai.name, "wins": ai.wins, "win_rate": ai.win_rate} game_data = {"sessions": game.sessions} save_status = game.save_game(player_data, ai_data, game_data) # asks to save the game if save_status == True: # print a message if saved succesfully print('Saved game succesfully')
from modules.methods import init_window from modules.game import Game if __name__ == '__main__': init_window() Game().main_loop()
def setUp(self): self.player_1 = Player("Matt Lucas", "paper") self.player_2 = Player("Bruce Lee", "scissors") self.player_3 = Player("Steve Buscemi", "paper") self.game = Game(self.player_1, self.player_2) self.game_2 = Game(self.player_1, self.player_3)
async def on_message(message): guild = message.guild channel = message.channel async def get_game(ctx): game = None for i, o in enumerate(games): if o.guild.id == guild.id and o.channel.id == channel.id: game = games[i] if not game: insult = insult_generator.generate_insult() await message.channel.send( "There ain't no game, you {insult}".format(insult=insult)) return game if message.author == client.user: return if not message.content.startswith('.al '): return cmd = message.content[4:] if cmd.startswith('quote'): quote = get_quote() await message.channel.send(quote) return if cmd.startswith('cheer'): no_cheerz = "No cheerz be availables :cry:" await message.channel.send(no_cheerz) return if cmd.startswith("list cheer"): raise Exception("Not yet implemented.") if cmd.startswith("new cheer"): raise Exception("Not yet implemented.") if cmd.startswith("del cheer"): raise Exception("Not yet implemented.") if cmd.startswith("new game"): for game in games: if game.guild.id == guild.id and game.channel.id == channel.id: msg = "There is already a game in this channel (#{channel}). Please end the game before start a new one. You can use the `kill game` command to end a game.".format( channel=channel.name) await message.channel.send(msg) return new_game = Game(message.guild, message.channel) games.append(new_game) msg = "A new game has been created in #{channel}".format( channel=channel) await message.channel.send(msg) return if cmd.startswith("kill game"): for i, o in enumerate(games): if o.guild.id == guild.id and o.channel.id == channel.id: del games[i] break msg = "Game has been killed off. Are you happy now? :cry:" await message.channel.send(msg) return if cmd.startswith("join game"): game = await get_game(message) if not game: return name = message.author.name try: name = cmd.split("join game ", 1)[1] except: print("Player name not supplied") if game.get_player(message.author): msg = "You have already joined the game, you silly. :joy:" await message.channel.send(msg) return else: player = Player(game, message.author, name) game.players.append(player) msg = "Player {name} has joined the game! :fist:".format( name=player.name) await message.channel.send(msg) return if cmd.startswith("leave game"): game = await get_game(message) if not game: return if game.state == game_state["PLAYING"]: msg = "You cannot leave a game once it has started." await message.channel.send(msg) return player = game.get_player(message.author) if player: msg = "Player {name} has left the game! :door:".format( name=player.name) game.kick_player(player) await message.channel.send(msg) return else: msg = "You are not in the game, you whackadoodledoo!" await message.channel.send(msg) return if cmd.startswith("game status"): game = await get_game(message) if not game: return msg = game.get_game_status() if not msg: msg = "Game is fookin' empty mate. Nothing to see here..." await message.channel.send(msg) return if cmd.startswith("add enemy"): game = await get_game(message) if not game: return name = cmd.split("add enemy ", 1)[1] enemy = Enemy(game, name, 20, 5) game.players.append(enemy) msg = "An enemy {name} was added to the game! :japanese_goblin:".format( name=name) await message.channel.send(msg) return if cmd.startswith("start game"): game = await get_game(message) if not game: return if game.state == game_state["NEW"]: msg = "A new adventure begins... :drum:" await message.channel.send(msg) await game.start(message) elif game.state == game_state["PLAYING"]: msg = "The adventure is already ongoing, you fool! :dog:" await message.channel.send(msg) else: msg = "The adventure has ended already..." await message.channel.send(msg) return if cmd.startswith("init template"): game = await get_game(message) if not game: return name = cmd.split("init template ", 1)[1] await game.init_template(message, name) await message.channel.send( "Template {name} initialized. :white_check_mark: ".format( name=name)) return if cmd.startswith("attack"): game = await get_game(message) if not game: return name = cmd.split("attack ", 1)[1] player = game.get_player(message.author) await player.attack(message, name) return if cmd.startswith("insult"): game = await get_game(message) if not game: return name = cmd.split("insult ", 1)[1] message.channel.send('{name}, you {insult}.'.format( name=name, insult=insult_generator.generate_insult())) return if cmd.startswith("report status"): numbers = [1, 2, 3, 4, 5, 6, 7] chosen = random.choice(numbers) statuses = [ "{number}: Injured.".format(number=chosen), "{number}: Where are you?".format(number=chosen), "{number}: Low ammo.".format(number=chosen), "{author}: Oh no, #{number} is down".format( author=message.author.name, number=chosen) ] msg = random.choice(statuses) await message.channel.send(msg) return await message.channel.send( 'Not a valid command, {name}. You {insult}.'.format( name=message.author.name, insult=insult_generator.generate_insult()))
async def init_elo_by_anddy(self, ctx): """Init the bot in the server. Initialize the bot to be ready on a guild. This command creates every channel needed for the Bot to work. Can be used anywhere. Need to have Elo Admin role Read https://github.com/AnddyAnddy/discord-elo-bot/wiki/How-to-set-up """ guild = ctx.guild if not discord.utils.get(guild.roles, name="Elo Admin"): await guild.create_role( name="Elo Admin", # permissions=discord.Permissions.all_channel(), colour=discord.Colour(0xAA0000)) await ctx.send("Elo admin role created. Since I don't know the " \ "layout of your roles, I let you put this new role above "\ "normal users.") if not discord.utils.get(guild.roles, name="20 games double xp"): for elem in (100, 50, 20): await guild.create_role(name=f"{elem} games double xp", colour=discord.Colour(0x5AE78E)) await ctx.send("Premium roles created. Since I don't know the " \ "layout of your roles, I let you put this new role above "\ "normal users.") if not discord.utils.get(guild.categories, name='Elo by Anddy'): perms_secret_chan = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), discord.utils.get(guild.roles, name="Elo Admin"): discord.PermissionOverwrite(read_messages=True) } base_cat = await guild.create_category(name="Elo by Anddy") await guild.create_text_channel(name="Init", category=base_cat, overwrites=perms_secret_chan) await guild.create_text_channel(name="Moderators", category=base_cat, overwrites=perms_secret_chan) await guild.create_text_channel(name="Info_chat", category=base_cat) await guild.create_text_channel(name="Register", category=base_cat) await guild.create_text_channel(name="Submit", category=base_cat) # await guild.create_text_channel(name="Autosubmit", category=base_cat) await guild.create_text_channel(name="Game_announcement", category=base_cat) await guild.create_text_channel(name="Bans", category=base_cat) await guild.create_text_channel(name="announcements", category=base_cat) await guild.create_category(name="Solo elo") await guild.create_category(name="Teams elo") await ctx.send("Elo by Anddy created, init done, use !help !") if ctx.guild.id not in GAMES: GAMES[guild.id] = Game(guild.id)
def play_game(starter, num_players): ''' Starts the game. ''' game = Game(starter) if num_players == 1: game.ai = True while True: clear() game.print_board() print() # Computer's turn in one-player game if game.ai and game.turn == 2: print('it\'s computer\'s turn!') sleep(0.5) print('Thinking...') sleep(0.8) print('This is a brilliant move!') sleep(1) while True: if game.place_marker(randint(1, 9)) == 0: if game.has_winner(): clear() game.winner(ai=True) return if game.open_grids_available(): game.change_turn() else: clear() game.tie() return break # Two player game and human's turn in one-player game else: print(f'It\'s player {game.turn}\'s turn!') print('Press "i + enter" to show game instructions') print() try: grid = input('Place your marker (grid number 1 - 9): ') if grid == 'i' or grid == 'I': show_instructions() continue grid = int(grid) if (grid > 0) and (grid < 10): if game.place_marker(grid) == 0: if game.has_winner(): clear() game.winner() return if game.open_grids_available(): game.change_turn() else: clear() game.tie() return else: print('That grid is already taken!') sleep(0.5) else: raise ValueError except ValueError: print('Please provide a valid input!') sleep(0.5) except KeyboardInterrupt: print() print('See you soon!') sys.exit()
def playGame(): # build the solar system sun = Celestial("resources/images/sun.jpg", 75, 0, 1) player1 = Player( 1, Celestial("resources/images/player1.png", mass=20, radius=85, eccentricity=0.95)) player2 = Player( 2, Celestial("resources/images/player2.png", mass=20, radius=340, eccentricity=0.95)) # this collection is everything that can attract the ship planets = [ sun, player1.celestial, Celestial("resources/images/planet.png", mass=15, radius=123, eccentricity=1.05), Celestial("resources/images/planet.png", mass=10, radius=175, eccentricity=0.90), Celestial("resources/images/planet.png", mass=10, radius=250, eccentricity=0.85), Celestial("resources/images/planet.png", mass=20, radius=300, eccentricity=0.95), player2.celestial ] ship = Ship() game = Game([player1, player2], ship, planets, screen) # the game is over when all but one player is dead while not game.is_over(): # this is listening for someone to close the window event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit(0) # clear the screen screen.fill(black) # let the player know whose turn it is, and how # much fuel is left on the spaceship game.render_state() # move the planets in their orbits for p in planets: p.move() p.blit(screen) # move the ship by # - dragging it towards the sun and each planet # - if the player is pressing the direction keys, then apply that thrust if ship.is_launched: # while the ship is launching we ignore the home planet attracting_planets = planets if ship.is_launching: attracting_planets = [ e for e in planets if e != game.current_player().celestial ] ship.apply_acceleration(attracting_planets) ship.move() # if the ship has hit something, or has run out of fuel, then # then it's the next player's turn # : if the ship hit a player and killed them then game.is_over() # will say so game.check_collisions() if ship.is_ship_dead(): game.next_player() else: # the ship isn't launched, so check if we've been asked # to do so game.check_launch_trigger() game.heal_other_players() # redraw the frame, but we don't want a framerate > 40 pygame.display.flip() clock.tick(40) # if we're here, then the game is over game.render_game_over()
class Jarvis: def __init__(self, logAll=True): # конструктор self.logAll = logAll self.yandexStuff = YandexStuff() self.loop = True # создаем модули self.radio = Radio() self.anekdot = Anekdot() self.game = Game() self.weather = Weather() self.citygame = city_game() self.recognizer = speech.Recognizer() self.iamToken, self.iamTokenExpires = self.yandexStuff.create_token() self.play('audio/powerup.wav') time.sleep(0.5) # todo uncomment self.play('audio/jarvisHi.wav') time.sleep(0.5) self.playLowBeep() def destroy(self): self.play('audio/jarvisBye.wav') time.sleep(1) self.play('audio/powerdown.wav') self.loop = False def checkActive(self): result = False t = "" with speech.WavFile("audio/tmp/send.wav") as source: audio = self.recognizer.record(source) # используем возможности библиотеки Spinx try: t = self.recognizer.recognize_sphinx( audio) # todo check, language='ru-RU/cmusphinx-ru-5.2') if t != "" or self.logAll: print("Sphinx thinks you said: [" + t + "]") except speech.UnknownValueError: result = 0 if self.logAll: print("Sphinx could not understand audio") except speech.RequestError as e: print("Sphinx error; {0}".format(e)) if t == "jarvis": result = True if result: self.playHiBeep() return result def playHiBeep(self): Jarvis.sysCommand("aplay audio/beep_hi.wav", self.logAll) def playLowBeep(self): Jarvis.sysCommand("aplay audio/beep_lo.wav", self.logAll) def listen(self, n, useOgg=False): # записываем n секунд эфира с микрофона Jarvis.sysCommand('arecord -fcd -d' + str(n) + ' audio/tmp/send.wav', self.logAll) if useOgg: Jarvis.sysCommand( 'opusenc --bitrate 48 audio/tmp/send.wav audio/tmp/send.ogg', self.logAll) # with self.r.Microphone() as source: # audio = self.r.listen(source) def mainLoop(self): try: while self.loop: self.listen(2) res = self.checkActive() if res: # записываем основной запрос пользователя self.listen(3, True) self.playLowBeep() time.sleep(0.5) words = self.yandexRecognize() command = CommandChecker.checkForCommand(words.lower()) print('команда: ' + command) if (command == "exit"): loop = False self.destroy() elif (command == "game"): self.game.GameLoop() elif (command == "weather"): self.weather.getWeather() elif (command == "radio"): self.radio.listen() elif (command == "radiostop"): self.radio.stop() elif command == "cities": self.citygame.citi_function() elif (command == "anekdot"): try: joke = self.anekdot.getJoke() print(joke) self.say(joke) except: self.say("Что-то я не в настроении шутить") except Exception as e: print("Глобальная ошибка; {0}".format(e)) self.play('audio/error.wav') # статические функции для использования в других классах @staticmethod def sysCommand(command, logAll=False): #c = "{}{}".format(command, self.devNull) #os.system(c) subprocess.run(command, shell=True, capture_output=not logAll) @staticmethod def play(file): Jarvis.sysCommand('aplay ' + file) @staticmethod def playmp3(file): Jarvis.sysCommand('mpg123 ' + file) def say(self, text): # print(text) self.yandexStuff.createSynthAudio(self.iamToken, text, "tts.wav") Jarvis.play("audio/tmp/tts.wav") def yandexRecognize(self): # speech-to-text от старины Яндекса #print('token: ' + self.iamToken); recognizedText = self.yandexStuff.recognize(self.iamToken) result = recognizedText['result'] print(result) return result
def setUp(self): self.game = Game("Rock, Paper, Scissors") self.mark = Player("Mark", "Rock") self.jill = Player("Jill", "Paper") self.chris = Player("Chris", "Scissors")
def main(): game = Game() # initialize the Game object human = Player() # initialize the Player object ai = AiPlayer() # initialize the AiPlayer object (player_data, ai_data, game_data, loaded) = game.load_game() # ask to load the previous game (load_game() returns a tuple of 4 elements) if loaded == True: # only load data if game.load_game() ran succesfully human.name = player_data['name'] # get the human name from the player data dict human.wins = player_data['wins'] # get the human wins from the player data dict human.win_rate = player_data['win_rate'] # get the win rate from the player data dict ai.name = ai_data['name'] # get the ai name from the ai data dict ai.wins = ai_data['wins'] # get the ai wins from the ai data dict ai.win_rate = ai_data['win_rate'] # get the ai win rate from the ai data dict game.sessions = game_data['sessions'] # get the game sessions data from game data dict print('Loaded succesfully') while (game.get_state() == True): # keep looping if the game state is True human.set_choice() # set human choice if human.choice not in game.options: # check the input and break the loop if the input is not what we want print('Error 1: Incorrect input') continue human.history.append(human.choice) # add player choices to a list if human.choice == 'exit': game.close() continue game.sessions += 1 # track game sessions if game.sessions == 1: # if it's the first round ai.set_choice() # set the ai choice (randomly) else: if game.sessions % 5 == 0: # every 5 rounds if human.get_last_choice() == 'rock': # set the ai choice to the last player choice ai.choice = 'paper' elif human.get_last_choice() == 'paper': ai.choice = 'scissors' elif human.get_last_choice() == 'scissors': ai.choice = 'rock' human.history = [] # wipe the player player history to get fresh data for next 5 rounds else: if human.frequent_choice() == 'rock': # set the ai choice to the most frequent player choice ai.choice = 'paper' elif human.frequent_choice() == 'paper': ai.choice = 'scissors' elif human.frequent_choice() == 'scissors': ai.choice = 'rock' print('------------------------') print(f'{human.name} selected: {human.choice}') # display the player choice print(f'{ai.name} selected: {ai.choice}') # display the ai choice # compare the choices and display the winner if ai.choice == human.choice: print('[Draw]') elif ai.choice == 'rock' and human.choice == 'scissors': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 elif ai.choice == 'paper' and human.choice == 'rock': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 elif ai.choice == 'scissors' and human.choice == 'paper': print(f'[{ai.name} won]') ai.wins += 1 # increment ai win by 1 else: print(f'[{human.name} won]') human.wins += 1 # increment player win by 1 print('------------------------') ai.win_rate.append(ai.wins / game.sessions) # track the ai win rate human.win_rate.append(human.wins / game.sessions) # track the player win rate # player, ai and game data is saved in dictionaries for the purpose of saving player_data = {"name": human.name, "wins": human.wins, "win_rate": human.win_rate} ai_data = {"name": ai.name, "wins": ai.wins, "win_rate": ai.win_rate} game_data = {"sessions": game.sessions} print(f'SCORES ---- Humans: {human.wins} AI: {ai.wins}') # display the individual wins print(f'AI Win Rate: {ai.get_win_rate()}%') # display the ai win rate print(f'HUMAN Win Rate: {human.get_win_rate()}%') # display the player win rate save_status = game.save_game(player_data, ai_data, game_data) # asks to save the game if save_status == True: # print a message if saved succesfully print('Saved game succesfully')
import sys from pprint import pprint from modules.moves import is_valid_move from modules.game import Game moves_file = sys.argv[1] print(f"📁 Loading {moves_file}... ") f = open(moves_file, 'r') lines = f.read().splitlines() game = Game() for line in lines: if is_valid_move(line): print(f"↗ Move {line}") game.execute_move(line) f.closed pprint(game.get_result())
"""Script to run the game.""" import pygame as pg pg.init() from modules.game import Game if __name__ == '__main__': Game.main_loop()
# realdir = os.path.dirname(realpath) # Set title and init game window with icon pygame.display.set_caption("PyCheckers") screen = pygame.display.set_mode((1080, 720)) icon = pygame.image.load("app/assets/icon.png").convert() pygame.display.set_icon(icon) # Create main menu menu = Menu() menu.main() # Create a game game = Game() # Not playing so main page # Game loop running = True input_text = '' while running: if game.is_playing: # Update game screen game.update(screen, input_text) input_text = '' else: menu.update(screen)