def handle_my_custom_event(json, methods=['GET', 'POST']): print('received my event: ' + str(json)) room = session.get('session_id') socketio.emit('my response', json, callback=messageReceived, room=room) gameSession = db.fetchOne({'_id': ObjectId(room)}) gameSession['messages'].append(json) db.updateOne({'_id': ObjectId(room)}, {'$set': { 'messages': gameSession['messages'] }})
def do_PUT(self): # Look for PUT request if re.match(r'\/product\/\d+', self.path): length = int(self.headers.getheader('content-length')) # Get form data postvars = urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1) # Init data name = postvars.get('name')[0] desc = postvars.get('description')[0] price = float(postvars.get('price')[0]) # Send request to DB db.updateOne(re.search(r'[^/]*$', self.path).group(0), name, desc, price) # Send code 200 self.send_response(200) self.end_headers()
def handle_board_state_change(json, methods=['GET', 'POST']): print('received board state: ' + str(json)) username = session['user_id'] room = session.get('session_id') board_state = session.get('board_state') board_state = { row: { key: { 'color': value['color'], 'piece': value['piece'] } for key, value in sorted(board_state[row].items(), key=lambda item: int(item[0])) } for row in board_state } origin_row = json['origin_cell'][0] origin_col = json['origin_cell'][1] destination_row = json['destination_cell'][0] destination_col = json['destination_cell'][1] unplaced_pieces = session.get('unplaced_pieces') if json['origin_cell'] != ['', '']: board_state[origin_row][origin_col]['piece'] = "" board_state[origin_row][origin_col]['color'] = "none" else: for piece in unplaced_pieces: if piece[0] == json['moved_piece']['piece']: piece[1] -= 1 #if two pieces from different teams collide, do battle def combat(piece1, piece2): # if piece being attacked is a flag, end the game if piece2['piece'] == '#': game_over = True else: game_over = False # determine winning piece if auth.pieces_reference[piece1['piece']].weakness == piece2['piece']: result = piece2 elif auth.pieces_reference[ piece2['piece']].weakness == piece1['piece']: result = piece1 elif auth.pieces_reference[piece1[ 'piece']].rank < auth.pieces_reference[piece2['piece']].rank: result = piece1 elif auth.pieces_reference[piece1[ 'piece']].rank == auth.pieces_reference[piece2['piece']].rank: result = {'piece': "", 'color': 'none'} elif auth.pieces_reference[piece1[ 'piece']].rank > auth.pieces_reference[piece2['piece']].rank: result = piece2 return result, game_over if board_state[destination_row][destination_col]['color'] not in [ 'none', json['moved_piece']['color'] ]: json['moved_piece'], json['game_over'] = combat( json['moved_piece'], board_state[destination_row][destination_col]) print(json) socketio.emit('own combat result', json, room=room) board_state[destination_row][destination_col] = json['moved_piece'] # fetch room info from db gameSession = db.fetchOne({'_id': ObjectId(room)}) # update unplaced pieces record gameSession['unplaced_pieces'][username] = unplaced_pieces current_phase = gameSession['phase'] # sum up total pieces unplaced, change phases if necessary total_pieces = 0 if current_phase == "preparation": for user in gameSession['unplaced_pieces']: for piece in gameSession['unplaced_pieces'][user]: total_pieces += piece[1] # check if both players have entered the game and placed all their pieces if (total_pieces == 0) and (len(gameSession['unplaced_pieces']) == 2): current_phase = "blue" elif current_phase == "blue": current_phase = "red" elif current_phase == "red": current_phase = "blue" try: if json['game_over'] == True: current_phase = json['responsible_team'] + '_wins' except KeyError: pass json['phase'] = current_phase # emit response to clients socketio.emit('my response', json, callback=messageReceived, room=room) # update unplaced pieces record for this player, to be re-inserted in db below gameSession['unplaced_pieces'][username] = unplaced_pieces # update board state, phase, and unplaced pieces records in database db.updateOne({'_id': ObjectId(room)}, { '$set': { 'board_state': board_state, 'unplaced_pieces': gameSession['unplaced_pieces'], 'phase': current_phase } }) # update same attributes from above in user's session cookie session['board_state'], session['unplaced_pieces'], session[ 'phase'] = board_state, unplaced_pieces, current_phase print(board_state)
def enterGame(username=None, password=None): if request.method == 'POST': if username is None: username = request.form['username'] if password is None: password = request.form['password'] error = None session_code = None try: session_code = request.form['session_code'] print('session found: ' + session_code) except: print('no code found') if session_code is None: session_code = get_random_alphaNumeric_string(5) db.createSession({ 'code': session_code, 'users': {}, 'board_state': board.grid, 'phase': 'preparation', 'unplaced_pieces': {}, 'messages': [] }) print('session created: ' + session_code) if username is None: error = 'Please provide a username. You can make one up.' else: gameSession = db.fetchOne({'code': session_code}) session.clear() # check if user exists in current session if username in gameSession['users']: print('existing username found...') session_id, color, phase = gameSession['_id'], gameSession[ 'users'][username]['color'], gameSession['phase'] if not check_password_hash( gameSession['users'][username]['password'], password): error = 'Incorrect password.' else: print('users\n', gameSession['users']) if len(gameSession['users']) == 1: color = 'red' else: color = 'blue' gameSession['users'].update({ username: { 'password': generate_password_hash(password), 'color': color } }) gameSession['unplaced_pieces'].update({ username: [(key, pieces_reference[key].maxQuantity) for key in pieces_reference] }) db.updateOne({'code': session_code}, { '$set': { 'users': gameSession['users'], 'unplaced_pieces': gameSession['unplaced_pieces'] } }) phase = gameSession['phase'] session_id = str(gameSession['_id']) if error is None: session['user_id'], session['session_code'], session[ 'session_id'], session['color'], session[ 'phase'] = username, session_code, session_id, color, phase return redirect(url_for('sessions', id=session_id)) flash(error) return render_template('auth/login.html')