Beispiel #1
0
def generate_fake_date():
    form = dict(username='******', password='******')
    u = User.register(form)

    form = dict(title='all')
    b = Board.new(form)

    form = dict(title='test')
    b = Board.new(form)

    form = dict(
        title='test',
        content='test',
        receiver='123',
        receiver_id=1,
        sender_id=1,
    )
    m = Mail.new(form)

    form = dict(
        title='test',
        content='test',
        user_id=1,
    )
    t = Topic.new(form)

    form = dict(
        content='test',
        user_id=1,
        topic_id=1,
    )
    r = Reply.new(form)

    form = dict(title='重置了数据库', )
    u = Update.new(form)
Beispiel #2
0
    def __init(self):
        ''' Initialisation of game '''

        # Create and display map
        self.board = Board(self)

        # Create game window
        self.py.create_screen(self.board.map_size)

        # Load Images for building the interface and characters
        self.py.load_image()

        # Print the map on screen
        self.py.display_map(self.board.map_size, self.board.paths)

        # Add characters to the board
        self.board.add_sprites()

        # Play game music in infinite loop
        self.py.sounds["game_music"].play(-1)

        self.win = False
        self.loose = False

        self.__start()
Beispiel #3
0
def generate_fake_date():
    form = dict(
        username='******',
        password='******',
    )
    u = User.register(form)

    form = dict(
        username='******',
        password='******',
    )
    u = User.register(form)

    form = dict(title='Null')
    b = Board.new(form)

    form = dict(title='Test')
    b = Board.new(form)

    with open('markdown_demo.md', encoding='utf8') as f:
        content = f.read()
    topic_form = dict(title='markdown demo', board_id=b.id, content=content)

    for i in range(5):
        log('begin topic <{}>'.format(i))
        t = Topic.new(topic_form, u.id)

        reply_form = dict(
            content='reply test',
            topic_id=t.id,
        )
        for j in range(5):
            Reply.new(reply_form, u.id)
Beispiel #4
0
class BoardController:
  def __init__(self):
    self.board = Board(None)
    self.view  = ConsoleBoardView(self.board)

  def init_game(self):
  #  self.white_player = Core1Player(Board.WHITE)
    self.white_player = HumanPlayer(Board.WHITE)
    self.black_player = Core2Player(Board.BLACK)
  #  self.black_player = RandomPlayer(Board.BLACK)
    self.atual_player = self.black_player

    finish_game = 0

    self.view.update_view()
    

    while finish_game != 2:
      #raw_input("")
      atual_color = self.atual_player.color
      print 'Jogador: ' + atual_color +' ('+ self.atual_player.name() +')'

      if self.board.valid_moves(atual_color).__len__() > 0:
        self.board.play(self.atual_player.play(self.board.get_clone()), atual_color)
        self.view.update_view()
        finish_game = 0
      else:
        print 'Sem movimentos para o jogador: ' + atual_color
        finish_game += 1
      self.atual_player = self._opponent(self.atual_player)

    return self._end_game()


  def _end_game(self):
    score = self.board.score()
    print ''
    print'-----------------PLACAR DESTA RODADA---------------------'
    print self.white_player.name() , " = " , score[0]
    print self.black_player.name() , " = " , score[1]
    if score[0] > score[1]:
      print ""
      print 'Jogador ' + self.white_player.name() + ' Ganhou'
      return 1
    elif score[0] < score[1]:
      print ""
      print 'Jogador ' + self.black_player.name() + ' Ganhou'
      return 2
    else:
      print ""
      print 'Jogo terminou empatado'
      return 0
    print'---------------------------------------------'
    
    
  def _opponent(self, player):
    if player.color == Board.WHITE:
      return self.black_player

    return self.white_player
Beispiel #5
0
def new():
    u = current_user()
    if u is not None and u.role == 1:
        boards = Board.all()
    else:
        boards = Board.all_not_hide()
    return render_template("topic/new.html", boards=boards, u=u)
Beispiel #6
0
def generate_fake_date():
    form = dict(
        username='******',
        password='******'
    )
    u = User.register(form)

    form = dict(
        username='******',
        password='******',
    )
    g = User.register(form)

    form = dict(
        title='all'
    )
    b = Board.new(form)

    form = dict(
        title='test'
    )
    b = Board.new(form)

    with open('markdown_demo.md', encoding='utf8') as f:
        content = f.read()

    form = dict(
        title='markdown demo',
        board_id=b.id,
        content=content,
    )
    Topic.add(form, u.id)
    Topic.add(form, g.id)
Beispiel #7
0
 def get(self):        
     board = Board()
     keys = board.allKey()        
     _data = board.all(keys)
     print _data
     #self.dumpJson(keys)       
     self.render('manager/board.html',data=_data)
Beispiel #8
0
 def get(self,key):
     user = User()
     
     categroy = Category()       
     user_keys = user.allKey()
     category_keys = categroy.allKey()
     
     _data_user =  user.all(user_keys)
     _data_category = categroy.all(category_keys)        
     data = {}
     if key:
         board = Board()
         board.data = board.get(key)
         data['title']       = board.data['title']
         data['key']         = board.data['key']
         data['user']        = board.data['user']
         data['category']    = board.data['category']
         data['createTime']    = board.data['createTime']
         data['follow']    = board.data['follow']
     else:            
         data['title']       = ''
         data['key']         = ''
         data['user']        = ''
         data['category']    = ''            
     
     self.render('manager/board_new.html',data = data,data_user = _data_user,data_category = _data_category)
Beispiel #9
0
def board_delete():
    board_id = request.args.get('board_id')
    if board_id:
        Board.delete(board_id)
    else:
        pass
    return redirect(url_for('index.board_setting'))
Beispiel #10
0
def index(board_id=None):
    boards = Board.all()
    page = int(request.args.get("page", 1))
    if page < 2:
        former_page = None
    else:
        former_page = page - 1
    sort = request.args.get("sort", "ct")
    if (board_id is None) or (board_id == "5a6b00b965d4400b98bcf605"):
        page_number = Topic.get_page_number()
        board = Board.find_by(_id=ObjectId("5a6b00b965d4400b98bcf605"))
        ms = Topic.find_byPage(page, sort)
    else:
        if len(board_id) < 12:
            pass
        else:
            page_number = Topic.get_page_number(board_id)
            board = Board.find_by(_id=ObjectId(board_id))
            ms = Topic.find_byPage(page, sort, board_id=ObjectId(board_id))
    if page_number == page:
        next_page = None
    else:
        next_page = page + 1
    return render_template("BBS/bbs.html",
                           filter=board,
                           pagenumber=page_number,
                           sort=sort,
                           ms=ms,
                           boards=boards,
                           next_page=next_page,
                           former_page=former_page)
Beispiel #11
0
def add():
    u = current_user()
    if u.username != 'admin':
        return redirect(url_for('index.index'))
    else:
        form = request.form
        Board.new(form)
        return redirect(url_for('.index'))
Beispiel #12
0
def random_init(board: Board, initial_cells: int):
    """ Start board with random cells based on config. """
    cell_ids = list(range(board.size ** 2))
    shuffle(cell_ids)
    for cell in cell_ids[:initial_cells]:
        print(int(cell / board.size), cell % board.size, cell)
        board.make_alive(int(cell / board.size), cell % board.size)
    board.set_grid()
Beispiel #13
0
    def create(self):
        board = Board()
        board_id = board.short_id
        board.id = board_id

        self.boards.insert_one(board.to_mongo())

        return {"board_id": board_id}
 def exec(self, *args):
     try:
         if (len(args) != 1):
             raise BadArgsException
         Board.create(name=args[0], user=self.user)
         self.write('Create board successfully.')
     except BoardAlreadyExistException:
         self.write('Board already exist.')
Beispiel #15
0
def delete_board(board_id, **fields):
    with DBSession() as session:
        assert_can_edit(board_id, session=session)
        board = Board.get(id=board_id, session=session)
        api_assert(not board.board_type == "favorite",
                   "Cannot delete favorite")

        Board.delete(board.id, session=session)
    def __init__(self):
        self.board = Board(None)
        self.view = ConsoleBoardView(self, self.board)

        self.white_player = None
        self.black_player = None
        self.atual_player = None
        self.finish_game = 0
Beispiel #17
0
 def get(self,key):
     uri = self.request.uri
     request = {}
     pin = Pin()
     
     pin_keys = pin.getByKeyValues("board",key)
     pin_count = len(pin_keys)
     
     query = {}
     query['q']         = "board:%s" % key    
             
     query['start']  = "0"
     query['rows']   = globalSetting['max_index_pin_rows']
     query['sort']   = "createTime"
     
     if "page" in uri:
         request = urldecode(uri)
         page = int(request['page'])
         query['start']  = query['rows']*page
         if pin_count < query['rows']*page:
             return ''
     
     pin_data = pin.solr(query)
     print len(pin_data)
     
     marks_dict = pin.formatPins(pin_data)        
     
     if request:
         #print request['callback']
         #print request['page']            
         callback_result = {
                         'filter':'pin:index',
                         'pins':marks_dict
                         }
         
         callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
         self.set_header("Content-Type", "text/html; charset=utf-8")            
         return self.write(callback_response)
     else:
         marks = ''            
         for _mark_t in marks_dict:                
             marks = self.render_string('mark.html',mark=_mark_t)+marks
         board = Board()
         user = User()
         category = Category() 
  
         board_data = board.get(key)
         
         b_user = user.getDetail(board_data['user'])
         b_category = category.get(board_data['category'])
         b_keys = board.getByKeyValues("user", board_data['user'])
         
         if key in b_keys:
             b_keys.remove(key)
             
         b_boards = board.all(b_keys)
     
         self.render('board_pins_list.html',f_board = self.formatFollowBoardData(key), b_boards= b_boards,b_category = b_category,b_user=b_user,user=self.currentUserInfo(),board = board.get(key),marks=marks)
Beispiel #18
0
def add():
    form = request.form
    token = request.args.get('token')
    u = current_user()
    if u.id == 1 and token in csrf_tokens and csrf_tokens[token] == u.id:
        # 验证token和id
        Board.new(form)
        csrf_tokens.pop(token)
    return redirect(url_for('.index'))
Beispiel #19
0
def delete():
    u = current_user()
    if u.role != 1:
        abort(Response('您无权访问此板块'))
    form = request.form
    print(form)
    board_id = int(form.get('board_id', -1))
    Board.delete_self_and_topics(board_id)
    return redirect(url_for('topic.index'))
Beispiel #20
0
def delete(board):
    role = current_user().role
    if role != 1:
        return redirect(url_for('index.index'))
    else:
        b = Board.find_by(title=board)
        b_id = b._id
        Board.delete(b_id)
        return redirect(url_for('.admin'))
Beispiel #21
0
 def test_get_lists_by_board_id(self):
     bid0 = Board.add("board1", "A")
     bid1 = Board.add("board2", "A")
     lid0 = List.add("List0", bid0)
     list0 = List.get(lid0)
     lid1 = List.add("List1", bid1)
     list1 = List.get(lid1)
     assert lid0 in [_list.id for _list in List.get_lists_by_board_id(bid0)]
     assert lid1 not in [_list.id for _list in List.get_lists_by_board_id(bid0)]
Beispiel #22
0
 def __init__(self, white, black, p):
     self.board = Board(None)
     self.white = white
     self.black = black
     self.view = ConsoleBoardView(self.board)
     self.win = 0
     self.p1 = p[0]
     self.p2 = p[1]
     self.p3 = p[2]
Beispiel #23
0
    def test_add_and_get_lists(self):
        bid0 = Board.add("board0", "A")
        board0 = Board.get(bid0)
        bid1 = Board.add("board1", "A")

        lid0 = List.add("list0", bid0)
        lid1 = List.add("list1", bid1)
        assert lid0 in [_list.id for _list in board0.get_lists()]
        assert lid1 not in [_list.id for _list in board0.get_lists()]
Beispiel #24
0
def delete():
    u = current_user()
    if u.is_admin():
        print("debug", u, u.is_admin() )
        id = int(request.args.get('id'))
        Board.delete(id)
        return redirect(url_for(".index"))
    else:
        return redirect(url_for("topic.index"))
    def restart_game(self):
        """Reinicia o jogo Othelo."""
        self.board = Board(None)
        self.view.reiniciar_jogo(self.board)

        self.white_player = None
        self.black_player = None
        self.atual_player = None
        self.finish_game = 0
Beispiel #26
0
def create_boards(board: Board, moves: int, marble: Marble) -> Sequence[Board]:
    boards = set()
    houses_index = board.marble_houses(marble, indexes_seq=True)
    for index in houses_index:
        if board.can_move(index, marble.get_destination(index, moves), marble):
            new_board = board.copy()
            new_board.move_by(index, marble, moves)
            boards.add(new_board)
    return list(boards)
Beispiel #27
0
 def test_add_and_get_users(self):
     bid0 = Board.add("board0", "A")
     board0 = Board.get(bid0)
     uid0 = User.add("test1", "password", "*****@*****.**")
     user0 = User.get(uid0)
     uid1 = User.add("test2", "password", "*****@*****.**")
     user1 = User.get(uid0)
     board0.add_user(user0)
     assert str(uid0) in board0.get_user_ids()
     assert str(uid1) not in board0.get_user_ids()
Beispiel #28
0
def delete():
    id = int(request.args.get('board_id'))
    u = current_user()
    # 判断 token 是否是我们给的
    if u.role == 1:
        print('删除 board 用户是', u, id)
        Board.delete(id)
        return redirect(url_for('topic.index'))
    else:
        abort(404)
Beispiel #29
0
def move():  # Computer is always X
    # Get board passed in as a json object
    data = request.data.decode("utf-8")
    board_inplay = json.loads(data)

    # Create board and get next move
    board = Board(board_inplay['board'])
    state, move = board.minimax('X')

    return jsonify({'move': move, 'state': state})
def test_next_gen_with_cells():
    """ Check next_gen with set of cells to check. """
    board = Board(4, 2, 3, 3)
    board.make_alive(1, 1)
    board.set_grid()
    board.cells_to_check = set()
    board.cells_to_check.add((1, 1))
    board.next_gen()
    # single cell should die
    assert not board.get_cell(1, 1).is_alive()
Beispiel #31
0
def board_delete():
    board_id = int(request.args.get('id'))
    u = current_user()
    if u.username == 'admin':
        # print('删除的board_id是', board_id, type(board_id))
        Board.delete(board_id)
        delete_topics_for_board(board_id)

    bs = Board.all()
    return render_template('admin/manage_board.html', bs=bs, administrator=u)
Beispiel #32
0
    def edit_board(self, board, headers):
        try:
            # Checking if the token is valid or not
            payload = JwtHandler.decode_auth_token(headers['Authorization'])
            if (payload):
                # Creating a board object
                board_obj = Board()
                board_obj.user_id = payload['sub']
                board_obj.name = board['name']
                board_obj.board_id = board['board_id']
                board_obj.description = board['description']
                board_obj.color = board['color']
                board_obj.image = board['image']
                # Checking if the image is being passed or not
                if (board['image'] and len(board['image']) > 0):
                    # Storing the image in Amazon S3 bucket
                    amazon_s3_handler = AmazonS3Handler()
                    board_obj.image = amazon_s3_handler.store_in_S3(
                        board['image'], board['board_id'])

                # Updating the board
                boards_collection = self.__get_board_collection()
                query = {'_id': ObjectId(board_obj.board_id)}
                updated_values = {"$set": board_obj.__dict__}
                boards_collection.update_one(query, updated_values)

                # Closing the DB connection
                self.mongo_db.disconnect()

                return board_obj
            else:
                return "Invalid Authorization"

        except Exception as exception:
            raise exception
Beispiel #33
0
def board():
    user = current_user()
    if user is not None and user.is_administartor():
        if request.method == 'POST':
            form = request.form
            new_board = Board.new(form)
            new_board.hold()
        boards = Board.all()
        return render_template('admin/board.html', boards=boards)
    else:
        return redirect(url_for('index.index'))
Beispiel #34
0
def main():
    reset_database()

    User.new(username='******',
             password='******',
             role=UserRole.admin,
             avatar='/user/avatar/4.jpg')

    Board.new(title='good', )

    Board.new(title='share', )
Beispiel #35
0
 def __init__(self, app_ref):
     super().__init__(app_ref)
     self.current_player_label = Label(self, '', 20)
     self.current_player_checker_label = Button(self, '')
     self.current_player_checker_label.config(state=tk.DISABLED, width=5)
     self.max_depth_label = Label(self, '', 12)
     self.board = Board(self)
     self.players: {PlayerType: Player} = {
         PlayerType.COMPUTER: Player(self, PlayerType.COMPUTER, self.board.blue_checkers),
         PlayerType.USER: Player(self, PlayerType.USER, self.board.orange_checkers)
     }
Beispiel #36
0
    def get(self):
        uri = self.request.uri
        request = {}
        board = BoardFollow()
        
        #in_keys = board.allKey()
        user_key = self.get_secure_cookie("user_key")
        query = {}
        query['q']         = "user:%s" % user_key
                
        query['start']  = "0"
        query['rows']   = globalSetting['max_index_board_rows']
        query['sort']   = "follow"
        
        if "page" in uri:
            request = urldecode(uri)
            page = int(request['page'])
            query['start']  = query['rows']*page
            #if pin_count < query['rows']*page:
            #    return ''
        
        board_data = board.solr(query)
        #print len(board_data)

        boards_dict = board.formatBoards(board_data)
        
        if request:
            #print request
            callback_result = {
                            'filter':'board:index',
                            'boards':boards_dict
                            }
            
            callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
            self.set_header("Content-Type", "text/html; charset=utf-8")            
            return self.write(callback_response)
        else:
            boards = ''            
            for _board_t in boards_dict:                
                boards = self.render_string('board_unit.html',board=_board_t) + boards
                
            user_key = self.get_secure_cookie("user_key")
            user = User()
            userInfo = user.getDetail(user_key)
            from models.userFollow import UserFollow
            userFollow = UserFollow()
            counts = {}
            pinM = Pin()
            boardM = Board()
            counts['fans'] = len(userFollow.getByKeyValues("follow", user_key)) 
            counts['pins'] = len(pinM.getByKeyValues("user", user_key)) 
            counts['boards'] = len(boardM.getByKeyValues("user", user_key)) 
            
            self.render('board_follow.html',counts=counts,userInfo = userInfo,user=self.currentUserInfo(),boards=boards) 
def test_next_gen_without_cells():
    """ Check next_gen checking all cells. """
    board = Board(4, 2, 3, 3)
    board.make_alive(1, 1)
    board.set_grid()
    board.next_gen()
    # single cell should die
    assert not board.get_cell(1, 1).is_alive()
Beispiel #38
0
    def Play(request):
        # FIXME: Data sent from client is not JSON.
        # Figure out how to actually send json.
        cell = eval(request.request.json["cell"])
        row, column = cell["location"]
        grid = eval(request.request.json["grid"])
        flag_event = request.request.json.get("flag_cell")

        board = Board(grid)
        board.handle_move(row, column, flag_event)

        return {"grid": board.grid, "winner": board.winner}
Beispiel #39
0
    def test_add_and_get_boards(self):
        cid = User.add("test_user1", "password", "*****@*****.**")
        user = User.get(cid)

        bid0 = Board.add("board1", "A")
        bid1 = Board.add("board2", "A")
        board0 = Board.get(bid0)
        board1 = Board.get(bid1)
        user.add_board(board0)

        assert str(bid0) in user.get_board_ids()
        assert str(bid1) not in user.get_board_ids()
def test_next_gen_with_bad_cell_to_check():
    """ Check next_gen with set of cells to check. """
    board = Board(4, 2, 3, 3)
    board.make_alive(1, 1)
    board.set_grid()
    board.cells_to_check = set()
    board.cells_to_check.add((10, 10))
    with pytest.raises(IndexError):
        board.next_gen()
Beispiel #41
0
def api_board(board_id=None):
    print "=======", request.form
    try:
        title = request.form['title']
    except:
        return jsonify({'code':400, 'message':'Invalid Request'})

    board_id = Board.add(title,'A')
    board = Board.get(board_id)
    board.add_user(current_user)
    current_user.add_board(board)
    List.add("To Do", board_id)
    List.add("Doing", board_id)
    List.add("Done", board_id)
    return jsonify({'board_id':board_id})
Beispiel #42
0
 def get(self,key):
     user_key = self.get_secure_cookie("user_key")
         
     board  = Board()
     query = {}
     query['q'] = "user:%s" % user_key            
     _data = board.solr(query)  
     
     thumb = Thumb()        
     pic = Pic() 
     
     pic_url = pic.get(key)['url']
     thumb_url = thumb.get(key)['url']
     
     self.render('repin.html',boards = _data,pic_url=pic_url,thumb_url=thumb_url)
Beispiel #43
0
    def test_get_comments_by_card_id(self):
        uid0 = User.add("test1", "password", "*****@*****.**")
        bid0 = Board.add("board1", "A")
        bid1 = Board.add("board2", "A")
        aid0 = Activity.add(bid0, uid0, "BLABLA")
        aid1 = Activity.add(bid0, uid0, "LA")
        aid2 = Activity.add(bid1, uid0, "HULA")

        activity0 = Activity.get(aid0)
        activity1 = Activity.get(aid1)
        activity2 = Activity.get(aid2)

        assert aid0 in [activity.id for activity in Activity.get_all(bid0)]
        assert aid1 in [activity.id for activity in Activity.get_all(bid0)]
        assert aid2 not in [activity.id for activity in Activity.get_all(bid0)]
        assert aid2 in [activity.id for activity in Activity.get_all(bid1)]
Beispiel #44
0
 def test_get_user_ids(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert str(uid0) in [user_id for user_id in card.get_user_ids()]
Beispiel #45
0
    def get(self, text_id):
        try:
            board = Board.get_board_by_text_id(text_id)
        except NoResultFound:
            return abort(404)

        #last_post = Post.query.order_by(Post.id.desc()).limit(1).subquery()
        #last_post_alias = aliased(Post, last_post)
        # threads = db.session.query(Thread, last_post_alias).filter_by(board_id=board.id).join(last_post_alias, Thread.id == last_post_alias.thread_id).order_by(Thread.id.desc()).all()
        threads = db.session.query(Thread).filter_by(board_id=board.id).order_by(Thread.id.desc()).all()

        #threads = db.session.query(Thread, Post)\
        #    .filter_by(board_id=board.id)\
        #    .order_by(Thread.id.desc())\
        #    .join(Post, Thread.id == Post.thread_id)\
        #    .all()

        #print(db.session.query(Thread, Post)
        #      .filter_by(board_id=board.id)
        #      .order_by(Thread.id.desc())
        #      .join(Post, Thread.id == Post.thread_id).statement)

        #for thread in threads:
        #    print(thread.__dict__)

        return render_template("forum_threads_view.jinja2", board=board, title=board.name, can_post=True,
                               threads=threads)
Beispiel #46
0
    def get(self):
        user = users.get_current_user()

        if user:
            # Filter by the google appengine user id property.
            active_user = User.query(User.google_id == user.user_id()).fetch(1)

            if not active_user:
                # If we couldn't find a user it means that is the first time it uses the application.
                # We just need to create a new entity with the get_current_user() information.
                active_user = User(email=user.email(), username=user.nickname(), google_id=user.user_id())
                active_user.put()
                logging.info("New user created. Email address is: %s", active_user.email)
            else:
                active_user = active_user[0]

            token = channel.create_channel(str(active_user.key.id()))
            memcache.add(key=str(active_user.key.id()), value=token)

            template_vars = {
                'user': active_user,
                'token': token,
                'logout_url': users.create_logout_url('/welcome'),
                'boards': Board.query().order(Board.created_at)

            }
            template = JINJA_ENVIRONMENT.get_template('root.html')
            self.response.write(template.render(template_vars))
        else:
            self.redirect('/welcome')
Beispiel #47
0
 def test_get_cards_by_list_id(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert card_id in [card.id for card in Card.get_cards_by_list_id(lid0)]
class BoardController:
  def __init__(self):
    self.board = Board(None)
    self.view  = ConsoleBoardView(self.board)

  def init_game(self):
    self.white_player = CornerPlayer(Board.WHITE)
    self.black_player = RandomPlayer(Board.BLACK)
    self.atual_player = self.black_player

    finish_game = 0

    self.view.update_view()

    while finish_game != 2:
      raw_input("")
      atual_color = self.atual_player.color
      print 'Jogador: ' + atual_color
      if self.board.valid_moves(atual_color).__len__() > 0:
        self.board.play(self.atual_player.play(self.board.get_clone()), atual_color)
        self.view.update_view()
        finish_game = 0
      else:
        print 'Sem movimentos para o jogador: ' + atual_color
        finish_game += 1
      self.atual_player = self._opponent(self.atual_player)

    self._end_game()


  def _end_game(self):
    score = self.board.score()
    if score[0] > score[1]:
      print ""
      print 'Jogador ' + Board.WHITE + ' Ganhou'
    elif score[0] < score[1]:
      print ""
      print 'Jogador ' + Board.BLACK + ' Ganhou'
    else:
      print ""
      print 'Jogo terminou empatado'

  def _opponent(self, player):
    if player.color == Board.WHITE:
      return self.black_player

    return self.white_player
Beispiel #49
0
 def test_add_and_get(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     aid0 = Activity.add(bid0, uid0, "BLABLA")
     activity0 = Activity.get(aid0)
     assert bid0 == activity0.board_id
     assert uid0 == activity0.user_id
     assert "BLABLA" == activity0.content
Beispiel #50
0
 def test_set_and_get_card(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert card.title == 'card0'
     assert card.list_id == lid0
Beispiel #51
0
 def test_get_and_test_description(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     card.set_description('desc')
     assert 'desc' in card.get_description()
Beispiel #52
0
 def get(self,key):        
     res = {}         
     user_key = self.get_secure_cookie("user_key")
     b_key = "%s%s" % (user_key,key)
     
     boardFollow = BoardFollow()
     
     if boardFollow.get(b_key):
         res['code'] = 1
         res['msg'] = "您已关注过了"
     else:
         board = Board()
         board.key = key
         board.data =  board.get(key)
         board.data['follow'] = int(board.data['follow']) + 1
         board.put()            
         boardFollow.key = b_key
         
         boardFollow.data['user'] = user_key
         boardFollow.data['board'] = key
         boardFollow.data['createTime'] = int(time.time())
         boardFollow.post()
         res['code'] = 0
         res['msg'] = "成功"
         print res                
     res_str = json.dumps(res)
     self.write(res_str)
Beispiel #53
0
    def get(self, board_text_id):
        try:
            board = Board.get_board_by_text_id(board_text_id)
        except NoResultFound:
            return abort(404)

        form = ThreadPostForm()

        return render_template("forum_thread_post.jinja2", board=board, form=form)
Beispiel #54
0
 def incr_decr_get_comment(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     Card.incr_comment(card_id)
     assert 1 == card.get_comment_count()
     Card.desc_comment(card_id)
     assert 0 == card.get_comment_count()
Beispiel #55
0
 def test_add_and_get(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     caid0 = Card.add("card1", lid0, uid0)
     coid0 = Comment.add(caid0, uid0, "comment1")
     comment0 = Comment.get(coid0)
     assert caid0 == comment0.card_id
     assert uid0 == comment0.user_id
     assert "comment1" == comment0.content
Beispiel #56
0
    def get(self):
        uri = self.request.uri
        request = {}
        board = Board()
        
        pin_keys = board.allKey()
        
        query = {}
        query['q']         = "public:1"
                
        query['start']  = "0"
        query['rows']   = globalSetting['max_index_board_rows']
        query['sort']   = "follow"
        
        if "page" in uri:
            request = urldecode(uri)
            page = int(request['page'])
            query['start']  = query['rows']*page
            #if pin_count < query['rows']*page:
            #    return ''
        
        board_data = board.solr(query)
        print len(board_data)

        boards_dict = board.formatBoards(board_data)
        
        if request:
            #print request
            callback_result = {
                            'filter':'board:index',
                            'boards':boards_dict
                            }
            
            callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
            self.set_header("Content-Type", "text/html; charset=utf-8")            
            return self.write(callback_response)
        else:
            boards = ''            
            for _board_t in boards_dict:                
                boards = self.render_string('board_unit.html',board=_board_t) + boards
            
            self.render('board_pop.html',user=self.currentUserInfo(),boards=boards)    
Beispiel #57
0
 def formatBoards(self,board_data):
     data = []
     boardModel = Board()
     for board in board_data:
         #print "******************"
         _board = {}
         _board =  boardModel.get(board['board'])  
             
         _board['pin_pics'] = []
         board_pins_max = 9
         i = 0
         for pin_key in _board['pins']:
             thumb = Thumb()                
             thumb.data = thumb.get(pin_key)
             #print thumb.data
             i = i + 1
             if i <= board_pins_max and thumb.data:                
                 _board['pin_pics'].append(thumb.data['url'])    
         data.append(_board)      
     return data   
Beispiel #58
0
 def getPinDetail(self,key):        
     board = Board()
     user = User()
     thumb = Thumb()        
     pic = Pic()        
     comment = Comment()    
     
     marks_dict = []
     pin = self.get(key)
     _pin = {}
     _pin['pin']               = self.get(key)
     _pin['user']              = user.getDetail(pin['user'])
     _pin['pin']['pic']        = pic.get(pin['key'])['url']
     
     
     _pin['board']             = board.getDetailWithPinThumb(pin['board']) 
     
     _pin['comments']         = comment.getByPin( pin['key'])           
         
     return _pin
Beispiel #59
0
def index():
    # board_id = 2
    board_id = int(request.args.get('board_id', -1))
    if board_id == -1:
        ms = Topic.all()
    else:
        ms = Topic.find_all(board_id=board_id)
    token = str(uuid.uuid4())
    u = current_user()
    csrf_tokens['token'] = u.id
    bs = Board.all()
    return render_template("topic/index.html", ms=ms, token=token, bs=bs, bid=board_id, user=u)