def update_image(self): if not Game().paused: if Game().counter % Game().animate_divider == 0: animate = True else: animate = False self.image.fill((0, 0, 0)) #for clearing sprites self.a.clear(self.image, self.image) self.a.update(animate) self.image.blit(self.bg, (-Camera().dx, -Camera().dy)) #pos bg #objects self.data = [] player_x, player_y = Game().player.get_pos() for y in range((player_y - self.height / 2) / self.tile_size, (player_y + self.height / 2) / self.tile_size): for x in range((player_x - self.width / 2) / self.tile_size, (player_x + self.width / 2) / self.tile_size): if (x, y) in self.data1: btn = self.data1[x, y] self.data.append(btn) img = btn.get_image() self.image.blit(img, (x * self.tile_size - Camera().dx, y * self.tile_size - Camera().dy)) self.a.draw(self.image)
def prepare_image(self): self.image = pygame.Surface((self.width, self.height)) self.a = pygame.sprite.Group( graphic.Character_Sprite('actor2'), graphic.Character_Sprite('actor1'), graphic.Character_Sprite('actor3'), #graphic.Character_Sprite('evil'), ) i = 0 for sprite in self.a: sprite.data = Game().npcs[i] i += 1 playersprite = graphic.Character_Sprite('evil') playersprite.data = Game().player self.a.add(playersprite) Camera().update(Game().player.get_pos()) map_drawer = self.controller.map_drawer self.bg = map_drawer.get_all_map_image(self.tile_size) self.image.blit(self.bg, (-Camera().dx, -Camera().dy)) self.data1 = map_drawer.prepare_map_objects(self.tile_size) '''test=ImageStorage()['plants'] for i in range(len(test)): testrow=test[i] for j in range(len(testrow)): testimg = testrow[j] self.bg.blit(testimg,(i*40,j*40))''' self.a.draw(self.image)
def example_data(): """Create example data for the test database.""" dob = datetime.strptime('16Sep2012', '%d%b%Y') u = User(username='******', password='******', name='Test', date_of_birth=dob) g = Game(num_players=4, difficulty='h') g2 = Game(num_players=4, difficulty='e') g3 = Game(num_players=4, difficulty='e') db.session.add_all([u, g, g2, g3]) db.session.commit() p = HumanPlayer(name='Test', user_id=1, game_id=1, position=1) o_1 = AIPlayer(name="opponent_1", difficulty='h', game_id=1, position=2) o_2 = AIPlayer(name="opponent_2", difficulty='h', game_id=1, position=3) o_3 = AIPlayer(name="opponent_3", difficulty='h', game_id=1, position=4) p_2 = HumanPlayer(name='Test', user_id=1, game_id=2, position=1) o_1_2 = AIPlayer(name="opponent_1", difficulty='e', game_id=2, position=2) o_2_2 = AIPlayer(name="opponent_2", difficulty='e', game_id=2, position=3) o_3_2 = AIPlayer(name="opponent_3", difficulty='e', game_id=2, position=4) p_3 = HumanPlayer(name='Test', user_id=1, game_id=3, position=1) o_1_3 = AIPlayer(name="opponent_1", difficulty='e', game_id=3, position=2) o_2_3 = AIPlayer(name="opponent_2", difficulty='e', game_id=3, position=3) o_3_3 = AIPlayer(name="opponent_3", difficulty='e', game_id=3, position=4) db.session.add_all( [p, o_1, o_2, o_3, p_2, o_1_2, o_2_2, o_3_2, p_3, o_1_3, o_2_3, o_3_3]) db.session.commit()
def game_on_game_in_progress(self, g): for player in g.players: self.send_message(player.name, message.game.in_progress, server=g.server.name, password=g.password, \ ip=g.server.address[0], port=g.server.address[1]) user = User.find_or_create_by_nick(player.name) if not user.games_played: user.games_played = 0 user.games_played += 1 user.save() user = User.find_or_create_by_nick(g.owner) if not user.games_admined: user.games_admined = 0 user.games_admined += 1 user.save() game_mode = "highlander" if g.is_highlander else "%sv%s" % (g.max_players / 2, g.max_players / 2) team_groups = (g.get_class_groups() if g.is_highlander else g.get_team_groups()) team_groups = dict(map(lambda k: (str(k), team_groups[k]), team_groups)) game = Game(created_at=datetime.datetime.now(), mode=game_mode, server=g.server.name, \ map=g.map, admin=g.owner, teams=team_groups) game.save() #self.set_topic_game_inprogress() self.game_end() self.send_message(message.game.sent_password)
def main(): screen = app_init() board_view = BoardView(screen, 'static/chessboard.png') game = Game() while not game.end(): handle_user_events(game) board_view.update_screen(game)
def pass_turn(game_info: Game) -> Game: game_info.turn_index = game_info.turn_index + 1 if game_info.turn_index >= len(game_info.turn_order): game_info.turn_index = 0 game_info.turn_order = (game_info.turn_order[1:] + game_info.turn_order[0]) game_info = restock_shop(game_info) return game_info
def __init__(self): self.game = Game() self.done = False self.state = None self.states = [] self.moves = [] self.rewards = [] self.generate_choices()
def create_game(self, request): """Creates a new game for Hangman users""" user = User.query(User.user_name == request.user_name).get() if not user: raise endpoints.NotFoundException('User does not exist') game = Game(user_name=user.key, target=random_word()) game.put() return game.to_form()
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption('Tic Tac Toe') self.screen.fill(BACKGROUND_COLOR) self.game = Game() self.player = Human('X') self.comp = Comp('O') self.level = None
def new_game(player_one, player_two, game_id): """Creates and returns a new game. Args: player_one: A key representing player one. player_two: A key representing player two. game_id: A string representing a game_id for generating a Game.key. Returns: A game detailing the players, the active player, and the deck. """ game_key = ndb.Key(Game, game_id) game = Game( key=game_key, player_one=player_one, player_two=player_two, active_player=player_one, game_over=False ) deck = Deck() deck.shuffle() # Deal out each player's starting hand player_one_hand = Poker.serialize_hand(deck.draw(5)) hand = Hand( player=player_one, game=game.key, hand=player_one_hand, state=str(HandState.STARTING) ) hand.put() player_two_hand = Poker.serialize_hand(deck.draw(5)) hand = Hand( player=player_two, game=game.key, hand=player_two_hand, state=str(HandState.STARTING) ) hand.put() game.deck = deck.serialize() game.put() # Send email to active player signaling the start of the game taskqueue.add( url='/tasks/send_move_email', params={ 'game_key': game.key.urlsafe(), 'user_key': game.active_player.urlsafe() }, transactional=True ) return game
def create_new_game(self, listing, price, country): game = Game(title=listing["game_title"], min_price=price, min_price_country_id=country, last_updated=self.date) game.id = self.db_util.save(game) self.existing_games.append(game) return game
def init_game(request): print "Init game..." player1 = Player("Player 1") player2 = Player("Player 2") game = Game(player1, player2) # Store game object to session request.session['game'] = game # Print game id for DEBUG print game.id() return game.toJSON()
async def post(self, request): ''' 新增游戏 ''' game = Game() # print(type(request.json)) result = game.replace_one(request.json, request.json, True) print(result.matched_count) print(result.modified_count) return json(request.json, 201)
def player_mouse_move(self,x,y): player = Game().player px,py = Camera().coord_transform(player.get_pos()) dx = x - px dy = y - py norm = max(abs(dx),abs(dy)) dx /= norm dy /= norm player.order_to_go(dx,dy) Camera().update(player.get_pos()) self.move_mini_map_to_player()
def player_keyboard_move(self,direction): player = Game().player if direction == 'up': player.order_to_go(0,-1) if direction == 'down': player.order_to_go(0,1) if direction == 'left': player.order_to_go(-1,0) if direction == 'right': player.order_to_go(1,0) Camera().update(player.get_pos()) self.move_mini_map_to_player()
def main(gameid, name, new, test): global p1, p2, p3, p4, p5, p6, p7, p8 if test: gameid = Game(**SHPlayer.new_game()).uuid p1 = player_thread(gameid, "Player 1") p2 = player_thread(gameid, "Player 2") p3 = player_thread(gameid, "Player 3") p4 = player_thread(gameid, "Player 4") p5 = player_thread(gameid, "Player 5") p6 = player_thread(gameid, "Player 6") p7 = player_thread(gameid, "Player 7") p8 = player_thread(gameid, "Player 8") p1.start() time.sleep(0.35) p2.start() time.sleep(0.35) p3.start() time.sleep(0.35) p4.start() time.sleep(0.35) p5.start() time.sleep(0.35) p6.start() time.sleep(0.35) p7.start() time.sleep(0.35) p8.start() p8.start_game = True p1.join() p2.join() p3.join() p4.join() p5.join() p6.join() p7.join() p8.join() sys.exit(0) if new: gameid = Game(**SHPlayer.new_game()).uuid print("Created a new game with UUID: {}".format(gameid)) if gameid is not None: player = SHPlayer(gameid, name) player.join_game() else: print("Please specify GAMEID or use --new flag") exit()
def example_data(): """Create example data for the test database.""" # If data already exists, delete it. Game.query.delete() g1 = Game(name="Super Smash Bros", description="A party fighting game by Nintendo.") g2 = Game(name="Set", description="A speed matching card game.") g3 = Game(name="Monopoly", description="A terrible game about capitalism.") db.session.add_all([g1, g2, g3]) db.session.commit()
def player_interact_roll(game_id: str, player_id: str): """ Given player tried to roll the dice """ try: game = Game(**games.get(where('uuid') == game_id)) game.roll(player_id) except Exception as err: return {"error": str(err)}, 404 games.update(game.dict(), where('uuid') == game_id) return {}
def delete_player(game_id, player_id): """ Delete a player from a game! """ try: game = Game(**games.get(where('uuid') == game_id)) except Exception as err: return {"error": str(err)}, 404 game.remove_player(player_id) games.update(game.dict(), where('uuid') == game_id) return {}
def player_interact_make_choice(game_id: str, player_id: str, choice_idx: int): """ Given player makes a choice from given list """ try: game = Game(**games.get(where('uuid') == game_id)) game.make_choice(player_id, choice_idx) except Exception as err: print(err) return {"error": str(err)}, 404 games.update(game.dict(), where('uuid') == game_id) return {}
def player_interact_end_turn(game_id: str, player_id: str): """ Given player ends their turn """ try: game = Game(**games.get(where('uuid') == game_id)) game.advance_turn() except Exception as err: print(err) return {"error": str(err)}, 404 games.update(game.dict(), where('uuid') == game_id) return {}
def post(self): user = users.get_current_user() if not user: self.redirect_to('/') name = self.request.get('game_name') new_game = Game( name = name, players_max = 6, players_current = 0, ) GameUpdater(new_game).init_deck() new_game.put() self.redirect_to('player',game_id=new_game.key.id())
def play_game(ngames=100): verbose = ngames == 1 cost_of_hut = 0.05 cost_of_station = 3 ntrees = 9 ngardens = 3 ncurses = 3 """ IDEAL GAME SCENARIOS: selfish vs. selfish: RARELY WIN selfish vs. default: MOSTLY WIN -> SELFISH selfish vs. generous: ALWAYS WIN -> SELFISH generous vs. generous: RARELY WIN """ player_types = ["reasonable", "reasonable"] # # player_types = ["default", "generous"] # # player_types = ["super-selfish", "super-selfish"] # # player_types = ["selfish", "reasonable"] # # player_types = ["selfish", "selfish"] # # player_types = ["reasonable", "selfish"] # # player_types = ["selfish", "super-selfish"] # # player_types = ["super-selfish", "reasonable"] # # player_types = ["super-selfish", "generous"] # # player_types = ["selfish", "default"] # 8/10, all S # player_types = ["selfish", "generous"] # 5/10, all S # player_types = ["generous", "generous"] # 0/10 # player_types = ["reasonable", "reasonable"] # 0/10 board = Board((6, 6), { "hut": cost_of_hut, "station": cost_of_station }, ntrees=ntrees) deck = Deck({"garden": ngardens, "curse": ncurses}) g = Game(board, deck, verbose=verbose) ps = get_players(player_types) ss = [] ws = [] for i in xrange(ngames): status, winner = g.play(ps, print_end_status=False) ss.append(status) ws.append(winner) g.reset() import collections print '==================' print collections.Counter(ws) print collections.Counter(ss)
def list_game(arg): return _format_message( 'list_game', 'ok', {'games': [{ 'id': str(g.key()), 'name': g.title } for g in Game.all()]})
def update_game(game_id: str, timestamp: int, game_info: Game, game_state: str): game_json = game_info.to_json_obj() game_table.update_item( Key={ "id": game_id, "timestamp": timestamp }, UpdateExpression="SET game_state = :new_state, \ current_disasters = :c_disasters, \ previous_disasters = :p_disasters, \ players = :players_info, \ turn_order = :t_order, \ turn_index = :t_index, \ shop = :game_shop, \ discard = :game_discard, \ deck = :game_deck", ExpressionAttributeValues={ ":new_state": game_state, ":c_disasters": game_json["current_disasters"], ":p_disasters": game_json["previous_disasters"], ":players_info": game_json["players"], ":t_order": game_json["turn_order"], ":t_index": game_json["turn_index"], ":game_shop": game_json["shop"], ":game_discard": game_json["discard"], ":game_deck": game_json["deck"], }, )
def create_game(name, description=None, publish_year=None, min_age=None, min_players=None, max_players=None, min_playtime=None, max_playtime=None, image_url=None, msrp=None, atlas_id=None): """Create and return a new game""" game = Game(name=name, description=description, publish_year=publish_year, min_age=min_age, min_players=min_players, max_players=max_players, min_playtime=min_playtime, max_playtime=max_playtime, image_url=image_url, msrp=msrp, atlas_id=atlas_id) db.session.add(game) db.session.commit() return game
def create_new_game(num_players, difficulty, username): """Create new game, create players, and save to DB. Return new game obj. Args: number of players in game, difficulty, and username of player creating the game Returns the new game object""" #Create new Game object new_game = Game(num_players=num_players, difficulty=difficulty) db.session.add(new_game) db.session.commit() game_id = new_game.id #Create new Player object (based on signed in user information) user_info = User.query.filter(User.username == username).first() player = HumanPlayer(user_info.name, user_info.id, game_id, 1) db.session.add(player) opponent_names = { 1: 'Harry (AI)', 2: 'Hermione (AI)', 3: 'Ron (AI)', 4: 'Voldemort (AI)', 5: 'Snape (AI)' } #Create new AI objects for i in range(1, num_players): AI_i = AIPlayer(opponent_names[i], difficulty, game_id, i + 1) db.session.add(AI_i) db.session.commit() return new_game
def get_game_history(self, request): """Get player game history.""" player = User.query(User.name == request.player).get() if not player: raise endpoints.NotFoundException( '{0} does not exist!'.format(request.player) ) games = Game.query( ndb.AND( Game.game_over == True, # noqa ndb.OR( Game.player_one == player.key, Game.player_two == player.key ) ) ) game_histories = [] for game in games: player_one = game.player_one.get() player_two = game.player_two.get() if game.is_forfeit: game_histories.append( GameHistoryForm( game_urlsafe_key=game.key.urlsafe(), player_one=player_one.name, player_two=player_two.name, is_forfeit=game.is_forfeit, winner=game.winner.get().name ) ) else: p1_hands = Hand.query( Hand.game == game.key, Hand.player == player_one.key ) p1_hands = Poker.get_player_start_end_hands(p1_hands) p2_hands = Hand.query( Hand.game == game.key, Hand.player == player_two.key ) p2_hands = Poker.get_player_start_end_hands(p2_hands) game_histories.append( GameHistoryForm( game_urlsafe_key=game.key.urlsafe(), player_one=player_one.name, player_one_start_hand=repr(p1_hands[0]), player_one_end_hand=repr(p1_hands[1]), player_two=player_two.name, player_two_start_hand=repr(p2_hands[0]), player_two_end_hand=repr(p2_hands[1]), is_forfeit=game.is_forfeit, winner=game.winner.get().name ) ) return GameHistoryForms( games=game_histories )
def get_players(game_id): try: game = Game(**games.get(where('uuid') == game_id)) except Exception as err: return {"error": err}, 404 return game.players.dict()
def start_game(game_id): """ Start game! """ try: game = Game(**games.get(where('uuid') == game_id)) except Exception as err: return {"error": err}, 404 status, error = game.start() if status is False: return {"error": error}, 400 games.update(game.dict(), where('uuid') == game_id) return {}
def new_game(): """ Make a new game! """ game = Game.new_game() games.insert(game.dict()) return game
def load_games(api_data, game_modes): """Transferring game data into database""" print("Games") # store json values into temporary dictionary before transferring into DB for game_data in api_data: game_info = create_game_json(game_data) # variables to add to game table game = Game(igdb_id=game_info['game_id'], title=game_info['name'], slug=game_info['slug'], artwork_urls=game_info['artworks'], popularity=game_info['popularity'], screenshot_urls=game_info['screenshots'], release_date=game_info['release_date'], summary=game_info['summary']) if game_info['game_modes']: for mode_name in game_info['game_modes']: mode = game_modes[mode_name] game.game_modes.append(mode) # #################################################3 # for genre_name in game_info['genres']: # genre = game_genres[genre_name] # game.game_genres.append(genre) db.session.add(game) db.session.commit() print(f'Created {game}!')
def get(self): """Send a reminder email to users with a game in progress.""" players = User.query(User.email != None) # noqa for player in players: games = Game.query( ndb.AND( Game.game_over == False, # noqa Game.active_player == player.key ) ) game_keys = ', '.join(game.key.urlsafe() for game in games) number_of_games = games.count() if number_of_games > 0: subject = 'This is a reminder!' body = '''Hey {0}, you have {1} games in progress. It is your turn to make a move in these games! Their url safe keys are: {2}'''.format( player.name, number_of_games, game_keys ) print body mail.send_mail( 'noreply@{}.appspotmail.com'.format( app_identity.get_application_id() ), player.email, subject, body )
def shop(event) -> Dict: if ("game_id" not in event or "game_timestamp" not in event or "player_id" not in event or "room_id" not in event or "x" not in event or "y" not in event or "rotation" not in event): return {} response = game_table.get_item(Key={ "id": event["game_id"], "timestamp": event["game_timestamp"] }) if response["Item"]["game_state"] != "PLAYING": return {} game_info = Game.from_json_obj(response["Item"]) game_info = manager.action_shop( game_info, event["player_id"], event["room_id"], event["x"], event["y"], event["rotation"], ) update_game(event["game_id"], event["game_timestamp"], game_info, "PLAYING") return { "player_id": event["player_id"], "game_id": event["game_id"], "game_timestamp": event["game_timestamp"], }
def create_game(current_user): data = request.get_json() now_time = datetime.datetime.now() # start_time = datetime.datetime.strptime( # data['start_time'], "%Y-%m-%d %H:%M:%S") blackone_id = data['opponent'][0]['name'] whiteone_id = data['opponent'][1]['name'] blacktwo_id = data['opponent'][2]['name'] whitetwo_id = data['opponent'][3]['name'] new_game = Game(name=data['name'], comment=data['comment'], start_time=now_time, blackone_id=blackone_id, blacktwo_id=blacktwo_id, whiteone_id=whiteone_id, whitetwo_id=whitetwo_id, total_time=int(data['total_time']) * 60, public=data['public'], password=data['password'], status='未开始', create_date=now_time, user_id=current_user.id) db.session.add(new_game) db.session.commit() return jsonify({'message': "对局创建成功!"})
def load_games(): """Load games from ign.csv into database.""" print "Games" Game.query.delete() # Start with a fresh database with open('seed_data/ign.csv') as csvfile: game_data = reader(csvfile, dialect='excel') next(game_data) # Skips header row # ID(0), descriptive score(1), title(2), ign URL(3), platform(4), # critic score(5), genre(6), editors choice(7), year(8), month(9), day(10) for row in game_data: title = row[2] platform = row[4] critic_score = row[5] game = Game(title=title, platform=platform, critic_score=critic_score) db.session.add(game) db.session.commit()
def get(self,game_id=None): user = users.get_current_user() template = jinja_environment.get_template('game.html') if not game_id: self.response.write("You need to have a game_id") return try: game = Game.get_by_id(int(game_id)) if not game: raise Exception("No table retrieved") except Exception as e: self.response.write("invalid table_id specified") return # player = Player.query(ndb.AND(Player.game_id == int(game_id),Player.player_id == user.user_id())) # player = ndb.gql('SELECT * From Player') for player in game.players: if player.player_id == user.user_id(): result = player values = { 'game' : game, 'curr_player' : result, 'user_id' : user.user_id(), } self.response.out.write( template.render(values) )
def get_user_games(self, request): """Retrieves all active games for a given user""" user = User.query(User.user_name == request.user_name).get() if not user: raise endpoints.NotFoundException("That user does not exist") games = Game.query(user.key == Game.user_name).filter( Game.over == False) return GameList(games=[game.to_form() for game in games])
def cmd_lastgame(self, c, e): games = Game.find().sort('created_at', -1) if not games: self.send_msg(message.general.no_games_played) return g = games[0] self.send_msg(message.general.last_game, admin=g.admin, map=g.map, server=g.server, \ time=datetime.datetime.strftime(g.created_at, "%I:%M:%S %p, %A %d %B")) #22:57:00, Friday 4 December
def post(self): user = users.get_current_user() if not user: raise Exception("Anonymous not allowed") game = Game.get_by_key_name(user.user_id()) if not game: raise Exception("No game for user %s" % user.user_id()) print self.request.get("setup")
def post(self): user = users.get_current_user() if not user: self.redirect("/") else: game = Game.get_by_key_name(user.user_id()) if game: self.redirect("/play") else: scenario_name = self.request.get("scenario") historical = self.request.get("historical") game = Game( key_name=user.user_id(), player=user, scenario=scenario_name, historical=(historical == "on") ) s = scenario.get_scenario(scenario_name) s.setup(game) game.put() self.redirect("/play")
def get(self): user = users.get_current_user() if not user: raise Exception("Anonymous not allowed") game = Game.get_by_key_name(user.user_id()) if not game: raise Exception("No game for user %s" % user.user_id()) s = scenario.get_scenario(game.scenario) self.response.out.write(json.dumps(s.starting_pieces()))
class game_loop(): def __init__(self): self.game = Game() self.done = False self.state = None self.states = [] self.moves = [] self.rewards = [] self.generate_choices() def generate_choices(self): self.choices = [ i for i, x in enumerate(self.game.post_states()) if x is not None ] if self.game.end: self.done = True self.state = None else: self.state = np.array(self.game.grid) def move(self, scores): if self.done: return scores = scores[self.choices] scores /= scores.sum() chosen_move = np.random.choice(self.choices, p=scores) chosen_reward = self.game.move(chosen_move) assert chosen_reward is not None self.states.append(self.state) self.moves.append(chosen_move) self.rewards.append(chosen_reward) self.generate_choices()
def cmd_lastteams(self, c, e): games = Game.find().sort('created_at', -1) if not games: self.send_notice(e.nick, "No previous game found.") return game = games[0] max_players, is_hl = 12, (game.mode == "highlander") if not is_hl: max_players = int(game.mode.split("v")[0]) * 2 teams_groups = dict(map(lambda k: (int(k), getattr(game.teams, k)), iter(game.teams))) teams_message = PickupGame.get_teams_message(game.owner, max_players, teams_groups, is_hl) self.send_msg(message.general.last_teams) self.send_msg(teams_message)
def new_game(self, request): """Start a new five card poker game""" player_one = User.query(User.name == request.player_one).get() player_two = User.query(User.name == request.player_two).get() err_msg = '{0} does not exist!' if not player_one: raise endpoints.NotFoundException( err_msg.format(request.player_one) ) if not player_two: raise endpoints.NotFoundException( err_msg.format(request.player_two) ) game_id = Game.allocate_ids(size=1)[0] game = Poker.new_game(player_one.key, player_two.key, game_id) return game.to_form()
def validate_name(self, gamename ='gamename'): '''validate authentication returns: True if validation is OK ''' self.game_name = self.request.get(gamename) if not self.game_name: self.response.set_status(400) self.response.out.write('variable %s not found' % gamename) return False self.game = Game.get_by_key_name( self.game_name ) if not self.game: self.response.set_status(400) self.response.out.write('game not found %s' % self.game_name) return False return True
def get(self,game_id=None): user = users.get_current_user() template = jinja_environment.get_template('player.html') game = Game.get_by_id(int(game_id)) values = { 'game' : game } for player in game.players: if player.player_id == user.user_id(): self.redirect_to('table',game_id=game_id) self.response.out.write( template.render(values) )
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) else: game = Game.get_by_key_name(user.user_id()) if not game: draw(self.response, "pick-scenario.html", {}) elif game.setup(): draw(self.response, "setup.html", {"nickname": user.nickname()}) elif game.playing(): draw(self.response, "game.html", {"nickname": user.nickname()}) elif game.finished(): # display finished state and let them start again raise Exception("Not Implemented") else: raise Exception("Not Implemented")
def main(): """ Get user input. Update game state. Display updates to user. """ keypad = "adws" game = Game(*map(int, sys.argv[1:])) game.display() while True: get_input = getch("Enter direction (w/a/s/d): ") if get_input in keypad: game.move(keypad.index(get_input)) elif get_input == "q": break else: print("\nInvalid choice.") continue if game.end: game.display() print("You Lose!") break game.display() print("Thanks for playing.")
def get_user_games(self, request): """Get all active user games.""" player = User.query(User.name == request.player).get() if not player: raise endpoints.NotFoundException( '{0} does not exist!'.format(request.player) ) games = Game.query( ndb.AND( Game.game_over == False, # noqa ndb.OR( Game.player_one == player.key, Game.player_two == player.key ) ) ) return GameForms( games=[game.to_form() for game in games] )
def get(self,game_id=None): game = Game.get_by_id(int(game_id)) user = users.get_current_user() player_array = [] for player in game.players: if player.player_id == user.user_id(): result = player else: player_array.append(player.player_id) if len(player_array) == 0: player_array.append(user.user_id()) game.current_turn = random.choice(player_array) result.cards_visible = GameUpdater(game).deal_cards() game.common_cards_visible = [] GameUpdater(game).init_deck() result.put() game.put() self.redirect_to('table',game_id=game_id)
def post(self,game_id=None): user = users.get_current_user() game = Game.get_by_id(int(game_id)) ## need to make a check to see if game exceeds max players game.players_current = game.players_current + 1 player = Player( game_id = int(game_id), player_id = user.user_id(), name = self.request.get('player_name'), tokens = 1000, cards_not_visible = game.deck, ) if not game.current_turn: game.current_turn = user.user_id() player.cards_visible = GameUpdater(game).deal_cards() player.put() game.players.append(player) game.put() self.redirect_to('table',game_id=game_id)
def post(self,game_id=None): # Query the data store and get the approriate playerid # Set that queried data store object and set the appropriate action # Based on that action do the appropriate thing # Play # Draw # Fold template = jinja_environment.get_template('action.html') game = Game.get_by_id(int(game_id)) action = self.request.get('Action') user = users.get_current_user() bet = int(self.request.get('bet_field')) for player in game.players: if player.player_id == user.user_id(): result = player if action == 'Play': value = GameUpdater(game).play(result,bet) elif action == 'Draw': value = GameUpdater(game).draw(result) if value == 'Cards' : self.redirect_to('table',game_id=game_id) return elif action == 'Fold': self.redirect_to('clear',game_id=game_id) return values = { 'player' : result, 'game' : game, 'value' : value } self.response.out.write( template.render(values) )
def __init__(self): self.users = Users() self.quests = Quests() self.game = Game()
class DevfestCdhApi(remote.Service): def __init__(self): self.users = Users() self.quests = Quests() self.game = Game() """ Users """ @endpoints.method(message_types.VoidMessage, UsersCollection_m, path='user', http_method='GET', name='users.list') def users_list(self, unused_request): usrs = self.users.list() logging.info(usrs) return usrs QUERY = endpoints.ResourceContainer( message_types.VoidMessage, query=messages.StringField(1, variant=messages.Variant.STRING)) @endpoints.method(QUERY, UsersCollection_m, path='userSearch/{query}', http_method='GET', name='users.search') def users_search(self, request): try: return self.users.search(request.query) except (IndexError, TypeError): raise endpoints.NotFoundException('User %s not found.' % (request.id)) ID_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT64)) @endpoints.method(ID_RESOURCE, User_m, path='user/{id}', http_method='GET', name='users.getUser') def user_get(self, request): try: return self.users.search(request.id) except (IndexError, TypeError): raise endpoints.NotFoundException('User %s not found.' % (request.id)) MULTIPLY_METHOD_RESOURCE_QUEST = endpoints.ResourceContainer( user_id=messages.IntegerField(2, variant=messages.Variant.INT64, required=True), faction_id=messages.IntegerField(3, variant=messages.Variant.INT64, required=True) ) @endpoints.method(MULTIPLY_METHOD_RESOURCE_QUEST, User_stats_m, path='userStats/{user_id}', http_method='GET', name='users.getUserStats') def user_stat(self, request): try: return self.users.get_stats(self.game, request.user_id, request.faction_id) except (IndexError, TypeError): raise endpoints.NotFoundException('User %s not found.' % (request.id)) MULTIPLY_METHOD_RESOURCE = endpoints.ResourceContainer(User_m) # , # name=messages.StringField(2, variant=messages.Variant.STRING, # required=True)) @endpoints.method(MULTIPLY_METHOD_RESOURCE, User_m, path='user', http_method='POST', name='users.addUser') def user_add(self, request): return self.users.create(request.name, request.email) #, request.faction) #return User(name=request.name) #* request.name MULTIPLY_METHOD_RESOURCE_FACTION = endpoints.ResourceContainer( user_id=messages.IntegerField(2, variant=messages.Variant.INT64, required=True), faction_id=messages.IntegerField(3, variant=messages.Variant.INT64, required=True) ) @endpoints.method(MULTIPLY_METHOD_RESOURCE_FACTION, User_m, path='setFraction/{user_id}', http_method='POST', name='users.setFaction') def user_set_fraction(self, request): return self.users.set_faction(self.game, request.user_id, request.faction_id) @endpoints.method(ID_RESOURCE, User_m, path='user/{id}', http_method='DELETE', name='users.delUser') def user_delete(self, request): try: return self.users.delete(request.id) except (IndexError, TypeError): raise endpoints.NotFoundException('User %s not found.' % (request.id,)) """ User Quests """ MULTIPLY_METHOD_RESOURCE_QUEST = endpoints.ResourceContainer( user_id=messages.IntegerField(2, variant=messages.Variant.INT64, required=True), quest_id=messages.IntegerField(3, variant=messages.Variant.INT64, required=True) ) @endpoints.method(ID_RESOURCE, SolvedQuestsCollection_m, path='userPoints/{id}', http_method='GET', name='users.getPoints') def user_get_points(self, request): # try: return self.users.get_points(request.id) # except (IndexError, TypeError): # raise endpoints.NotFoundException('User %s not found.' % # (request.id)) @endpoints.method(ID_RESOURCE, SolvedQuestSum_m, path='userPointsSum/{id}', http_method='GET', name='users.getPointsSum') def user_get_points_sum(self, request): try: return self.users.get_points_sum_m(request.id) except (IndexError, TypeError): raise endpoints.NotFoundException('User %s not found.' % (request.id)) MULTIPLY_METHOD_RESOURCE_POINTS = endpoints.ResourceContainer( user_id=messages.IntegerField(2, variant=messages.Variant.INT64, required=True), points=messages.IntegerField(3, variant=messages.Variant.INT64, required=True) ) @endpoints.method(MULTIPLY_METHOD_RESOURCE_POINTS, SolvedQuest_m, path='givePoints/{user_id}', http_method='POST', name='users.givePoints') def user_give_points(self, request): return self.users.add_points(request.user_id, request.points) @endpoints.method(MULTIPLY_METHOD_RESOURCE_QUEST, SolvedQuest_m, path='questSolved/{user_id}', http_method='POST', name='users.questSolved') def user_quest_solved(self, request): try: return self.users.solve_quest(request.user_id, request.quest_id) except: raise endpoints.ForbiddenException('Quest solved or not in faction') """ Quests """ @endpoints.method(message_types.VoidMessage, QuestsCollection_m, path='quest', http_method='GET', name='quests.list') def quests_list(self, unused_request): return self.quests.list() ID_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT64) ) @endpoints.method(ID_RESOURCE, QuestsCollection_m, path='freactionQuest/{id}', http_method='GET', name='quests.listFractionQuests') def quests_list_fraction(self, request): return self.quests.list_by_fraction(request.id) ID_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT64) ) @endpoints.method(ID_RESOURCE, Quest_m, path='quest/{id}', http_method='GET', name='quests.getQuest') def quest_get(self, request): try: return self.quests.get(request.id) except (IndexError, TypeError): raise endpoints.NotFoundException('Quest %s not found.' % (request.id)) MULTIPLY_METHOD_RESOURCE = endpoints.ResourceContainer(Quest_m) # , # name=messages.StringField(2, variant=messages.Variant.STRING, # required=True)) @endpoints.method(MULTIPLY_METHOD_RESOURCE, Quest_m, path='quest', http_method='POST', name='quests.addQuest') def quest_add(self, request): return self.quests.create(request.name, request.factionId, request.points, request.num) #return User(name=request.name) #* request.name @endpoints.method(ID_RESOURCE, Quest_m, path='quest/{id}', http_method='DELETE', name='quests.delQuest') def quest_delete(self, request): try: return self.quests.delete(request.id) except (IndexError, TypeError): raise endpoints.NotFoundException('Quest %s not found.' % (request.id,)) """ Game """ @endpoints.method(message_types.VoidMessage, FactionStats_m, path='stats', http_method='GET', name='faction.Stats') def faction_stats_get(self, request): # try: return self.game.stats() # except (IndexError, TypeError): # raise endpoints.NotFoundException('Quest %s not found.') ID_RESOURCE = endpoints.ResourceContainer( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT64)) @endpoints.method(ID_RESOURCE, FactionFull_m, path='factionHiring/{id}', http_method='GET', name='faction.hiring') def faction_hiring(self, request): # try: return self.game.faction_hiring(request.id) # except (IndexError, TypeError): # raise endpoints.NotFoundException('Quest %s not found.') LIMIT = endpoints.ResourceContainer( message_types.VoidMessage, limit=messages.IntegerField(1, variant=messages.Variant.INT64)) @endpoints.method(LIMIT, Leaderboard_m, path='leaderboard/{limit}', http_method='GET', name='leaderboard.get') def leaderboard_get(self, request): try: return self.game.leaderboard(request.limit) except (IndexError, TypeError): raise endpoints.NotFoundException('Quest %s not found.') VALUE = endpoints.ResourceContainer( message_types.VoidMessage, value=messages.IntegerField(1, variant=messages.Variant.INT64)) @endpoints.method(VALUE, FactionMinPoints_m, path='factionMinPoints', http_method='POST', name='faction.minPoints') def faction_min_points(self, request): # try: return self.game.set_min_faction_points(request.value) # except (IndexError, TypeError): # raise endpoints.NotFoundException('Quest %s not found.') @endpoints.method(message_types.VoidMessage, FactionMinPoints_m, path='factionMinPoints', http_method='GET', name='faction.getMinPoints') def faction_get_min_points(self, ususedRequest): return self.game.get_min_faction_points_m()