def start_game(self, team): log_stats('play') print self.team1, self.team2 teams = [('Player 1', self.team1), ('Player 2', self.team2)] mapsel = MapSelection(self.screen, 'map_new.txt') mapsel.loop() start_game(self.screen, mapsel.mapname, teams)
def start_game(sprites, grid, paths_mapper, walls): game.run_game = True game.clear() pygame.event.pump() print "Loaded Into Game!" pygame.mouse.set_visible(True) game.start_game(renderer, pygame.quit, clock, pygame, sprites, walls, grid, paths_mapper, audio_manager, show_menu, load_to_game, text_fonts)
def press(event, game, fig, do_something, do_something_args, initial_state): if event.key == "escape": plt.close() else: # print('press', event.key) sys.stdout.flush() reward, finish = game.action(event.key) plt.imshow(game.show()) plt.title("Latest Reward: " + str(reward)) fig.canvas.draw() if do_something is not None: do_something(*do_something_args) if finish: print("You Won!") game.start_game(initial_state)
def eval_genomes(genomes, config): for genome_id, genome in genomes: net = neat.nn.recurrent.RecurrentNetwork.create(genome, config) x = game.start_game() possb = [game.up_possible(x),game.down_possible(x),game.left_possible(x),game.right_possible(x)] y = [0 for i in range(16)] y = game.matrix_to_vector(x) death = 1 death_flag = 0 while possb != [0,0,0,0]: output = net.activate(format_input(x)) x = action(output, x) if game.matrix_to_vector(x) == y: if death_flag == 0: death = -3 death_flag = 1 else: death += 1 else: # print("not equal! \n") # print(game.matrix_to_vector(x), y) death = 1 death_flag = 0 y = game.matrix_to_vector(x) if death == 0: break scr = game.score(x) genome.fitness = scr possb = [game.up_possible(x),game.down_possible(x),game.left_possible(x),game.right_possible(x)]
def test_start_game(decision, expected): result = start_game(decision) # print(result) assert expected == result # class test_human_user(): # test_start_game("YES", "Game Over")
def main(self): print("Welcome to maze vision 2020.") print("Enter level number you want to play. ") print("1. Basic") print("2. Easy") print("3. Intermediate") print("4. Hard") print("5. Master") level = int(input()) self.levels = level print("\nYou selected", level) if level not in [1,2,3,4,5]: print("You selected wrong value.") return self.active_maze = randomize_maze_board(get_maze(level)) self.active_maze = show_optimal_path(self.active_maze) start_game(self.active_maze)
def ui_start_game(): players = [] for k in request.POST: if k.startswith("player_"): for i in range(int(request.POST[k])): players.append(k[7:]) game_id = start_game(json={"players": players})['game_id'] redirect('/ui/game/' + game_id)
def play_game(self): print("Welcome to maze vision 2020.") level = get_level_input() print("\nYou selected", level) if level not in [1, 2, 3, 4, 5]: print("You entered wrong value.") return strategy = get_control_strategy() print("\nYou selected", strategy) if strategy not in [1, 2, 3, 4]: print("You entered wrong value.") return active_maze = randomize_maze_board(get_maze(level)) # If Neural Network selected if strategy == 4: start_qlearning_game(active_maze, strategy) else: start_game(active_maze, strategy)
def add_player_to_game(request, game_id, user): game = get_object_or_404(Game, pk=game_id) if Player.objects.filter(user=request.user,game=game).exists(): print "WE ALREADY HAVE THIS DUUDE!" return json.dumps( { 'message': game_id, 'error': 'WE ALREADY HAVE THIS DUDE' } ) elif Player.objects.filter(game=game).count() > 4: print "Too many players" return json.dumps( { 'message': game_id, 'error': 'Too many players in game.' } ) elif Player.objects.filter(game=game).count() == 4: add_new_player(request, game_id, user, game) print 'gonna start the game' start_game(game) url = str(game.pk) + '/1' # game id + current day aka 1 return json.dumps( { 'message': game_id, 'user': user, 'url': url } ) else: print 'durp' add_new_player(request, game_id, user, game) return json.dumps( { 'message': game_id, 'user': user } )
def show_top10(screen, file_name, ingame): file = open(file_name, 'r') lines=file.readlines() all_score = [] for line in lines: sep = line.index(' - ') name = line[:sep] score = int(line[sep+3:]) all_score.append((score, name)) file.close() all_score.sort(reverse=True) # sort from largest to smallest best = all_score[:10] screen.blit(background, (0, 0)) screen.blit(framehs, (60, 40)) message_display(screen, "High Score", black, (120, 150), 90) if ingame: screen.blit(button, (20, 1100)) screen.blit(button, (380, 1100)) message_display(screen, "Play Again", white, (50, 1120), 50) message_display(screen, "Main Menu", white, (405, 1120), 50) else: message_display(screen, "tap to continue", white, (100, 1120), 70) for i, entry in enumerate(best): message_display(screen, entry[1] + " " + str(entry[0]), black, (120, 55*i+280), 55) while True: for event in pygame.event.get(): if event.type == pygame.FINGERDOWN: touch_pos = [event.x * WIDTH, event.y * HEIGHT] if ingame: if 1200 > touch_pos[1] > 1100: if 340 > touch_pos[0] > 20: screen.blit(buttonp, (20, 1100)) message_display(screen, "Play Again", white, (50, 1120), 50) return if 700 > touch_pos[0] > 380: screen.blit(buttonp, (380, 1100)) message_display(screen, "Main Menu", white, (405, 1120), 50) #pygame.quit() game.g.show_start_screen() else: game.start_game() game.g.clock.tick(FPS)
def eval_fitness(genomes, config): for idx, g in genomes: cppn = neat.nn.FeedForwardNetwork.create(g, config) network = ESNetwork(substrate, cppn, params) net = network.create_phenotype_network() fitnesses = [] for i in range(trials): x = game.start_game() possb = [ game.up_possible(x), game.down_possible(x), game.left_possible(x), game.right_possible(x) ] scr = 0 y = [0 for z in range(16)] y = game.matrix_to_vector(x) death = 1 death_flag = 0 net.reset() for j in range(max_steps): for k in range(network.activations): o = net.activate(format_input(x)) x = action(np.argmax(o), x) if game.matrix_to_vector(x) == y: if death_flag == 0: death = -3 death_flag = 1 else: death += 1 else: death = 1 death_flag = 0 y = game.matrix_to_vector(x) if death == 0: break scr = game.score(x) possb = [ game.up_possible(x), game.down_possible(x), game.left_possible(x), game.right_possible(x) ] if possb == [0, 0, 0, 0]: break fitnesses.append(scr) g.fitness = np.array(fitnesses).mean()
def start_game(): with lock: ret = game.start_game(request.get_json(), games) if ret.get_json() != 'OK': return ret session_id = request.get_json()['session_id'] emit_update_lobby(session_id) emit_update_game(session_id) emit_update_chat(session_id) return ret
def run_game(): not_quit = True p1_turn = False # This will make sense below for who goes first p1_x = game.start_game() while not_quit: # Clear the display clear_display() # Initialize the game game_board = board.init_board() status = game.get_status(game_board, game.get_marker(p1_turn, p1_x)) # Take turns until game is won or lost or quit while status == "ongoing": # Change whose turn it is p1_turn = not p1_turn # Set current marker marker = game.get_marker(p1_turn, p1_x) # Get choice positions and valid positions and move print("\n----------------") print("\nOpen Options Board:") move_choice = game.move(*board.get_open_pos(game_board), p1_turn) # Update the board game_board = board.update_game_board(game_board, move_choice, marker) # Clear the display clear_display() # Display the Board print("\nGame Board:") board.display_board(game_board) # Check if game is won or stalemate status = game.get_status(game_board, marker) if status != "ongoing": break t_sleep(1) # See if they want to play again not_quit = game.set_replay(status, p1_turn) print("\nSorry to see you go, but I'll enjoy watching you walk away :)")
def lobby_loop(self): logging.info('Entered Lobby') while not self.ready(): msg = yield from self.queue.get() if type(msg) == ConnectionEstab: yield from self.connect(msg) elif type(msg) == ConnectionLost: yield from self.disconnect(msg) elif type(msg) == GetState: yield from self.send_state(msg) elif type(msg) == SetReady: yield from self.change_ready(msg) p1, p2 = tuple(self.players) logging.info('Starting game with players %s and %s', p1, p2) self.game = game.start_game(p1, p2, field_depth=2) self.state = 'INGAME' yield from self.send_states()
def run(pf): x = game.start_game() prev_x = copy.deepcopy(x) possb = [game.up_possible(x),game.down_possible(x),game.left_possible(x),game.right_possible(x)] while possb != [0,0,0,0]: temp = copy.deepcopy(x) move = look_avg_future(temp, pf, 0) move = move.index(max(move)) if(possb[move]==1): x = action(x,move) x = game.populate(x) # game.print_board(x) # print("maxtile: ",game.maxtile(x)) if prev_x == x: print("breaking ###################################################################################################################################################") break else: prev_x = x # game.print_board(x) # print(possb) possb = [game.up_possible(x),game.down_possible(x),game.left_possible(x),game.right_possible(x)] print("maxtile: ", game.maxtile(x)) return game.score(x)
self.maplist.append(self.add_map(m, x, y, h, w)) self.add_map(m, x, y, w, h) y = (y + h) + margin def write_button(self, surface, text, x, y): buttontext = self.buttonfont.render(text, True, (255,255, 255), (159, 182, 205)) buttonrect = buttontext.get_rect() buttonrect.centerx = x buttonrect.centery = y surface.blit(buttontext, buttonrect) def load_map(self, mapname): if self.mapname == 'nomap': print "No map selected" else: print "starting game" game.start_game(self.mapname) def edit_map(self, mapname): print "loading map: " + mapname def select_map(self, mapname): self.mapname = mapname print "selected map: " + mapname map, mapsize, spawns = load_map(self.mapname) self.map = preview_map(map, *mapsize, tiletypes = self.tiletypes) self.map_sprites = self.map.get_sprites() self.mapfield.fill((100, 100, 100)) self.screen.blit(self.mapfield, self.mapfield_rect) self.map_sprites.draw(self.screen) def get_sprites(self):
import random from players import * from game import start_game player_list = [RandomPlayer(), NicePlayer(), GreedyPlayer(), FicklePlayer(), GrudgePlayer(), \ CopycatPlayer(), SoreLoserPlayer(), CautiousPlayer(), CopykittenPlayer(), StrategicPlayer()] # Create players user = Player() opponent = random.choice(player_list) # Initial configurations pot = 1000 pool = 100 max_round = 10 print("Initial pot money:\t{}".format(pot)) print("Pool per round:\t{}".format(pool)) print("Maximum round:\t{}".format(max_round)) print() # Start game start_game(user, opponent, pot, pool, max_round)
""" This module is used to start the game and control the flow of the program """ import game if __name__ == '__main__': print("----------------------Play American Checkers-----------------------") game = game.Game() game.start_game()
from game import start_game start_game()
from constants import Fonts from window_manager import Window from game import start_game if __name__ == '__main__': root = Window(title='Snake Menu', max_fps=10) root.set_buttons({ 'text': 'Snake', 'x': 250, 'y': 100, 'font': Fonts.default(size=80) }, { 'text': 'Start game', 'x': 250, 'y': 250, 'fn': lambda: start_game(root.id) }, { 'text': 'Exit Game', 'x': 250, 'y': 400, 'fn': exit }) root.mainloop()
def handle_message(event): message = event.message.text user_id = event.source.user_id user_is_playing_game = False try: if message.find('@') == 0: message = message.replace('@', '@') if message.find('$') == 0: message = message.replace('$', '$') # check if user is play game user_is_playing_game = game.check_is_playing_game(user_id) if message == '教我說話': content = '嗨嗨~只要照著 【@學習 指令 回覆】(ex: @學習 你好 哈囉~) 這個格式輸入就可以讓我學習說話哦!還不趕快試試嗎?' res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) elif message == '猜數字遊戲': confirm_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url= 'https://compass-ssl.xbox.com/assets/dc/48/dc486960-701e-421b-b145-70d04f3b85be.jpg?n=Game-Hub_Content-Placement-0_New-Releases-No-Copy_740x417_02.jpg', title='【猜數字】', text= '猜一個四位不重複的數字,A表示數字對位置對,B表示數字對位置錯,透過已知的線索,來看看你能多快猜到數字吧!', actions=[ MessageTemplateAction(label='我要玩', text='#我要玩猜數字') ])) line_bot_api.reply_message(event.reply_token, confirm_template_message) elif message == '#我要玩猜數字': game.start_game(user_id) content = '遊戲開始!請輸入「$」加上4位數字,如果想結束遊戲請輸入「結束遊戲」,如果像看答案請輸入「我投降」,加油啦~' res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) elif message == '觀看作品': content = '哈囉~這是我一部份的小作品,目前僅放上網站的作品,其他類型的作品因為不好呈現所以沒有放上,不過也歡迎到我的 GitHub 去看看哦:D 另外網站由於 RWD 並沒有做到很完整,所以使用電腦觀看會比較佳哦~' content_message = TextSendMessage(text=content) works_message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate(columns=[ CarouselColumn( thumbnail_image_url= 'https://www.smartone.com/services_and_apps/tchinese/Spotify.png', title='【Spotify Demo】', text='The Demo website using spotify api.', actions=[ URIAction( label='Spotify Demo', uri= 'https://spotify-demo-by-harrison.herokuapp.com/index' ) ]), CarouselColumn( thumbnail_image_url='https://i.imgur.com/CYcSKeP.jpg', title='【New Sound Website】', text='New Sound 公司官方網站.', actions=[ URIAction(label='New Sound', uri='https://newsound.herokuapp.com/') ]), CarouselColumn( thumbnail_image_url='https://i.imgur.com/wo3gJPi.jpg', title='【momofit Website】', text='個人健身記錄網站.\naccount:howard\npassword:9527', actions=[ URIAction(label='momofit', uri='https://momofit.herokuapp.com/') ]) ])) line_bot_api.reply_message(event.reply_token, [content_message, works_message]) elif message == '尋找附近餐廳': confirm_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/Y1DWfaU.jpg', title='【尋找附近餐廳】', text='透過 Yelp 尋找出你附近的推薦餐廳,並且可以透過連結到 Yelp 網站上觀看評論以及更多資訊哦!', actions=[ URITemplateAction(label="傳送我現在的位置", uri="line://nv/location") ])) line_bot_api.reply_message(event.reply_token, confirm_template_message) else: if user_is_playing_game: if message.startswith('$'): number_list = list(message) if len(number_list) != 5 or len(set(number_list)) != 5: content = '請輸入四位不同的數字哦!' res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) else: res = game.check_number(user_id, number_list[1], number_list[2], number_list[3], number_list[4]) res_message = TextSendMessage(text=res) line_bot_api.reply_message(event.reply_token, res_message) elif message == '結束遊戲': game.finish_game(user_id) content = '遊戲結束囉~' res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) elif message == '我投降': content = game.give_up_game(user_id) res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) else: content = '還在遊戲中哦!如果想結束遊戲請輸入「結束遊戲」~' res_message = TextSendMessage(text=content) line_bot_api.reply_message(event.reply_token, res_message) else: if message.startswith('@學習 '): res = teach.learn_new_word(message) else: result = teach.responding(message) if result is None: res = '還沒學會哦!' else: res = result res_message = TextSendMessage(text=res) line_bot_api.reply_message(event.reply_token, res_message) except Exception as e: res_message = TextSendMessage(text=str(e)) line_bot_api.reply_message(event.reply_token, res_message)
from tkinter import * from game import start_game if __name__ == "__main__": root = Tk() btn1 = Button(root, text='Player first', command=lambda: start_game(root, 0)).pack() btn2 = Button(root, text='AI first', command=lambda: start_game(root, 1)).pack() root.wm_title("Mini AlphaGo") root.mainloop()
if imput_time_span == "highscore": time_span = -5 else: time_span = int(imput_time_span) print("目標の平均到達階層は?(0.0~21.0):") target_chance = float(input()) game_success = deque() score_history = deque() avg_history = deque() if time_span > 0: for span in range(time_span): #自動プレイ for play in range(time_play): player.reset() game_success.append(game.start_game(player, director, True)) #自動プレイでのクリア確率を計測し、結果を表示 print("\n" + str(span + 1) + "回目の結果:") #chance=game_success/time_play #print("クリア確率:",chance) #learn_score=calc_score(chance,target_chance) print("到達:[" + ','.join(str(i) for i in sorted(list(game_success))) + "]") avg = np.average(np.array(game_success)) std = np.std(np.array(game_success)) print("平均:" + str(avg) + " 標準偏差:" + str(std)) learn_score = abs(target_chance - avg) * -1.0 print("報酬:", learn_score, "\n") #学習 director.learn(learn_score) score_history.append(learn_score)
import random from players import * from game import start_game player_list = [RandomPlayer(), HonestPlayer(), DishonestPlayer()] # Create players user = Player() opponent = random.choice(player_list) # Initial configurations rounds = 10 # Start game start_game(user, opponent, rounds)
async def on_message(message): message_delete = message message_author = message.author message_author_id = message.author.id message_channel = message.channel message_content = message.content.lower() if message_content.startswith(bot_trigger + 'join'): game.join_player(message_author_id) await bot.send_message( message.channel, "<@%s> has joined the game." % message_author_id) print(message_author) print(game.players) if message_content.startswith(bot_trigger + 'leave'): game.leave_player(message_author_id) await bot.send_message(message.channel, "<@%s> has left the game." % message_author_id) print(game.players) if message_content.startswith(bot_trigger + 'purge'): game.purge() await bot.send_message(message.channel, "All users purged!") print(game.players) if message_content.startswith(bot_trigger + 'startgame'): if game.is_live: await bot.send_message(message.channel, 'Game is still ongoing.') else: game.start_game() for player in game.players: await bot.send_message(discord.User(id=player.name), embed=embeded_message( player.role, game._game_data['locations'][ game.location]['Location'])) await bot.send_message(message.channel, "The game has started!") location_title = "Spyfall - Locations List" location_content = '' for i in game.loc_list: location_content += "**%s**\n" % i loc_embed = discord.Embed(title=location_title, description=location_content) locs = await bot.send_message(message.channel, embed=loc_embed) # Create a simple timer to time the game. time = await bot.send_message(message.channel, game.get_formatted_time()) while game.is_live and game.tick(): await bot.edit_message(time, game.get_formatted_time()) await asyncio.sleep(1) # Loop exited, game has ended or has run out of time. End it and clear messages. await bot.delete_message(locs) await bot.delete_message(time) # If game is still live, it means the spy has not been revealed yet even though the time is up. # Players still have a last chance to vote who the spy is before ending the game. if game.is_live: await bot.send_message( message.channel, "Time's up! Vote who you think the spy is now.") if message_content.startswith(bot_trigger + 'players'): playing = 'Current Players:\n' for player in game.players: playing += "<@%s>" % player.name playing += ' ' await bot.send_message(message.channel, playing) if message_content.startswith(bot_trigger + 'reveal'): reveal_title = 'Spyfall - Reveal' reveal_location = 'The Location Was --> %s\n' % ( game._game_data['locations'][game.location]['Location']) reveal_players = '' for player in game.players: reveal_players += '<@%s> --> %s\n' % (player.name, player.role) reveal_content = reveal_location + reveal_players reveal_embed = discord.Embed(title=reveal_title, description=reveal_content) await bot.send_message(message.channel, embed=reveal_embed) game.end_game() if message_content.startswith(bot_trigger + 'settings'): command = message_content.split() setting = command[1] value = command[2] if setting == 'time': try: game.set_time(int(value)) await bot.send_message( message.channel, 'Game time set to {} seconds.'.format(game.round_time)) except ValueError: # Show error message if an invalid integer was entered for time. await bot.send_message( message.channel, 'Invalid value specified for "{}".'.format(setting)) else: await bot.send_message(message.channel, 'Invalid settings command.')
import create_hero import game if __name__ == "__main__": heroes, name_file = game.start_game() while True: game.menu(heroes, name_file)
states[batch_ind, :, :, :] = s0 predictions[batch_ind, :] = pred loss = -1 else: loss = deepQ.train_step(states, predictions) loss_graph.append(loss) batch_ind = 0''' status = game.status(reward) status = status + " eps: " + str(policy.eps)[0:4] if loss != -1: status = status + " Loss: " + str(loss) if finish: status = status + " Game Over!" game.start_game(initial_state) print("Iter: #" + str(iter) + " " + status) #if iter % int(num_of_iters / 15) == 0: #plt.figure() #plt.imshow(Q_table[:,relevant_states]) # Show results print("End of Training: {:.2f} secs".format(time.time() - start_time)) plt.figure() plt.plot(game.actions_per_game) plt.title("Number of turns per game") #plt.figure() #plt.imshow(tabular_learning.Q_table) game.start_game(initial_state)
from game import start_game if __name__ == '__main__': start_game(True) # app.mainloop()