def main(): parser = argparse.ArgumentParser(description='n-puzzle') parser.add_argument('-d', '--distance-metric', help='Distance function', choices=['simple', 'manhattan', 'euclead'], default='manhattan') parser.add_argument('-v', '--verbose', help='Verbose intermediate results', action='store_true') parser.add_argument('-g', '--greedy', help='Use greedy algorithm', action='store_true') parser.add_argument('-u', '--uniform', help='Use uniform cost', action='store_true') parser.add_argument('file', help='input file') parser = parser.parse_args() try: data_parser = Parser(file_name=parser.file) node = Node(puzzle_data=data_parser.get_data(), metric=parser.distance_metric, print_inter_res=parser.verbose, greedy=parser.greedy, uniform_cost=parser.uniform) game = Game(start_node=node) game.solve() exit(0) except ValueError as error: print(error) exit(2)
def __init__(self): """init the game""" self.running = True # the snake can move self.game = Game() self.player = Player(START_SIZE, CELL_SIZE) self.apple = Apple(START_POS_APPLE[0], START_POS_APPLE[1], CELL_SIZE) pygame.init() self._display_surf = pygame.display.set_mode((self.window_width, self.window_height), pygame.HWSURFACE) self.image_surf = pygame.image.load(IMAGE_CELL).convert() self.apple_surf = pygame.image.load(IMAGE_APPLE).convert() pygame.display.set_caption("Snake") # the caption of the game
def main(): # inicio o pygame init() # posiciono a tela no centro environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (300, 80) # crio a janela com o nome pacman tamanho_tela = (730, 434) tela = display.set_mode(tamanho_tela) display.set_caption("Pac-man!") # crio um objeto do tipo jogo jogo = Game(tela) # loop do jogo jogo.run() # desaloca recursos do pygame quit()
def debug(uuid): try: file = open(f"{root}{uuid}.json", "r") lines = "".join([line.strip() for line in file.readlines()]) file.close() jason = json.loads(lines) from Classes.Game import Game game = Game(jason) print(game) return game except FileNotFoundError: print(f"Failed debug of {uuid}.json", sep="")
def create_host(): game_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5)) game_name = "abvd" create_game(game_name) res, _ = HostScreen("Your host data", game_name, width, height).run(game_name) # вот здесь надо от юзеров получать змейки и кидать в массив # По идее, надо просто передать змейку хосту и там уже всё запускать snakes = [ Snake(name, width=width, height=height) for name in get_game(game_name)["snakes"] ] for ind, snake in enumerate(snakes): body, direction = body_choice(ind, width, height) if body is not None and direction is not None: snake.body = body snake.head_pos = body[0] snake.direction = direction game = Game(snakes, width=width, height=height, speed=speed, host_addr=game_name) game.scores = [0 for i in game.scores] update_game_var(game_name, "state", game.to_dict()) update_game_var(game_name, "status", PLAYING) play(host=game_name, player_name="HOST")
def old_query_games(constraints=None, limit=13477, describe_results=True, display_progress=True, categorization_function=lambda game: None): data_directory = os.listdir(root) categories = {} accepted, rejected = 0, 0 if display_progress: print("Querying games, please wait...") print(f"0%{'.' * 21}25%{'.' * 22}50%{'.' * 22}75%{'.' * 21}100%") prog_bar = 0 for filename in data_directory: try: file = open(root + filename, "r") lines = "".join([line.strip() for line in file.readlines()]) file.close() jason = json.loads(lines) if constraints is None or constraints(jason): game = Game(jason) category = categorization_function(game) if category in categories: categories[category].append(game) else: categories[category] = [game] accepted += 1 if accepted >= limit: break else: rejected += 1 if display_progress: delta = (101 * (accepted + rejected) // limit) if delta > prog_bar: print(end="|") prog_bar += 1 except: print(f"Problematic File?\t{filename}") if display_progress: print("|") if describe_results: total = accepted + rejected print(f"Queried {total} games:") acc_ratio, rej_ratio = round(100 * accepted / total, 1), round(100 * rejected / total, 1) print(f" Accepted {accepted} games ({acc_ratio}%)") if rejected > 0: print(f" Rejected {rejected} games ({rej_ratio}%)") return categories
def play(host, player_name): import time global stop_sign stop_sign = True while True: global sum, frame_cont, val start = time.time() res = Game.game_calculate_once(host, player_name) # res = next(a) setted = set_key(name, val) if res: val = res
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "f", ["file"]) except getopt.error as msg: print(msg) print("It is necessary file :((") sys.exit(2) for arg in args: try: parser = Parser(file_name=arg) node = Node(puzzle_data=parser.get_data(), metric='simple') game = Game(start_node=node) game.solve() exit(0) except ValueError as error: print(error) exit(2) parser = Parser() node = Node(puzzle_data=parser.get_data(), metric='euclead') game = Game(start_node=node) game.solve()
def populate_from_dir(self, directory, distrib_source): for entry in scandir(directory): if (entry.name[0] != "!") and (entry.name != "System Volume Information") and entry.is_dir(): # titles will include [ and ] for distrib_source, we ignore them for title and parse them for source if entry.name.find('[') >= 0: game_title = entry.name[0:entry.name.find('[')].strip() else: game_title = entry.name folder = entry.path version = 0.0 # for installers we use a function installer = get_installer_paths(folder) if distrib_source != 0: distrib_type = distrib_source elif entry.name.find('[') >= 0: distrib_type = entry.name[entry.name.find('[') + 1:entry.name.find(']')].strip() else: distrib_type = "Unknown" new_game = Game(game_title, version, folder, installer, distrib_type) self.add_game(new_game)
def startAgain(self): self.root.destroy() from Classes.Game import Game game = Game() game.main() return True
def eval_fitness(genomes, config): global genome_num nets = [] names = [] ge = [] for genome_id, genome in genomes: genome.fitness = 0 # start with fitness level of 0 net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) ge.append(genome) names.append("AI" + str(genome_num)) genome_num += 1 for player1 in range(len(ge)): for player2 in range(player1 + 1, len(ge)): game = Game(names[player1], names[player2]) p1_nn_input = [] p2_nn_input = [] map_linear = [] game_state_repeat_cnt = 0 game_state = [] game_state_prev = [] game_state_2prev = [] while not game.game_over: map_linear.clear() for y in range(Cfg.map_y_tiles): for x in range(Cfg.map_x_tiles): map_linear.append(game.map.grid[x][y]) p1_nn_input.clear() p1_nn_input.extend(map_linear) p1_nn_input.append(game.player1.bombs) p1_nn_input.append(game.player1.health) p1_nn_input.append(game.player1.walls) p1_nn_input.append(game.player1.x) p1_nn_input.append(game.player1.y) p1_nn_input.append(game.player2.x) p1_nn_input.append(game.player2.y) p2_nn_input.clear() p2_nn_input.extend(map_linear) p2_nn_input.append(game.player2.bombs) p2_nn_input.append(game.player2.health) p2_nn_input.append(game.player2.walls) p2_nn_input.append(game.player2.x) p2_nn_input.append(game.player2.y) p2_nn_input.append(game.player1.x) p2_nn_input.append(game.player1.y) p1_output = nets[player1].activate(p1_nn_input) p2_output = nets[player1].activate(p2_nn_input) p1_command = output_interpreter(p1_output) p2_command = output_interpreter(p2_output) # print(p1_command, p2_command) game.loop(p1_command, p2_command) game_state.clear() game_state.extend(map_linear) game_state.append(game.player1.bombs) game_state.append(game.player1.health) game_state.append(game.player1.walls) game_state.append(game.player1.x) game_state.append(game.player1.y) game_state.append(game.player2.bombs) game_state.append(game.player2.health) game_state.append(game.player2.walls) game_state.append(game.player2.x) game_state.append(game.player2.y) if game_state == game_state_prev or game_state == game_state_2prev: game_state_repeat_cnt += 1 if game_state_repeat_cnt > 5: game.game_over = True elif game_state_repeat_cnt > 0: game_state_repeat_cnt = 0 game_state_2prev.clear() game_state_2prev.extend(game_state_prev) game_state_prev.clear() game_state_prev.extend(game_state) print(game.outcome) if game.outcome == names[player1]: ge[player1].fitness += 20 if game.outcome == names[player1]: ge[player2].fitness += 20 if game.outcome == "Tie": ge[player1].fitness += min(game.player1.fitness, 10) ge[player2].fitness += min(game.player2.fitness, 10) print(min(game.player1.fitness, 10), min(game.player2.fitness, 10)) del game
continue elif letter.isdigit(): print("The input can't contain any number value.") continue elif letter in guesses_list: print( "This character has already been used, please type another one." ) continue else: break return letter # Object Initialization Game = Game(word_rnd) print(drawing[0]) print("Word: %s" % Game.showBlanks()) blankedWord = Game.showBlanks() # Len function brings the length of the list, we use the -1 so we can # properly work with Python indexing while drawing_index < len(drawing) - 1: guess = inputValidation(all_guesses) if Game.Matched(guess): print(drawing[drawing_index]) blankedWord = Game.showGuess(guess, blankedWord) print("Word: %s" % blankedWord)
# Call to create the users character. player.create_player() # Asks the user to select the level of difficulty. difficulty = input("Please select a level of difficulty. \n" + "1. Easy\n" + "2. Normal\n" + "3. Hard\n" + "4. Extreme\n") Terminal.clear_CLI() # While loop that contines until the player currectly creates a character. cont = False while cont is False: print("You picked a", player.sex, player.race) print("that has a Health of", player.health, "\na damage of", player.damage, "\na magic point of", player.magic) user_in = input("Would you like to start the game? y/n \n") if user_in is 'y' or user_in is 'Y': cont = True elif user_in is 'n' or user_in is 'N': user_in = input( "Would you like to remake your character? y/n. No will start the game. \n" ) if user_in is 'y' or 'Y': player.create_player() elif user_in is 'n' or 'N': cont = True Terminal.clear_CLI() # Once the players character is created to the players liking the game will begin. game = Game(difficulty, player) game.play_game()
from Classes.Game import Game if __name__ == '__main__': game = Game() game.start_game()
class App(object): window_width = 800 # the width of the game field window_height = 600 # the height of the game filed player = 0 apple = 0 def __init__(self): """init the game""" self.running = True # the snake can move self.game = Game() self.player = Player(START_SIZE, CELL_SIZE) self.apple = Apple(START_POS_APPLE[0], START_POS_APPLE[1], CELL_SIZE) pygame.init() self._display_surf = pygame.display.set_mode((self.window_width, self.window_height), pygame.HWSURFACE) self.image_surf = pygame.image.load(IMAGE_CELL).convert() self.apple_surf = pygame.image.load(IMAGE_APPLE).convert() pygame.display.set_caption("Snake") # the caption of the game def on_loop(self): """ check the collisions in the game; check the snake has eaten an apple: create new apple; add new cell to the snake's body; check the snake is out of the game field. """ self.player.update() # check if the are collisions between the head and the body of the snake for i in range(1, self.player.length): if self.game.is_collision(self.player.x[i], self.player.y[i], self.player.x[0], self.player.y[0]): self.running = False # check if the snake has eaten an apple if self.game.is_collision(self.apple.x, self.apple.y, self.player.x[0], self.player.y[0]): # create new apple appl_appeared = False while not appl_appeared: appl_appeared = True self.apple.x = randint(0, 17) * CELL_SIZE self.apple.y = randint(0, 12) * CELL_SIZE # check the apple has not been appeared in the snake for i in range(self.player.length): if self.game.is_collision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i]): appl_appeared = False break # add new cell to the snake's body self.player.length += 1 self.player.x.append(self.player.x[self.player.length - 2]) self.player.y.append(self.player.y[self.player.length - 2]) # check the snake is out of the game field if self.game.is_out(self.player.x[0], self.player.y[0], self.window_width, self.window_height): self.running = False def on_render(self): """ draw the surface, the snake and an apple """ self._display_surf.fill((0, 0, 0)) self.apple.draw(self._display_surf, self.apple_surf) self.player.draw(self._display_surf, self.image_surf) pygame.display.flip() def on_cleanup(self): """ call the Tkinter widget when it is the player has lost the game. """ def exit_(event): """ destroy everything and exit the application. :param event: to call the function by some event (clicking on the button. """ pygame.quit() root.destroy() root = Tk() root["bg"] = "#262626" label = Label(root, anchor=CENTER, height=3, width=50, relief=GROOVE, font="Calibri 14", bg="#E31E00", fg="black") label["text"] = 'You lose!!!\nYou have received the {} level.\nCongratulations!!!'.format(self.game.level) button = Button(root, bg="black", activebackground="#E6E6E6", fg="white", relief=GROOVE, text="Exit", width=10) label.grid(row=0, column=0, columnspan=3) button.grid(row=1, column=2) button.bind("<Button-1>", exit_) root.mainloop() def on_execute(self): """ to check the movement of the snake; to move it. """ while self.running: pygame.event.pump() keys = pygame.key.get_pressed() if keys[K_RIGHT]: self.player.move_right() if keys[K_LEFT]: self.player.move_left() if keys[K_UP]: self.player.move_up() if keys[K_DOWN]: self.player.move_down() if keys[K_ESCAPE]: self.running = False self.on_loop() self.on_render() sleep(TIME_TO_SLEEP) self.on_cleanup()
import pygame from pygame.locals import * from globals import * from Classes.Game import Game pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() #variables sc = pygame.display.set_mode((W, H)) clock = pygame.time.Clock() game = Game() pygame.display.set_caption('Snake') while 1: events = pygame.event.get() sc.fill(BG) game.update() game.draw(sc) pygame.display.update() for event in events: if (event.type == QUIT): exit() if (event.type == KEYDOWN):
from Classes.Game import Game game = Game() game.run()
def buttonClicked(self): self.root.destroy() game = Game() game.main()