def keypress(event): global OPTION global IN_MENU global board if event.event_type == "up": return if IN_MENU: if event.scan_code == 72 and OPTION > 1: moveConsoleCursor(0,OPTION) print(" ",end="") OPTION -= 1 moveConsoleCursor(0,OPTION) print(">",end="") elif event.scan_code == 80 and OPTION < 4: moveConsoleCursor(0,OPTION) print(" ",end="") OPTION += 1 moveConsoleCursor(0,OPTION) print(">",end="") elif event.scan_code == 28: if OPTION == 1: board = Board(10,10) n_words = 5 elif OPTION == 2: board = Board(15,15) n_words = 12 elif OPTION == 3: board = Board(20,20) n_words = 25 elif OPTION == 4: board = Board(30,30) n_words = 40 else: raise ValueError("Option variable is out of bounds: "+str(OPTION)) words_to_search = sample(words, n_words) for word in words_to_search: board.addWord(word) IN_MENU = False board.startGame() else: if board.gameIsWon(): if event.scan_code == 28: IN_MENU = True OPTION = 1 promtStartMenu() return else: if board.moveCursor(event.scan_code): board.update() elif event.scan_code == 28: board.toggleMarking()
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
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)
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))
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('Координаты некорректы! Попробуйте другой ход!')
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
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("게임 게시판 테스트 데이터 입력 성공")
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('/')
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()))
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)
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)
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')
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
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")
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"]
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})
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())
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))
def submit_board(): data = request.json if User.query.filter(User.username == data["user"]).first() is None: new_user = User(username=data["user"]) db.session.add(new_user) db.session.commit() board_owner = new_user.username else: board_owner = User.query.filter( User.username == data["user"]).first().username new_board = Board(owner=board_owner, board=data["board"]) db.session.add(new_board) db.session.commit() return 'success', 200
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)
def generate_map(self): """ generate mine map """ global game game = Board(self._row_num, self._col_num) s = set([]) while len(s) <= self._mine_num: i = random.randint(0, self._row_num * self._col_num - 1) if i not in s: self._set_mine(i) s.add(i) return { #'board':[game.get_board()[inx].get_neighbor() for inx in range(0,self._row_num*self._col_num)], #'mines':game.get_mines(), 'row_num': self._row_num, 'col_num': self._col_num }
def main(self): board = Board() board.set_snakes(self.read_board_input()) # board.set_snakes([(62,5),(33,6),(49,9),(88,16),(41,20),(56,53),(98,64),(93,73),(95,75)]) board.set_ladders(self.read_board_input()) # board.set_ladders([(2,37),(27,46),(10,32),(51,68),(61,79),(65,84),(71,91),(81,100)]) players = self.read_players() # players = [Player('Ashish'), Player('Samin')] player_lineup = cycle(players) while Game._continue_game: current_player = next(player_lineup) current_player.play_turn()
def sports_insert(): print("게임 게시판 테스트 데이터 입력 시작...") boarname_list = ["야구"] for i in range(1, 34): board = Board() board.board_name = f"{boarname_list[i-1]}" board.description = f"게시판 설명{i}" board.category_id = 2 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("게임 게시판 테스트 데이터 입력 성공")
def getGameBoard(img, save=False): import sys import os path = f'images/{time()}' os.makedirs(path) boxes, boxLocations = getWhiteBoxLocations(img) if save: cv2.imwrite(f'{path}/current_board.jpg', img) for i, box in enumerate(boxes): cv2.imwrite(f'{path}/{i}.jpg', box) letters = getLetters(boxes, boxLocations) print("Identified Letters:") for letter in letters: print(letter.__repr__()) board = Board(letters) if save: centerDrawn = drawCenters(img, board) cv2.imwrite(f'{path}/centers.jpg', centerDrawn) return board
def add_board(): """ Add new board """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = AddBoardForm(request.form) if form.validate_on_submit(): board = Board(title=form.title.data, description=form.description.data, user_id=g.user.id) db.session.add(board) db.session.commit() return redirect("/") else: return render_template("user_home.html", form=form)
def Board_insert(): print("테스트 게시판 입력 시작...") for i in range(1, 20): ran = random.randrange(1, 20) if ran == 1: ran += 1 print(ran) board = Board() board.board_name = f"게시판 이름{i}" board.description = f"게시판 설명{i}" board.category_id = ran board.post_num = 0 board.category = Category.query.filter(Category.id == ran).first() board.category.board_num += 1 db.session.add(board) db.session.commit() print("테스트 게시판 입력 성공")
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
def board_add(): """Add a board: """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = AddForm() if form.validate_on_submit(): name = form.name.data board = Board(name=name) g.user.boards.append(board) db.session.commit() flash("Board created", "success") boards = (Board.query.filter(Board.user_id == g.user.id).all()) return render_template('boards/new.html', form=form, boards=boards)
def add_board(): board_name = request.form.get('board_name') print(request.form.get("board_name")) description = request.form.get('description') category_id = request.form.get('category_id') try: # 게시판 사진 받아도 되고 안받아도 됨 board_image = request.files['board_image'] except: board_image = None print(board_name,description,category_id,board_image) if not board_name: return jsonify({'error': '게시판 제목이 없습니다.'}), 400 category = Category.query.filter(Category.id == category_id).first() category.board_num += 1 board = Board() board.board_name = board_name board.description = description board.category_id = category_id board.category = category if board_image and allowed_file(board_image): # 프로필 이미지 확장자 확인 suffix = datetime.now().strftime("%y%m%d_%H%M%S") filename = "_".join([board_image.filename.rsplit('.', 1)[0], suffix]) # 중복된 이름의 사진을 받기위해서 파일명에 시간을 붙임 extension = board_image.filename.rsplit('.', 1)[1] filename = secure_filename(f"{filename}.{extension}") board_image.save(os.path.join(UPLOAD_FOLDER, filename)) board.board_image = filename db.session.add(board) db.session.commit() # db에 저장 return jsonify( result = "success" ), 201
def setUp(self): """ Create test client and add sample data """ User.query.delete() Post.query.delete() Board.query.delete() self.client = app.test_client() self.testuser = User.signup(first_name="Johnny", last_name="lingo", username="******", password="******") self.testuser_id = 20 self.testuser.id = self.testuser_id db.session.commit() b = Board(id=3, title="test", description="test", user_id=self.testuser_id) db.session.add(b) db.session.commit() b = Board.query.get(3) self.board = b self.board_id = 3