Пример #1
0
    def initUi(self):


        self.game = Game()

        layout = QGridLayout()

        table_results = QTableWidget()
        layout.addWidget(table_results, 2, 1)
        
        table_guesses = QTableWidget()
        layout.addWidget(table_guesses, 2, 2)

        table_selection = QTableWidget()

        self.setup_table_results(table_results)
        self.setup_table_guesses(table_guesses)
        self.setup_table_selection(table_selection, table_guesses, table_results)

        game_buttons = self.setup_game_buttons(table_guesses, table_results)
        layout.addWidget(game_buttons, 1, 1, 1, 4)        
        
        layout.addWidget(table_selection, 2, 3)

        self.setLayout(layout)
Пример #2
0
 def on_message(self, client, userdata, msg):
     if msg.topic == 't_general':
         data = json.loads(msg.payload)
         if data['type'] == "new_game":
             gameName = str(data['game'])
             print(gameName)
             try:
                 newGame = Game(len(self.games), gameName, data['author'])
                 self.games.append(newGame.gameName)
                 newGame.start()
             except:
                 print "Error: unable to start the thread for the new game"
         elif data['type'] == "sign_in":
             self.mqttClient.publish(str(data['player']), json.dumps({"type": "game_list", "games": self.games}))
         elif data['type'] == "sign_out":
             pass
Пример #3
0
    def game_worker(self):
        game = Game(self.clients)
        while True:
            client, request = self.queue_client.get()

            request: Request = request
            requests_to_send: tp.List[Request] = game.dispatch(request)
            self.queue_client.task_done()

            if len(requests_to_send) == 0:
                continue

            # response from game to client
            for request_to_send in requests_to_send:
                for client_to_send in self.clients.get_clients_from_request(
                        request_to_send):
                    data_to_send = request_to_send.parse_headers()
                    self.queue_sender.put((client_to_send, data_to_send))
Пример #4
0
def process_input(input, user_number):

    if 'hi' in input.lower():
        varied_response = (
            'Hello Number: {}! You are now chatting to a bot powered by Twilio!'
            ' Would you like to play a simple quiz to guess the name of the 80s/90s song based'
            ' off the lyrics? It is powered by the Muisxmatch API that retrieves snippets'
            ' of a song lyrics. To proceed, type yes to play or no to exit.'.
            format(user_number))

    elif 'yes' in input.lower():
        game = Game()
        questions = game.shuffle_questions()
        q_list = []

        for k, v in questions.items():
            q_list.append(questions[k])

        new_q_list = ('\n'.join(q_list))

        varied_response = (
            'Welcome to guess the 80s and 90s song! Lets start by guessing...'
            ' Enter the song name to guess right... '
            ' NOTE: You must separate the words with a comma or else you will get'
            ' an invalid response!'
            ' Here are the questions:' + '\n' + '\n' + new_q_list)

    elif ',' in input:
        result = input.replace(' ', '').split(',')
        result = [song.lower() for song in result]

        if 'bohemianrhapsody' and 'smellsliketeenspirit' and 'thunderstruck' and 'nevergonnagiveyouup' in result:
            varied_response = 'Congratulations, you have guessed correctly!'

        else:
            varied_response = 'Oops! You guessed wrong. Please try again'

    elif 'no' in input.lower():
        varied_response = 'Very well, Have a good day then. See you later!'
    else:
        varied_response = 'This is not a valid choice. Choose from one of the available responses. ' \
                          'Alternatively, type hi to view the welcome message again'

    return varied_response
Пример #5
0
 def on_message(self, client, userdata, msg):
     if msg.topic == 't_general':
         data = json.loads(msg.payload)
         if data['type'] == "new_game":
             gameName = str(data['game'])
             print(gameName)
             try:
                 newGame = Game(len(self.games), gameName, data['author'])
                 self.games.append(newGame.gameName)
                 newGame.start()
             except:
                 print "Error: unable to start the thread for the new game"
         elif data['type'] == "sign_in":
             self.mqttClient.publish(
                 str(data['player']),
                 json.dumps({
                     "type": "game_list",
                     "games": self.games
                 }))
         elif data['type'] == "sign_out":
             pass
Пример #6
0
def test():
    data_bytes = request._get_body_string()

    request_data = json.loads(data_bytes)
    cookie = request_data['cookie']

    returnVal = None
    # Handle new clients
    print(request_data)

    # Retrieve all rows with the cookie as ID
    curs.execute(
        "SELECT COUNT(*) FROM " + connectionTableName + " WHERE cookie=?;",
        (cookie, ))

    if curs.fetchone()[0] == 0:
        # Add new cookie ID into database
        curs.execute(
            "INSERT INTO " + connectionTableName +
            " (cookie, firstAccessDate, numValidMoves) VALUES (?,?,?)",
            (cookie, datetime.today().timestamp(), 0))
    elif request_data['clickPosition'] != -1:
        # if it's a valid move, update number of valid moves registered
        curs.execute(
            "UPDATE " + connectionTableName +
            " SET numValidMoves=numValidMoves+1 WHERE cookie=?", (cookie, ))

    # for row in curs.execute("SELECT * FROM " + connectionTableName):
    #     print(row)
    # commit changes to database
    conn.commit()

    if request_data['game_key'] not in games.keys():
        games[request_data['game_key']] = [Game(cookie), 100]
        returnVal = games[request_data['game_key']][0].handleClick(
            cookie, request_data['clickPosition'])
    else:
        returnVal = games[request_data['game_key']][0].handleClick(
            cookie, request_data['clickPosition'])
        # Reset time to live of games with valid user clicks not just render refreshes
        if request_data['clickPosition'] != -1:
            games[request_data['game_key']][1] = 100
    return HTTPResponse(
        status=200,
        headers={
            "Content-Type": "application/json",
            # "Access-Control-Allow-Origin": "*",
        },
        body=json.dumps(returnVal))
Пример #7
0
    def test_get_distance(self):
        coordinates_tank1 = Coordinates(10, 20, 30, 40)
        direction_tank1 = Direction.DOWN
        coordinates_tank2 = Coordinates(15, 20, 11, 16)
        direction_tank2 = Direction.LEFT
        destroyable = True
        speed = Speed.NORMAL
        shots_until_destroyed = 1
        rank = Rank.NORMAL
        is_enemy1 = False
        is_enemy2 = True
        expected_distance = 0

        tank1 = Tank(coordinates_tank1, destroyable, direction_tank1, speed,
                     shots_until_destroyed, rank, is_enemy1)
        tank2 = Tank(coordinates_tank2, destroyable, direction_tank2, speed,
                     shots_until_destroyed, rank, is_enemy2)

        distance = Game.get_distance(tank1, tank2)

        self.assertEqual(distance, expected_distance)
Пример #8
0
    def test_detect_collision_False(self):
        coordinates_tank1 = Coordinates(10, 20, 30, 40)
        direction_tank1 = Direction.DOWN
        coordinates_tank2 = Coordinates(15, 20, 11, 16)
        direction_tank2 = Direction.LEFT
        destroyable = True
        speed = Speed.NORMAL
        shots_until_destroyed = 1
        rank = Rank.NORMAL
        is_enemy1 = False
        is_enemy2 = True
        step = 10

        tank1 = Tank(coordinates_tank1, destroyable, direction_tank1, speed,
                     shots_until_destroyed, rank, is_enemy1)
        tank2 = Tank(coordinates_tank2, destroyable, direction_tank2, speed,
                     shots_until_destroyed, rank, is_enemy2)

        tank1.move(step)
        tank2.move(step)
        collision = Game.detect_collision(tank1, tank2)

        self.assertFalse(collision)
Пример #9
0
class Window(QWidget):
    
    def __init__(self):
        
        super().__init__()
        self.initUi()

        self.current_row = 0
        
        self.show()
       
        
    def initUi(self):


        self.game = Game()

        layout = QGridLayout()

        table_results = QTableWidget()
        layout.addWidget(table_results, 2, 1)
        
        table_guesses = QTableWidget()
        layout.addWidget(table_guesses, 2, 2)

        table_selection = QTableWidget()

        self.setup_table_results(table_results)
        self.setup_table_guesses(table_guesses)
        self.setup_table_selection(table_selection, table_guesses, table_results)

        game_buttons = self.setup_game_buttons(table_guesses, table_results)
        layout.addWidget(game_buttons, 1, 1, 1, 4)        
        
        layout.addWidget(table_selection, 2, 3)

        self.setLayout(layout)


    def setup_game_buttons(self, table_guesses, table_results):

        group_box = QGroupBox()

        hbox = QHBoxLayout()
        
        button_newgame = QPushButton('New game')
        button_checkcombo = QPushButton('Check combination')
        button_backspace = QPushButton('Delete symbol')

        button_checkcombo.clicked.connect(
                lambda: self.check_combos(table_guesses, table_results))

        hbox.addWidget(button_newgame)
        hbox.addWidget(button_checkcombo)
        hbox.addWidget(button_backspace)

        group_box.setLayout(hbox)

        return group_box
    

    def setup_table_guesses(self, table_guesses):

        table_guesses.setFixedSize(258, 514)
        table_guesses.horizontalHeader().hide()
        table_guesses.verticalHeader().hide()
        
        table_guesses.setRowCount(8)
        table_guesses.setColumnCount(4)

        for i in range(4):
            table_guesses.setColumnWidth(i, 64)

        for i in range(8):
            table_guesses.setRowHeight(i, 64)


    def setup_table_results(self, table_results):

        table_results.setFixedSize(258, 514)
        table_results.horizontalHeader().hide()
        table_results.verticalHeader().hide()
        
        table_results.setRowCount(8)
        table_results.setColumnCount(4)

        for i in range(4):
            table_results.setColumnWidth(i, 64)

        for i in range(8):
            table_results.setRowHeight(i, 64)        


    def setup_table_selection(self, table_selection, table_guesses, table_results):

        table_selection.setFixedSize(66, 514)
        table_selection.horizontalHeader().hide()
        table_selection.verticalHeader().hide()
        
        table_selection.setRowCount(8)
        table_selection.setColumnCount(1)

        table_selection.setColumnWidth(0, 64)

        for i in range(8):
            table_selection.setRowHeight(i, 64)

        table_selection.cellClicked.connect(
                lambda: self.on_table_selection_cell_clicked(
                        table_selection, table_guesses, table_results))


        for i in range(1, 9):

            label = QLabel()
            label.setFixedSize(64, 64)
            label.setAlignment(Qt.AlignCenter)

            pixmap = QPixmap('icons/{}.png'.format(i))
            pixmap = pixmap.scaledToHeight(34)
            pixmap = pixmap.scaledToWidth(34)

            label.setPixmap(pixmap)

            label.setProperty('element_id', i)

            table_selection.setCellWidget(i - 1, 0, label)


    def set_attempt_combo(self, label, table_guesses):
        print(self.current_row)
        if not hasattr(Window.set_attempt_combo, 'column'):
            Window.set_attempt_combo.column = 0

        if Window.set_attempt_combo.column < 5:    
            if Window.set_attempt_combo.column < 4:
                table_guesses.setCellWidget(
                        self.current_row,
                        Window.set_attempt_combo.column, label)
                Window.set_attempt_combo.column += 1


    def on_table_selection_cell_clicked(self, sender, table_guesses, table_results):

        if not hasattr(Window.set_attempt_combo, 'count'):
            Window.on_table_selection_cell_clicked.count = 0
            
        Window.on_table_selection_cell_clicked.count += 1
        
        if Window.on_table_selection_cell_clicked.count == 5:
            self.current_row += 1
            print(self.current_row)  

        if Window.on_table_selection_cell_clicked.count < 5:
            label = sender.cellWidget(sender.currentRow(), 0)
            
            label_copy = QLabel()
            label_copy.setFixedSize(64, 64)
            label_copy.setAlignment(Qt.AlignCenter)
            
            label_copy.setPixmap(label.pixmap())
            label_copy.setProperty(
                    'element_id', label.property('element_id'))
            self.set_attempt_combo(label_copy, table_guesses)




    def check_combos(self, table_guesses, table_results):

        secret = self.game.secret[:]
        attempt = list()

        for i in range(4):
            label = table_guesses.cellWidget(
                    self.current_row, i)
            attempt.append(label.property('element_id'))
        print(attempt)
        print(secret)

        full, partial = self.game.compare_combos(attempt, secret)
        self.display_results(full, partial, table_results)      


    def display_results(self, full, partial, table_results):

        for i in range(full):
            
            label = QLabel()
            label.setFixedSize(64, 64)
            label.setAlignment(Qt.AlignCenter)

            pixmap = QPixmap('icons/bingo.png')
            pixmap = pixmap.scaledToHeight(34)
            pixmap = pixmap.scaledToWidth(34)

            label.setPixmap(pixmap)

            table_results.setCellWidget(self.current_row, i, label)

        for i in range(partial):
            
            label = QLabel()
            label.setFixedSize(64, 64)
            label.setAlignment(Qt.AlignCenter)

            pixmap = QPixmap('icons/almost.png')
            pixmap = pixmap.scaledToHeight(34)
            pixmap = pixmap.scaledToWidth(34)

            label.setPixmap(pixmap)

            table_results.setCellWidget(self.current_row, i, label)
Пример #10
0
    grid.set_drawaction('=', partial(grid.draw_background, color=(70, 70, 70)))
    grid.set_drawaction(':', partial(grid.draw_background,
                                     color=(140, 120, 80)))
    grid.set_drawaction('\\', drawing.draw_down_line)
    grid.set_drawaction('O', drawing.draw_boulder)
    grid.set_drawaction('/', drawing.draw_up_line)
    grid.set_drawaction('!', drawing.draw_bomb)
    grid.set_drawaction('*', drawing.draw_money)
    grid.set_drawaction('^', drawing.draw_balloon)
    grid.set_drawaction('@', drawing.draw_hero)
    grid.set_drawaction('M', drawing.draw_monster)
    grid.set_drawaction('S', drawing.draw_baby_monster)
    grid.set_drawaction('+', drawing.draw_cage)
    grid.set_drawaction('<', partial(grid.draw_character_cell, character='←'))
    grid.set_drawaction('>', partial(grid.draw_character_cell, character='→'))

    return grid


if __name__ == '__main__':
    grid = setup_grid()
    game = Game(grid)

    grid.set_timer_action(partial(game.timer_step))
    grid.set_key_action(partial(key_action, game=game))
    grid.set_mouse_click_action(partial(mouse_click, game=game))
    grid.set_update_sidebar_action(game.update_sidebar)
    pygame.key.set_repeat(100, 60)
    game.start_level()
    grid.run()
Пример #11
0
	#				 [0, 0, 0, 0],
	#				 [0, 0, 2, 0],
	#				 [2, 2, 4, 4]]
	game.slide_down()
	result_board = game.get_board()
	assert(result_board[0]==[0,0,0,0])
	assert(result_board[1]==[0,0,0,0])
	assert(result_board[2]==[0,0,2,0])
	assert(result_board[3]==[2,2,4,4])
	print("Passed!")


##  
# Run the tests
##


test_game = Game(0, 4)


test_init(test_game)
test_get_board(test_game)
test_clear_board(test_game)
test_get_empty_squares(test_game)
test_has_valid_move(test_game)

test_spawn_tile(test_game)
test_slide_left(test_game)
test_slide_right(test_game)
test_slide_up(test_game)
test_slide_down(test_game)
Пример #12
0
import queue as q
import threading

from command import Commands
from game_logic import Game
from speech_detector import SpeechDetector

commands_queue = q.Queue()
speech_detector = SpeechDetector(commands_queue)

game = Game(commands_queue)
game_thread = threading.Thread(target=game.game_loop)
game_thread.start()

speech_thread = threading.Thread(target=speech_detector.start_stream)
speech_thread.start()
Пример #13
0
from turtle import Screen, Turtle
from game_logic import Game

game = Game()
turtle = Turtle()
turtle.hideturtle()
turtle.penup()
screen = Screen()
screen.setup(height=491, width=725)
screen.title("U.S. States Game")
screen.bgpic("blank_states_img.gif")

while game.score < 50:
    try:
        guess = screen.textinput(
            title=f"{game.score}/50 states correct", prompt="Guess a State").title()
    except AttributeError:
        continue
    if guess == "Exit":
        game.generate_states_to_learn_csv()
        break
    state_coords = game.take_guess(guess)
    if state_coords:
        turtle.goto(state_coords)
        turtle.write(guess)
Пример #14
0
    def handle_threads(self):
        try:
            is_everyone_disconnected = False

            all_players_connected = False

            sleep(2)

            connected_players = 0
            for _ in range(5):
                connected_players = 0
                for conn_thread in self.connections_threads:
                    if conn_thread.thread.is_connected():
                        connected_players = connected_players + 1
                        is_everyone_disconnected = False
                sleep(0.5)
                all_players_connected = connected_players == len(self.connections_threads)
                if all_players_connected:
                    break
            

            if all_players_connected:
                players_names = []

                # clear all message bins
                for conn_thread in self.connections_threads:
                    self.logger.debug(conn_thread.status.player_name)
                    conn_thread.status.msg_to_send = ''
                    conn_thread.status.received_msg = ''
                    players_names.append(conn_thread.status.player_name)

                app = App(self.username, players_names)

                # initialize list and lock for keyPress event
                pressed_keys_list = []
                pressed_keys_lock = threading.Lock()

                main_game = Game(pressed_keys_list, pressed_keys_lock)
                app.set_game_thread(main_game)

                # wait for app to bootstrap
                while not app.is_running:
                    pass

                # initialize players handlers for easier access to board/game_view/connection_thread
                players_handlers = []
                for idx, player_board in enumerate(app.other_players_boards):
                    game_view = GameView(player_board.player_name_value)
                    player_handler = PlayerHandler(player_board, game_view, self.connections_threads[idx])
                    players_handlers.append(player_handler)

                # make handlers immutable
                players_handlers = tuple(players_handlers)

                # start all game threads
                for player in players_handlers:
                    player.game_view.start()
                main_game.start()

                # while not app.is_screen_destroyed and not app.is_end_game:
                end_game = False
                game_view_end = False
                while not app.is_screen_destroyed and not app.is_end_game:
                    if end_game:
                        break
                    # set new values on host board
                    app.main_player_board.set_player_combo(main_game.get_combo())
                    app.main_player_board.set_player_score(main_game.get_score())
                    app.main_player_board.set_moles_status(main_game.get_board())
                    # get new package to send to other players
                    package = main_game.create_bits_package()
                    for conn_thread in self.connections_threads:
                        # set package to send
                        conn_thread.thread.set_message_to_send(package)
                    for idx, player in enumerate(players_handlers):
                        if player.connection_thread.thread.disconnected:
                            player.board.disconnected = True
                        # set received package in game_view for view update
                        player.game_view.set_package(player.connection_thread.thread.get_received_message())
                        player.board.set_player_combo(player.game_view.get_combo())
                        player.board.set_player_score(player.game_view.get_score())
                        player.board.set_moles_status(player.game_view.get_board())
                        if player.game_view.get_end():
                            # set if any of game views has end_state
                            game_view_end = True
                    if main_game.get_end() or game_view_end:
                        # if any game has ended, wait until all players know about endgame
                        end_game = True
                        if not main_game.get_end():
                            main_game.set_end()
                        for idx, player in enumerate(players_handlers):
                            if not player.connection_thread.thread.disconnected:
                                # await only connected players
                                if not player.game_view.get_end():
                                    end_game = False

                # close GUI after ending game
                # after that, App thread automatically shuts down
                app.callback()
                if end_game:
                    # Get the scoreboard
                    players_scores = []
                    players_scores.append([self.username, int(main_game.get_score())])
                    for idx, player in enumerate(players_handlers):
                        players_scores.append([player.board.player_name_value, int(player.game_view.get_score())])
                    players_scores.sort(key=lambda x:x[1], reverse=True)
                    print('---- Scoreboard ----')
                    for idx, player_score in enumerate(players_scores):
                        print(f'{idx+1}. {player_score[0]} - {player_score[1]}')
                    print('---- Scoreboard ----')
                else:
                    print('Disconnected!')

                # independent of errors in app mainloop - set all games to end, so threads can be closed
                main_game.end = True
                for player in players_handlers:
                    player.game_view.end = True

                # kill all connections
                for connection_thread in self.connections_threads:
                    connection_thread.status.to_kill = True

                # close all threads
                self.logger.debug('Joining main_game')
                app.join()
                main_game.join()
                for player in players_handlers:
                    self.logger.debug(f'Joining {player.board.player_name_value} game_view')
                    player.game_view.join()
                    self.logger.debug(f'Joining {player.board.player_name_value} conn_thread')
                    player.connection_thread.thread.join()
                return
            else:
                print('There were some problems with connection. Shutdown...')
            for connection_thread in self.connections_threads:
                    connection_thread.status.to_kill = True
            for connection_thread in self.connections_threads:
                    connection_thread.thread.join()

        except KeyboardInterrupt as e:
            self.logger.debug('Interrupt in Client')
            self.logger.debug(e)
Пример #15
0
from game_logic import Game

game = Game()
game.start()




Пример #16
0
def init(data):
    data.game = Game(0, 4)
    data.width = 400
    data.height = 400
    data.gameFinished = False