Example #1
0
	def new_game(self, request):
		"""Start a new game"""

		#Check if players have registered
		player1 = User.query(User.name == request.player1).get()
		if not player1:
			raise endpoints.ConflictException('Player 1 must register')
		
		player2 = User.query(User.name == request.player2).get()
		if not player2:
			raise endpoints.ConflictException('Player 2 must register')

		if player1 == player2:
			raise endpoints.ConflictException('Cannot play against oneself')

		#Create new game and put in datastore
		game = Game(player1=player1.key, 
				    player2=player2.key, 
					playerTurn=player1.key,
					game_over=False
				)
		game.put()

		#Create initial game board and set as ancestor of game
		boardId = Board.allocate_ids(size=1, parent=game.key)[0]
		boardKey = ndb.Key(Board, boardId, parent=game.key)

		board = Board(key=boardKey)
		board.put()

		game.state = boardKey
		game.put()

		return StringMessage(message="Game between {0} and {1} created! {2}".format(player1.name, player2.name, game.key))
Example #2
0
def startGame(args, username, channel):
    usernameX = username  # X is the user that ran startGame command

    if (Board.objects.filter(active=True, channel=channel)):
        return generateJsonResponse(
            'There is already an active game in this channel. Please wait til the current game is finished to start a new game. To view current game, use /tictactoe showBoard.',
            error=True)

    if (len(args) < 2):
        return generateJsonResponse(
            'Please specify username of player you would like to play with.',
            error=True)

    usernameO = args[1]  # O is the user that usernameX chose to play with

    playerX = findPlayer(usernameX, channel)
    playerO = findPlayer(usernameO, channel)

    # Create new board for new game.
    board = Board(active=True,
                  channel=channel,
                  playerX=playerX,
                  playerO=playerO)
    board.save()

    return generateJsonResponse(
        'New Tic Tac Toe game between %s and %s!' % (usernameX, usernameO),
        generateBoardWithNextPlayerString(board))
Example #3
0
    def _turn(self, board):
        self.board = Board(board)
        self.history.appendleft(board)
        self.tick()

        for row in range(self.board.n):
            print(self.board.text[self.board.n * row:self.board.n * (row + 1)])

        if self.board.me is None:
            self.reset()
            print("Dead. Do nothing")
            return ''

        self.visualizer.print(f'fc={self.fire_countdown}')
        for tactic in self.tactics:
            tactic.update(self)

        possible_actions = [tactic.action for tactic in self.tactics]
        action_dangerous = [
            self._estimate_action(action) for action in possible_actions
        ]
        self.visualizer.print('\n'.join(
            '{t.__class__.__name__:<14} {t.usability:.2f} {t.action} {d}'.
            format(t=t, d=d) for t, d in zip(self.tactics, action_dangerous)))

        current_tactics = max(self.tactics, key=lambda t: t.usability)
        action = current_tactics.action
        if 'act' in action:
            self.fire_countdown = self.FIRE_COUNTDOWN
        assert isinstance(action, str)
        # return 'right,act'
        return action
class Controller(AbstractController):
    def __init__(self):
        super().__init__()
        pygame.init()
        self._running = True
        self.vis = PyGameVisuals(SIZE_OF_CELL)
        self.board = Board(NUM_ROWS, NUM_COLS, self.vis)

    def app(self, entry_point):
        while self._running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self._running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_s:
                        self.vis.display_text = False
                        self.vis.set_bg = False
                        self.vis.game_running = True
                        self.board.run_game = True
                        self.board.entry_point(entry_point)
                    if event.key == pygame.K_0:
                        self.board.run_game = False
                    if event.key == pygame.K_1:
                        self.board.run_game = True
            self.board.game_of_life()
            if not self.board.run_game:
                self.vis.fill_screen()

        pygame.quit()
Example #5
0
def new(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        file = request.FILES.get('file')
        board = Board(title=title, content=content, file=file)
        board.save()
        return redirect('boards:detail', board.pk)
    else:
        return render(request, 'boards/new.html')
Example #6
0
def createNewBoard(request):
	username = request.GET.get('user')
	role = "Admin"

	board = Board(userid=username,role=role)

	board.save()

	bId = board.boardid

	issuccess = True

	return JsonResponse({'boardId':bId,'issuccess':issuccess})
Example #7
0
    def __init__(self, configuration):
        self.board = Board()

        player1 = Player(self, configuration["name_player1"],
                         configuration["intelligence_player1"])

        player2 = Player(self, configuration["name_player2"],
                         configuration["intelligence_player2"])

        self.players = (player1, player2)
        self.active_player = player1

        self.state = self.STATES["WAIT_SELECTION"]
Example #8
0
def game_insert():
	print("게임 게시판 테스트 데이터 입력 시작...")
	boarname_list = ["던전앤파이터", "메이플스토리","마인크래프트","블레이드소울","어몽어스",
					"검은사막","워크래프트","로스트아크","마비노기","아키에이지",
					"GTA","디아블로","데스티니 가디언즈","피파","lol",
					"오버워치","스타2","리니지M","발더스케이트","서든어택",
					"애니팡","어쌔신크리드","콜오브듀티","킹덤스토리","피파21",
					"다크위시","마구마구","모두의마블","바람의나라연","삼국지",
					"캐슬베인","킹오브파이터올스타","한게임포커"
					]
	for i in range(1,34):

		board = Board()

		board.board_name = f"{boarname_list[i-1]}"
		board.description = f"게시판 설명{i}"
		board.category_id = 1
		board.post_num = 0
		board.board_image = f"{i}.png"
		board.category = Category.query.filter(Category.id == 1).first()
		board.category.board_num += 1

		db.session.add(board)
		db.session.commit()
	print("게임 게시판 테스트 데이터 입력 성공")
Example #9
0
def addBoardView(request):
    if request.method == 'POST':  # se la richiesta e una POST e il form e valido aggiungi board
        user = User.objects.get(username=request.user.username)
        form = AddBoardForm(request.POST)
        form.setUser(user)
        if form.is_valid():
            boardname = form.cleaned_data.get('boardname')
            newBoard = Board(name=boardname)
            newBoard.save()
            newBoard.users.add(user)
            return redirect(newBoard.get_absolute_url())
    else:  # se la richiesta e una GET publica Form vuoto
        form = AddBoardForm()
    return render(request, 'addboard.html', {'form': form})
Example #10
0
def new_board(request):
    board = Board()
    board.radius = Decimal(request.POST['radius'])
    board.lat = Decimal(request.POST['lat'])
    board.lng = Decimal(request.POST['lng'])
    board.name = request.POST['name']
    board.save()
    return redirect('/')
Example #11
0
def write():
    form = WriteSubmitForm()
    board = Board()
    if request.method == 'POST' and form.validate_on_submit():
        request_data = {
            'name': form.name.data,
            'title': form.title.data,
            'content': form.content.data
        }
        board.post(request_data)
        return redirect(url_for('board.get_board'))
    elif request.method == 'POST' and not form.validate_on_submit():
        return make_response(render_template('report/write.html', form=form),
                             400)
    return render_template('report/write.html', **locals())
Example #12
0
    def on_message(self, message):
        data = json.loads(message)
        if "update_type" in data and data["update_type"] == "draw":
          board_id = data["board_id"]
          broadcastData = data
          self.broadcast(board_id, broadcastData, write_to_self=False)
          return
        message_type = data.get('message_type')
        board_id = data["board_id"]

        if message_type and message_type == 'user_update':
            self._update_user(board_id, data['username'])
            self._broadcast_user_display(board_id)
        elif message_type and message_type == 'board_name_update':
            name = self._update_board_name(board_id, data['name'])
            self._broadcast_board_name_update(board_id, name)
        else:
            board = Board.get(board_id)
            item = Item(**data["item"])
            board.updateItem(item)
            board.save()

            broadcastData = {
                "update_type": "pos_change",
                "item": json.loads(item.to_json())
            }
            self.broadcast(board_id, broadcastData, write_to_self=False)
Example #13
0
	def post(self):
		email = self.request.get('email')
		user = User.query(User.email == email).get()
		monsterlist = Monster.query(Monster.user == user.key).fetch()
		if user is not None and monsterlist is not None:
			playlist = []
			for monst in monsterlist:
				dbplay = Player.query(Player.monster == monst.key).get()
				if dbplay is not None:
					playlist.append(dbplay)
			pl = []
			logging.warning(playlist)
			for play in playlist:
				monster = Monster.query(Monster.key == play.monster).get()
				board = Board.get(play.board)
				if monster.properties is None:
					monster.properties = json.dumps({})
				pd = {'key': play.key.urlsafe(), 'monster': {'key': monster.key.urlsafe(), 'name': monster.name, 'properties': json.loads(monster.properties), 'date': str(monster.date)}, 'board': {'key': play.board.urlsafe()}}
				pl.append(pd)

			if user.gamelimit is None:
				user.gamelimit = 1
				user.put()
			logging.warning({'status': 1, 'games': pl, 'gamelimit': user.gamelimit})
			self.response.out.write(json.dumps({'status': 1, 'games': pl, 'gamelimit': user.gamelimit}))
		else:
			self.response.out.write(json.dumps({'status': -1, 'message': 'User not found.'}))
Example #14
0
	def get_game_history(self, request):
		"""Get all moves in game"""

		history = ndb.Key('Game', request.game).get().game_history
		q = Board.query(ancestor=ndb.Key('Game', request.game))

		return multiBoard(items=[self._printBoard(board) for board in q])
Example #15
0
def get_board(board_name, page=1):

    try:
        board = Board.get(Board.name == board_name)
    except:
        abort(404, "This page doesn't exist.")

    current_user = get_current_user(request)

    per_page = int(config['threads.per_page'])

    query = board.posts.where(Post.is_reply == False).order_by(
        Post.pinned.desc(), Post.bumped_at.desc())

    threads = query.paginate(page, per_page)

    return dict(board_name=board.name,
                board_title=board.title,
                threads=threads,
                board=board,
                current_page=page,
                is_detail=False,
                current_user=current_user,
                thread_count=query.count(),
                max_file_size=config['uploads.upload_max_size'],
                maxlength=config['threads.content_max_length'],
                per_page=per_page,
                basename=basename)
Example #16
0
def delete_board(data: dict):
    """
    Try to delete board record from DB.

    Function is called upon DELETE request, checks request
    parameters for required fields, then delete record
    from DB if it exists

    Args:
        data (dict): Parameters from request query and body

    Returns:
        flask.Response with JSON-data regardless of success

    """
    # validate all required fields exists
    for required_field in ["board_url"]:
        if required_field not in data.keys():
            err = f"No '{required_field}' specified"
            return send_error_response(400, err)

    try:
        board_url = str(data["board_url"])
    except Exception as err:
        return send_error_response(400, str(err))

    try:
        # checks if record with such 'board_url' exists in DB
        if not Board.delete({"url": board_url}):
            err = f"Didn't find board with url '{board_url}'"
            return send_error_response(404, err)
    except Exception as err:
        return send_error_response(400, str(err))

    return send_success_response()
Example #17
0
def get_threads(board, page=0, fmt_name="page"):

  _fmt = "thread_" + fmt_name
  if _fmt in globals():
    fmt = globals()[_fmt]
  else:
    fmt = thread_plain


  threads = []

  board_db = Board.get_by_key_name(board)
  if board_db:
    threads = board_db.linked

    if not threads:
      threads = [ (board, th) for th in board_db.thread]

  per_page = get_config('aib.ib', 'thread_per_page')
  threads = threads[per_page*page:per_page*(page+1)]
  logging.info("threadlist in %r : %r" % (board, threads))

  # grab data from cache
  data =  Thread.load_list(threads)

  return [ fmt(th) for th in data if th ]
Example #18
0
def signup():
    """ Sign up user and save credentials """
    form = SignupForm()

    if form.validate_on_submit():
        try:
            user = User.signup(first_name=form.first_name.data,
                               last_name=form.last_name.data,
                               username=form.username.data,
                               password=form.password.data)

            user_board = Board(
                title="General",
                description="A general hodge-podge of articles and ideas")
            user.boards.append(user_board)
            db.session.add(user)
            db.session.commit()
        except IntegrityError:
            flash("Username already taken", "danger")
            return render_template("signup.html", form=form)

        do_login(user)
        return redirect("/")

    else:
        return render_template('signup.html', form=form)
Example #19
0
def bump(boards, thread):

  board_db = Board.get_by_key_name(boards)
  main = boards[0]

  per_page = get_config('aib.ib', 'thread_per_page')
  pages = get_config('aib.ib', 'board_pages')
  threads = per_page * pages

  def hide(linked, board):
    for _board, thread in list(linked):
        if board == _board:
            linked.remove((board, thread))

  add = 0
  for x,(name,board) in enumerate(zip(boards,board_db)):
    if not board:
      board = Board(key_name=name)
      board.linked = []
      board_db[x] = board

    if not board.linked and board.thread:
      board.linked = [
        (board.code, th)
        for th in
        board.thread
      ]

    if main[-1] == '~':
      hide(board.linked, main)
      add = per_page/3

    if (main,thread) in board.linked:
      board.linked.remove((main,thread))

    board.linked.insert(add, (main,thread))
    board.linked = board.linked[:threads]

  main_db = board_db[0]

  if thread in main_db.thread:
    main_db.thread.remove(thread)

  main_db.thread.insert(add, thread)
  main_db.thread = main_db.thread[:threads]

  db.put(board_db)
Example #20
0
 def test_square_neighbors(self):
     """ Tests getting a squares neighbors. """
     board = Board(3, 3)
     square = Square(board, 0, 0, False)
     print(square.neighbors())
     self.assertEqual(3, len(square.neighbors()))
     square_center = Square(board, 1, 1, False)
     self.assertEqual(8, len(square_center.neighbors()))
Example #21
0
def school_board(user: User, school: School, board: Board, school_name: str,
                 board_id: str):
    return render_template(
        "pages/board.html",
        school_name=school_name,
        board=board.render(
            visible=not (board.member_only and (school_name != school.name))),
    )
Example #22
0
def addRole(request):

	admin = request.GET.get('admin')
	newuser = request.GET.get('newuser')
	rolein = request.GET.get('role')
	boardrequest = request.GET.get('boardid')

	board = Board(boardid = boardrequest, userid = newuser, role = rolein)

	filtered = Board.objects.filter(boardid__exact=boardrequest)

	if filtered.filter(userid__exact=admin).exists():
		board.save()
		return JsonResponse({'issuccess':True})

	else:
		return JsonResponse({'issuccess':False})
Example #23
0
File: views.py Project: Taejun/GAE
 def get(self):
     q = Board.all()
     results = q.fetch(limit=10)
     
     values = {'name': results}
     
     template = jinja_env.get_template('index.html')
     self.response.out.write(template.render(values))
Example #24
0
 def test_square__init__(self):
     """ Tests the Square __init__. """
     board = Board(3, 3)
     square = Square(board, 0 ,0, False)
     self.assertFalse(square.mine)
     self.assertFalse(square.clicked)
     square = Square(board, 0, 0, True)
     self.assertTrue(square.mine)
     self.assertFalse(square.clicked)
Example #25
0
def create_board():
    name = request.json['name']
    user_id = request.json['user_id']

    new_board = Board(name, user_id)
    db.session.add(new_board)
    db.session.commit()

    return board_schema.jsonify(new_board)
Example #26
0
    def assign_ship_on_board(self, request):
        """One of the players, tries to assing one boat to his board game"""

        player = Player.query(Player.name == request.player_name).get()
        """we validate that the player is in the Data Base"""
        if not player:
            raise endpoints.NotFoundException('player not found')

        game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
        """we validate that the game where we want to create the board exists"""
        if not game:
            raise endpoints.NotFoundException(
                'Game not found in the DB, please start a new game')

        board = Board.query(Board.key == player.board).get()
        """we validate that the board where we want to create the board exists"""
        if not board:
            raise endpoints.NotFoundException('board not found')
        """we validate that the board of the player is active, the player can't create
            multiple boards for the same Game"""
        if not player.board and not player.board_active:
            raise endpoints.ConflictException(
                'This player has already an empty board have already a board')

        if player.board != board.key:
            raise endpoints.ConflictException(
                'the board for this player is not the proper')

        if gameutils.valid_positions(request.start_x_position,
                                     request.start_y_position,
                                     SHIPS_IDS[request.ship_id],
                                     request.orientation):
            raise endpoints.BadRequestException(
                'Please verify the position that you choose for the boat')
        """Here we check if the boat sent
        in the request is already active in the board"""
        if gameutils.check_if_boat_is_active(request.ship_id, board):
            raise endpoints.BadRequestException(
                'Please the selected boat that you sent '
                'in the request is already active in the board')

        if gameutils.place_boat_in_board(board, request.start_x_position,
                                         request.start_y_position,
                                         request.ship_id, request.orientation):
            raise endpoints.BadRequestException(
                'The place for the boat is not available, '
                'Please verify the position that you choose for the boat')

        try:
            gameutils.log_board_on_console(board)
            board.put()
        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information ')

        return StringMessage(
            message='Boat Assigned!'.format(request.player_name))
Example #27
0
    def make_move(self, request):
        """One of the players, tries to hit the opponent boat"""

        player = Player.query(Player.name == request.player_name).get()
        """we validate that the player is in the Data Base"""
        if not player:
            raise endpoints.NotFoundException('player not found')

        game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
        """we validate that the game where we want to create the board exists"""
        if not game:
            raise endpoints.NotFoundException(
                'Game not found in the DB, please start a new game')

        board = Board.query(Board.key == player.board).get()
        """we validate that the board where we want to create the board exists"""
        if not board:
            raise endpoints.NotFoundException('board not found')
        """we validate that the board of the player is active, the player can't create
            multiple boards for the same Game"""
        if not player.board and not player.board_active:
            raise endpoints.ConflictException(
                'This player has already an empty board have already a board')

        if player.board != board.key:
            raise endpoints.ConflictException(
                'the board for this player is not the proper')

        if not gameutils.valid_target_pointed(request.x_position,
                                              request.y_position):
            raise endpoints.ConflictException(
                'the targeted position is not ok')

        try:
            result = gameutils.search_in_board(board, request.x_position,
                                               request.y_position)

            if result == "error":
                raise endpoints.ConflictException(
                    'there is a problem with the BOARD')
            else:
                score = Score.query(Score.player_name == player.name,
                                    Score.board == board, Score.game == game)
                board.add_target(request.x_position, request.y_position)
                game.add_move_to_history(request.x_position,
                                         request.y_position, player.name)
                message = score.target_hitted(player, request.x_position,
                                              request.y_position, board, game)
                if score.check_if_win():
                    message = "You sunk the last Boat, you win!!!"
                    board.deactivate()
                return StringMessage(message=message)

        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information ')
Example #28
0
def new_board(request):
  board = Board()
  board.radius = Decimal(request.POST['radius'])
  board.lat = Decimal(request.POST['lat'])
  board.lng = Decimal(request.POST['lng'])
  board.name = request.POST['name']
  board.save()
  return redirect('/')
Example #29
0
    def create_empty_board(self, request):
        """One of the players, creates the game and gets the game-id and gives that ID
        to the other player in order to play between each other"""
        player = Player.query(Player.name == request.player_name).get()
        game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
        """ HERE WE START THE PROPER VALIDATIONS FOR THIS ENDPOINT"""
        """we validate that the player is in the Data Base"""
        if not player:
            raise endpoints.NotFoundException(
                'A Player with that name does not exist!, '
                'we need a second player in order to join the game')
        """we validate that the game where we want to create the board exists"""
        if not game:
            raise endpoints.NotFoundException(
                'Game not found in the DB, please start a new game')
        """we validate that the game where we want to create the board is not Over"""
        if not game.game_over == False:
            raise endpoints.ConflictException('Game is over')
        """we validate that the board of the player is active, the player can't create
                    multiple boards for the same Game"""
        if player.board and player.board_active:
            raise endpoints.ConflictException(
                'This player has already an empty board have already a board')

        try:
            board = Board.new_board(player, Board.create_empty_board(), game)
            player.board_active = True
            player.board = board.key
            player.put()
            board.put()
        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information '
                'of the board')

        # Use a task queue to update the average attempts remaining.
        # This operation is not needed to complete the creation of a new game
        # so it is performed out of sequence.

        return board.to_form("Board created", player.name,
                             board.aircraft_carrier, board.battleship,
                             board.submarine, board.destroyer,
                             board.patrol_boat)
Example #30
0
def startGame(args, username, channel):
	usernameX = username # X is the user that ran startGame command

        if (Board.objects.filter(active=True, channel=channel)):
                return generateJsonResponse('There is already an active game in this channel. Please wait til the current game is finished to start a new game. To view current game, use /tictactoe showBoard.', error=True)
	
	if (len(args) < 2):
		return generateJsonResponse('Please specify username of player you would like to play with.', error=True)

	usernameO = args[1] # O is the user that usernameX chose to play with

	playerX = findPlayer(usernameX, channel)
	playerO = findPlayer(usernameO, channel)

	# Create new board for new game.
        board = Board(active=True, channel=channel, playerX=playerX, playerO=playerO)
        board.save()
	
	return generateJsonResponse('New Tic Tac Toe game between %s and %s!' % (usernameX, usernameO), generateBoardWithNextPlayerString(board))
Example #31
0
def WritePostView(request):
    if request.method == 'POST':
        if request.user.is_superuser:
            form = AdminPostForm(request.POST)
        else:
            form = PostForm(request.POST)
        if form.is_valid():
            post = Board(user=request.user,
                         category=form.cleaned_data['category'],
                         title=form.cleaned_data['title'],
                         content=form.cleaned_data['content'])
            post.save()
            return HttpResponseRedirect('/board/')
    else:
        if request.user.is_superuser:
            form = AdminPostForm(initial=request.GET)
        else:
            form = PostForm(initial=request.GET)
    return render(request, 'board/write_post.html', dict(form=form))
Example #32
0
 def insert_board(self, bName, bDesc, privacy, userid):
     maxbval = 0
     print "Inside db"
     try:
         print "Inside db try"
         for index in database:
             if (database[index].get('userid') == userid and database[index].get('bid') > maxbval):
                 print database[index].get('bid')
                 maxbval = database[index].get('bid')
         board = Board(boardName=bName, boardDesc=bDesc)
         board['bid'] = maxbval + 1
         board['privacy'] = privacy
         board['userid'] = userid
         board.store(database)
         result = "users/" + str(userid) + "/boards/" + str(board['boardName'])
         print result
         return result
     except:
         print "Exception"
Example #33
0
    def get_objects(self, identifier):
        board = Board.get_by_id(int(identifier))
        if board is None:
            self.abort(404)
            return
        permission = board.get_permission_level(self.get_current_user())
        if permission is None:
            self.abort(404)

        self.board = board
        self.permission = permission
Example #34
0
 def put(self):
     board_id = self.get_argument('board_id')
     item_id = self.get_argument('id')
     b = Board.get(board_id)
     for item in b.items:
         if item_id == str(item.id):
             b.items.remove(item)
     b.save()
     data = {'update_type': 'remove_item', 'item_id': item_id}
     for socket in sockets[board_id]:
         EchoWebSocket.safe_write_to_socket(socket, json.dumps(data))
Example #35
0
    def test_board_model(self):
        """Does basic model work?"""

        b = Board(name="test board name", user_id=self.uid)

        db.session.add(b)
        db.session.commit()

        # User should have 1 board created
        self.assertEqual(len(self.u.boards), 1)
        self.assertEqual(self.u.boards[0].name, "test board name")
Example #36
0
def promtStartMenu():
    board = Board(1,1)
    print(board)
    clearConsole()
    print("Select difficulty:")
    print("> Easy (10x10, 5 words)")
    print("  Medium (15x15, 12 words)")
    print("  Hard (20x20, 25 words)")
    print("  Very Hard (30x30, 40 words)")
    IN_MENU = True
    OPTION = 1
Example #37
0
def school_main(user: User, school: School, school_name: str):
    boards: list[Board] = Board.get(school_name)
    form: LoginForm = LoginForm(request.form)

    mfa_passed: bool = False
    error: str = ""

    if len(boards) == 0:
        abort(404)

    if request.method == "POST" and form.validate_on_submit():
        username: str = form.username.data
        password: str = form.password.data

        if user.username != username:
            error = "현재 로그인 되어 있는 사용자의 이름을 입력해주세요."
        else:
            requested_user: User = User.query.filter(
                User.username == username,
                User.password == authenticator.hash(password)).first()

            mfa_passed = requested_user is not None

            if not mfa_passed:
                error = "인증에 실패했습니다."
            elif requested_user.school_name != school_name:
                mfa_passed = False
                error = f"{school_name}을(를) 열람할 권한이 없습니다."

    return render_template(
        "pages/school.html",
        form=form,
        school_name=school_name,
        boards=[
            board.render(
                visible=not (board.member_only and school.name != school_name))
            for board in Board.get(school_name)
        ],
        mfa_passed=mfa_passed,
        error=error,
    )
Example #38
0
def show_board(request):
    if request.method == "GET":
        boards = Board.objects.filter(user=request.user)
        form = Boardform()
        shared = ReadPermissions.objects.filter(username=request.user.username)
        ret = render(request, "issueview/boards.html", {
            "form": form,
            "boards": boards,
            "shared": shared
        })
        add_never_cache_headers(ret)
        return ret
    form = Boardform(request.POST)
    if form.is_valid():
        if valid_board(form.cleaned_data["board"], request.user):
            board = Board()
            board.board = form.cleaned_data["board"]
            board.user = request.user
            board.save()
            form = Boardform()
        else:
            form.add_error(
                None,
                "board names should be unique and should only use small case digits, alphabet and underscore."
            )
    boards = Board.objects.filter(user=request.user)
    shared = ReadPermissions.objects.filter(username=request.user.username)
    ret = render(request, "issueview/boards.html", {
        "form": form,
        "boards": boards,
        "shared": shared
    })
    add_never_cache_headers(ret)
    return ret
Example #39
0
    def player_move(self, request):
        """Make a move"""

        user = endpoints.get_current_user()

        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        game = get_by_urlsafe(request.game_key, Game)
        if not game:
            raise endpoints.NotFoundException("Game not found")

        player = Player.query(Player.email == user.email()).get()
        if not player or player.key != game.player:
            raise endpoints.UnauthorizedException(
                'You are not the player for the game')

        if game.state == 1:
            raise endpoints.ForbiddenException(
                'It is the AI\'s turn')
        if game.state != 0:
            raise endpoints.ForbiddenException(
                'Game already over')

        origin = (request.origin_row, request.origin_column)
        destination = (request.destination_row, request.destination_column)

        board = Board(game.board_values)

        if not board.valid_player_move(origin, destination):
            raise endpoints.BadRequestException("invalid move")

        score, captures = attacker_cell_score(board, destination)
        player_won = True if score == MAX_SCORE else None

        origin_value = game.add_move(
            board, True, player_won, origin, destination, captures)

        return game.get_play_result(
            origin_value, origin, destination, captures, game.state)
Example #40
0
def create_layout():
    FILEPATH = 'inputs/1.txt'

    board_id = 1
    board_rows = 10
    board_cols = 10

    with open(FILEPATH) as fp:
        number_of_snakes = fp.readline()
        snake_positions = list()
        ladder_positions = list()
        players = list()
        for i in range(0, int(number_of_snakes.strip())):
            snake_positions.append(fp.readline().split(' '))

        number_of_ladders = fp.readline()
        for i in range(0, int(number_of_ladders.strip())):
            ladder_positions.append(fp.readline().split(' '))

        number_of_players = fp.readline()
        for i in range(0, int(number_of_players.strip())):
            players.append(fp.readline().strip())

    board = Board(board_id, board_rows, board_cols,
                  snake_count=number_of_snakes,
                  ladder_count=number_of_ladders,
                  player_count=number_of_players)

    board.setup_board()

    for positions in snake_positions:
        board.place_snake(board_id, int(positions[0]), int(positions[1]))

    for positions in ladder_positions:
        board.place_ladder(board_id, int(positions[0]), int(positions[1]))

    for player in players:
        board.add_player(board_id, player)

    return board
Example #41
0
def main():
    board = Board()

    # Цикл ввода команд игроков
    while True:
        board.print()

        print('Команды:')
        print('    exit                               -- выход')
        print(
            '    move <row> <col> <row1> <row1>     -- ход из клетки (row, col)'
        )
        print(
            '                                          в клетку (row1, col1)')

        # Выводим приглашение игроку нужного цвета
        if board.current_player_color() == WHITE:
            print('Ход белых:')
        else:
            print('Ход чёрных:')

        command = input()
        if command == 'exit':
            break

        move_type, row, col, row1, col1 = command.split()
        row, col, row1, col1 = int(row), int(col), int(row1), int(col1)

        if board.move_piece(row, col, row1, col1):
            print('Ход успешен')
        else:
            print('Координаты некорректы! Попробуйте другой ход!')
Example #42
0
class GameLoadTest(TestCase):
    GAME_COUNT = 1000
    def setUp(self):
        self.board = Board()
        self.player = Player("X", self.board, "Sys")
        self.computer = ComputerPlayer("O",self.board)
        self.winners = {}
        self.moves = {}
        
    def play_game(self):
        sys_moves = []
        while self.board.winner == None:
            choice_made = False
            while not choice_made:
                choice = random.randrange(0, 9, 1)
                if choice not in sys_moves and self.board.get_cell(choice) == None:
                    sys_moves.append(choice)
                    choice_made = True
                    self.player.place_marker(choice)
                    if self.board.winner == None:
                        self.computer.place_marker()
        
        winner = self.board.winner
        if winner in self.winners.keys():
            self.winners[winner] = self.winners[winner] + 1
        else:
            self.winners[winner] = 1
        if winner == "X":
            move = sys_moves.__str__()
            if move in self.moves.keys():
                self.moves[move] = self.moves[move] + 1
            else:
                self.moves[move] = 1
            
    def test_game(self):
        for count in range(self.GAME_COUNT):
            self.play_game()
            self.board.clear()
        print "\n{0}".format(self.winners)
        print "\n{0}".format(self.moves)
Example #43
0
File: app.py Project: t20/skore
def new_board():
    if request.method == 'GET':
        return render_template('board_form.html')
    # else POST
    name = request.form.get('name')
    desc = request.form.get('desc', '')
    items = request.form.getlist('item')

    b = Board(name=name, desc=desc)
    saved = b.save()
    
    board_id = int(b.id)
    for item in items:
        if not item:
            continue
        i = Item(name=item, board_id=board_id)
        saved = i.save()
        # print 'saved?', saved
        # print 'Item: {} - saved? {}'.format(item, saved)

    flash('New board created.')
    return redirect(url_for('board', board_id=int(b.id)))
Example #44
0
File: api.py Project: cklzqw/gaeaib
  def get(self):
    boardq = Board.all()

    return json_response(
        [
          {
            "code":board.code,
            "name":board.name,
            "last" : board.counter,
          }
          for board in boardq
        ]
    )
def board(request):
    response = {}
    result = {}

    if request.method == "POST":
        member_id = request.data["memberId"]
        title = request.data["title"]
        content = request.data["content"]

        if member_id is None or title is None or content is None:
            response["STS"] = ERR_USER_PARAM
            response["MSG"] = MSG[ERR_USER_PARAM]

            return Response(response)

        board = Board(member_id=member_id, title=title, content=content)
        board.save()

        response["STS"] = SUCCESS
        response["MSG"] = MSG[SUCCESS]
        response["DAT"] = board.id

        return Response(response)

    if request.method == "GET":
        paginator = PageNumberPagination()

        board_list = Board.objects.order_by("-id").all()
        result_page = paginator.paginate_queryset(board_list, request)
        board_list_serializer = BoardListSerializer(result_page, many=True)

        result["board_list"] = board_list_serializer.data
        result["total_cnt"] = len(board_list)

        response["STS"] = SUCCESS
        response["MSG"] = MSG[SUCCESS]
        response["DAT"] = result

        return Response(response)
Example #46
0
    def post(self, *args, **kwargs):
        log.error('self.request.POST = %s' %
                (unicode(self.request.POST),))

        if self.get_current_user() is None:
            raise Exception('Foo')
        log.info('Creating a new board')
        try:
            name = self.request.get('inputName', '')
            if not name:
                log.error('Name is false?')
                log.error('self.request.POST = %s' %
                        (unicode(self.request.POST.items()),))
                return super(CreateHandler, self).get(*args, **kwargs)

            board = Board(name=name, owner=self.get_current_user())
            board.put()
            log.info('Created a new board: %d' % (board.key().id(),))
            self.redirect_to('board', identifier=unicode(board.key().id()))
            return
        except:
            log.exception('Error creating a board')
            return super(CreateHandler, self).get(*args, **kwargs)
Example #47
0
    def open(self, board_id):
        user_id = self._generate_user_id()

        sockets[board_id].append(self)
        socket_to_board_id[self] = board_id
        socket_to_user_id[self] = user_id
        users[board_id].append(user_id)

        board = Board.get(board_id)
        if board:
            broadcastData = json.dumps({
                'board': json.loads(board.to_json())
            })
            self.safe_write_to_socket(self, broadcastData)
            self._broadcast_user_display(board_id)
Example #48
0
    def test_unauthorized_board_delete(self):
        u = User.signup(first_name="John", last_name="Deere", username="******", password="******")
        u.id = 124

        b = Board(id=1234, title="test", description="test", user_id=self.testuser_id)
        db.session.add_all([u, b])
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess["curr_user"] = 124

            resp = c.get("/boards/1234/delete", follow_redirects=True)
            self.assertEqual(resp.status_code, 200)
            self.assertIn("Access unauthorized", str(resp.data))
Example #49
0
    def game():
        print('Welcome to Tic Tac Toe')

        human = Human.choose_letter().upper()
        computer = Computer.comp_letter(human)
        board = Board.board

        while True:
            move = Human.player_move(board, human)

            if move is True:
                Computer.computer_move(board, computer, human)
                Board.print_board(board)

            if Board.is_board_full(board) is None:
                print('-> It\'s a bloody draw!')
                break

            elif Game.winner(board, computer, human) == -10:
                print(f'-> {human} (you) won this round!')
                break

            elif Game.winner(board, computer, human) == 10:
                print(f'-> {computer} (the machine) won this round!')
                break

        while True:
            play_again = input('-> Wanna play again? Yes/ No: ')

            if play_again.lower() == 'yes' or play_again.lower() == 'y':
                Board.clear_board(board)
                Game.game()

            elif play_again.lower() == 'no' or play_again.lower() == 'n':
                print('Thanks for playing my little game!')
                break
Example #50
0
def add_board():

    if check_admin(request) == 1:
        return abort(403, "You are not allowed to do this.")

    name = request.forms.get("name").strip().lower()

    if any(char in list(punctuation + ' ') for char in name):
        return abort(400, "Boards can't have symbols in their name.")

    if Board.select().where(Board.name == name).exists():
        return abort(400, "A board with this name already exists.")

    data = {
        "name": name,
        "nsfw": bool(request.forms.get("nsfw")),
        "title": request.forms.get("title").strip()
    }

    board = Board(**data)
    board.save()
    board_directory(name)

    return redirect(f'{basename}/admin')
Example #51
0
def thread_close(board_name, refnum):

    if f':{board_name}:' not in get_current_user(request).mod:
        return abort(404, "This page doesn't exist.")

    board = Board.get(Board.name == board_name)

    thread = board.posts.where(Post.refnum == refnum).get()

    if thread.closed: thread.closed = False
    else: thread.closed = True

    thread.save()

    return redirect(f'{basename}/{board_name}/')
Example #52
0
    def test_board_delete(self):

        b = Board(id=1234, title="test", description="test", user_id=self.testuser_id)

        db.session.add(b)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess["curr_user"] = self.testuser_id

            resp = c.get("/boards/1234/delete", follow_redirects=True)
            self.assertEqual(resp.status_code, 200)

            b = Board.query.get(1234)
            self.assertIsNone(b)
Example #53
0
def get_threads(board, page=0, fmt_name="page"):

  _fmt = "thread_" + fmt_name
  if _fmt in globals():
    fmt = globals()[_fmt]
  else:
    fmt = thread_plain

  threads = Board.load(board)
  threads = threads[THREAD_PER_PAGE*page:THREAD_PER_PAGE*(page+1)]
  logging.info("threadlist in %r : %r" % (board, threads))

  # grab data from cache
  data =  Thread.load_list(threads, board)

  return [ fmt(num,th) for num,th in data if th ]
Example #54
0
File: api.py Project: cklzqw/gaeaib
  def get(self, board):
    key = "posts-%s" % board
    post = memcache.get(key)

    if post != None:
      return json_response(post)

    board = Board.get_by_key_name(board)

    if board:
      post = board.counter
      memcache.set(key, post)
    else:
      post = None

    return json_response(post)
Example #55
0
    def get_context_data(self, **kwargs):
        context = super(BoardHandler, self).get_context_data(**kwargs)
        context['board'] = self.board
        context['board_id'] = self.board.key().id()
        context['user_boards'] = \
            Board.get_all_for_user(self.get_current_user())
        context['permission'] = self.permission
        context['changes'] = Change.all().ancestor(self.board)
        context['board_navigation'] = [
            (self.uri_for('board', identifier=self.board.key().id()),
                '<i class="icon-table"></i> Board'), 
            (self.uri_for('board-sharing', identifier=self.board.key().id()),
                '<i class="icon-user"></i> Sharing'),
        ]

        return context
Example #56
0
def get_threads(board, page=0, fmt_name="page"):

  _fmt = "thread_" + fmt_name
  if _fmt in globals():
    fmt = globals()[_fmt]
  else:
    fmt = thread_plain

  per_page = get_config('aib.ib', 'thread_per_page')

  threads = Board.load(board) or []
  threads = threads[per_page*page:per_page*(page+1)]
  logging.info("threadlist in %r : %r" % (board, threads))

  # grab data from cache
  data =  Thread.load_list(threads, board)

  return [ fmt(num,th) for num,th in data if th ]
Example #57
0
 def attach_pin(self,user_id,pin_id,board_id):
     """
     This method returns "pin Attached" on successful operation and False on unsuccessful attempts.
     This method attaches a particular pin with pin_id to a board with board_id
     """
     if board_id in boarddb and user_id in userdb:
         try:
             board=Board.load(boarddb,board_id)
             if board['user_id']==user_id:
                 board.pins.append(pin_id=pin_id)
                 board.store(boarddb)
                 return "Pin Attached"
             else:
                 return False
         except:
             return False
     else:
         return False
Example #58
0
    def __init__(self, configuration):
        self.board = Board()

        player1 = Player(
            self,
            configuration["name_player1"],
            configuration["intelligence_player1"]
        )

        player2 = Player(
            self,
            configuration["name_player2"],
            configuration["intelligence_player2"]
        )

        self.players = (player1, player2)
        self.active_player = player1

        self.state = self.STATES["WAIT_SELECTION"]
Example #59
0
 def get_board(self,board_id):
     """
     Returns All the pins in a particular board with board_id
     """
     try:
         board=Board.load(boarddb,board_id)
         result={}
         result['board_id']=board_id
         result['board_name']=board.board_name
         pins=[]
         for pin_item in board.pins:
             pin2=Pin.load(pindb,pin_item.pin_id)
             pin={}
             pin['pin_id']=pin_item.pin_id
             pin['pin_name']=pin2.pin_name
             pin['pin_url']=request.urlparts.scheme+"://"+request.urlparts.netloc+"/"+pin2.pin_url
             pins.append(pin)
         result['pins']=pins
         return result
     except:
         return False
Example #60
0
    def put(self, id=None, *args, **kwargs):
        board_id = self.get_argument('board_id')
        url = self.get_argument('url')
        image_url = self.get_argument('image_url')
        #tags = self.get_arguments('tags[]', [])
        tags = self.request.arguments.get('tags[]');
        #tags = self.get_argument('tags[]', [])
        pos_x = self.get_argument('pos_x')
        pos_y = self.get_argument('pos_y')
        scale = self.get_argument('scale')
        locked = self.get_argument('locked')

        item = Item(id=uuid.uuid4(), url=url, image_url=image_url, tags=tags,
                    pos_x=pos_x, pos_y=pos_y, scale=scale, locked=locked)
        b = Board.get(board_id)
        b.items.append(item)
        b.save()

        data = {'update_type': 'add_item', 'item': json.loads(item.to_json())}
        for socket in sockets[board_id]:
            EchoWebSocket.safe_write_to_socket(socket, json.dumps(data))