def poll_events(): global selected_seed for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: cleanup() elif Globals.game_state == Globals.Game_State.game_over: Globals.do_quit = True Globals.do_new_game = True elif event.type == QUIT: Globals.do_quit = True elif event.type == MOUSEBUTTONDOWN: if event.button == 1: if Globals.game_state == Globals.Game_State.game_over: Globals.do_quit = True Globals.do_new_game = True return selected_seed = Seeds.get_selected_seed() if selected_seed != -1: if (Seeds.can_plant(selected_seed)): pos = mouse_to_coord(pygame.mouse.get_pos()) if (pos[0] < 0 or pos[0] > Gameboard.Gameboard_size or pos[1] < 0 or pos[1] > Gameboard.Gameboard_size): Seeds.selected_seed = -1 else: Gameboard.plant_seed(pos, Seeds.get_selected_seed()) Seeds.remove_seed(selected_seed) Seeds.selected_seed = -1 else: try_swap() Seeds.check_seed_click(pygame.mouse.get_pos()) elif event.type == MOUSEMOTION: cursor_pos = pygame.mouse.get_pos()
def new_game(): from Graphic_Element import draw_graphic_elements Globals.do_new_game = False Gameboard.random_Gameboard() Score.Reset_Score() Globals.selected_element = (-1, -1) Gameboard.check_availible_moves() set_start_time() set_game_state(Globals.Game_State.ready) Graphic_Element.clear_graphic_elements() Seeds.reset() while not Globals.do_quit: update_ticks() Globals.clock.tick() Globals.screen.fill((0,0,0)) draw_background() game_loop() for x in range(0, Gameboard.Gameboard_size): for y in range(0, Gameboard.Gameboard_size): obj = Gameboard.Gameboard[x][y] if (obj is not None): obj.update() obj.draw(x, y) if not Globals.selected_element == (-1, -1): element = get_selected_element() if element is not None: element.draw_box(Globals.selected_element) draw_score() Seeds.draw_seed_interface() if Globals.game_state != Globals.Game_State.game_over: draw_time_left() draw_graphic_elements(get_ticks()) pygame.display.flip() Globals.clock.tick_busy_loop(60) Globals.do_quit = False
def poll_events(): global selected_seed for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: cleanup() elif Globals.game_state == Globals.Game_State.game_over: Globals.do_quit = True Globals.do_new_game = True elif event.type == QUIT: Globals.do_quit = True elif event.type == MOUSEBUTTONDOWN: if event.button == 1: if Globals.game_state == Globals.Game_State.game_over: Globals.do_quit = True Globals.do_new_game = True return selected_seed = Seeds.get_selected_seed() if selected_seed != -1: if (Seeds.can_plant(selected_seed)): pos = mouse_to_coord(pygame.mouse.get_pos()) if (pos[0] < 0 or pos[0] > Gameboard.Gameboard_size or pos[1] < 0 or pos[1] > Gameboard.Gameboard_size): Seeds.selected_seed = -1 else: Gameboard.plant_seed(pos, Seeds.get_selected_seed()) Seeds.remove_seed(selected_seed) Seeds.selected_seed = -1 else: try_swap() Seeds.check_seed_click(pygame.mouse.get_pos()) elif event.type == MOUSEMOTION: cursor_pos = pygame.mouse.get_pos()
def new_game(): from Graphic_Element import draw_graphic_elements Globals.do_new_game = False Gameboard.random_Gameboard() Score.Reset_Score() Globals.selected_element = (-1, -1) Gameboard.check_availible_moves() set_start_time() set_game_state(Globals.Game_State.ready) Graphic_Element.clear_graphic_elements() Seeds.reset() while not Globals.do_quit: update_ticks() Globals.clock.tick() Globals.screen.fill((0, 0, 0)) draw_background() game_loop() for x in range(0, Gameboard.Gameboard_size): for y in range(0, Gameboard.Gameboard_size): obj = Gameboard.Gameboard[x][y] if (obj is not None): obj.update() obj.draw(x, y) if not Globals.selected_element == (-1, -1): element = get_selected_element() if element is not None: element.draw_box(Globals.selected_element) draw_score() Seeds.draw_seed_interface() if Globals.game_state != Globals.Game_State.game_over: draw_time_left() draw_graphic_elements(get_ticks()) pygame.display.flip() Globals.clock.tick_busy_loop(60) Globals.do_quit = False
def try_swap(): global cursor_pos margin = Globals.margin image_size = Globals.image_size x, y = pygame.mouse.get_pos() x = int(int(x - margin[0]) / image_size) y = int(int(y - margin[1]) / image_size) if not (x < 0 or x >= Gameboard.Gameboard_size or y < 0 or y >= Gameboard.Gameboard_size): if (Globals.selected_element == [x, y]): Globals.selected_element = (-1, -1) elif Globals.selected_element == (-1, -1): Globals.selected_element = [x, y] else: if coord_distance(Globals.selected_element, [x, y]) <= 1: Gameboard.swap_elements(Globals.selected_element, [x, y]) old_swap = ([x, y], Globals.selected_element) ## if we didn't get a match, undo this swap if not Gameboard.check_adjacency(3): Gameboard.swap_elements(old_swap[0], old_swap[1]) return Gameboard.check_drop() set_game_state(Globals.Game_State.animation) Globals.selected_element = (-1, -1) else: Audio.Cancel()
def try_swap(): global cursor_pos margin = Globals.margin image_size = Globals.image_size x,y = pygame.mouse.get_pos() x = int(int(x - margin[0]) / image_size) y = int(int(y - margin[1]) / image_size) if not (x < 0 or x >= Gameboard.Gameboard_size or y < 0 or y >= Gameboard.Gameboard_size): if (Globals.selected_element == [x, y]): Globals.selected_element = (-1, -1) elif Globals.selected_element == (-1, -1): Globals.selected_element = [x, y] else: if coord_distance(Globals.selected_element, [x, y]) <= 1: Gameboard.swap_elements(Globals.selected_element, [x, y]) old_swap = ([x,y], Globals.selected_element) ## if we didn't get a match, undo this swap if not Gameboard.check_adjacency(3): Gameboard.swap_elements(old_swap[0], old_swap[1]) return Gameboard.check_drop() set_game_state(Globals.Game_State.animation) Globals.selected_element = (-1, -1) else: Audio.Cancel()
def run(self): # create the root and the canvas self.GM = Gameboard() self.GM.init(self.canvas, self.root) self.canvas.bind("<Button-1>", self.GM.click) # Bind button to function call self.canvas.tag_bind("DnD", "<ButtonPress-1>", self.GM.down) # Bind button to function call self.canvas.tag_bind("DnD", "<ButtonRelease-1>", self.GM.chkup) # Bind button to function call self.canvas.tag_bind("DnD", "<Enter>", self.GM.enter) # Bind button to function call self.canvas.tag_bind("DnD", "<Leave>", self.GM.leave) # Bind button to function call self.GM.associate_letter_tiles(self.serv.letter_holderPL1) # Diplay first letter holder self.root.mainloop()
def game_loop(): if (get_ticks() >= Globals.end_time and Globals.game_state != Globals.Game_State.game_over): game_over() elif Globals.game_state == Globals.Game_State.ready: poll_events() elif Globals.game_state == Globals.Game_State.animation: do_animations() elif Globals.game_state == Globals.Game_State.update: if Gameboard.check_drop(): set_game_state(Globals.Game_State.animation) elif not Gameboard.check_adjacency(Globals.match_length): set_game_state(Globals.Game_State.ready) Score.Reset_Combo() Globals.current_turn += 1 if not Gameboard.check_availible_moves(): Graphic_Element.make_graphic_element( TextHandler.Render_TextBox("Shuffling Board",(255,255,255)), 250, 250, get_ticks() + 1000) reset_board() elif Globals.game_state == Globals.Game_State.game_over: poll_events()
def game_loop(): if (get_ticks() >= Globals.end_time and Globals.game_state != Globals.Game_State.game_over): game_over() elif Globals.game_state == Globals.Game_State.ready: poll_events() elif Globals.game_state == Globals.Game_State.animation: do_animations() elif Globals.game_state == Globals.Game_State.update: if Gameboard.check_drop(): set_game_state(Globals.Game_State.animation) elif not Gameboard.check_adjacency(Globals.match_length): set_game_state(Globals.Game_State.ready) Score.Reset_Combo() Globals.current_turn += 1 if not Gameboard.check_availible_moves(): Graphic_Element.make_graphic_element( TextHandler.Render_TextBox("Shuffling Board", (255, 255, 255)), 250, 250, get_ticks() + 1000) reset_board() elif Globals.game_state == Globals.Game_State.game_over: poll_events()
def __init__(self, ai_opponent, expert, player1_name, player2_name): self.is_ai_opponent = ai_opponent #Booléen indiquant si une ia est présente ou non self.gameboard = Gameboard(expert) #On initialise le plateau de jeu self.player1 = Player( player1_name, 0, self.gameboard, self.gameboard.hands[0]) #On initialise le joueur 1 self.player2 = Player( player2_name, 1, self.gameboard, self.gameboard.hands[1]) #On initialise le joueur 2 self.Turn = 1 #Numéro du tour self.turnIsDone = True #Booléen indiquant si le tour est terminé ou non self.message = "" #Message à afficher sur la fenêtre de jeu self.scene = pygame.Surface #Surface d'affichage principale de la fenêtre de jeu self.selectedCardNumber = -1 #Numéro de carte sélectionnée (-1: pas de carte sélectionnée) self.selectedFrontierNumber = -1 #Numéro de frontière sélectionnée (-1: pas de carte sélectionnée) self.frontierClaimNumber = -1 #Numéro de frontière à revendiquer sélectionnée (-1: pas de carte sélectionnée) self.cards_stack = pygame.image.load( "resources/cards_stack.png") #Visuel de la pile de cartes self.cards_stack_rect = self.cards_stack.get_rect() self.skip_button = pygame.image.load( "resources/button_skip_turn.png") #Bouton SKIP TURN self.skip_button_rect = self.skip_button.get_rect()
class Scrabble_GUI(Frame): def __init__(self): self.serv = Serv = Serveur() Frame.__init__(self, None) self.pack() self.root = Tk() fields = ("Word Suggested",) self.word = "" print "Available letters : " # To display first available letters in the holder print self.serv.letter_holderPL1 Button(self.root, text="Fetch", command=(lambda v=vars: self.fetch_and_run(v))).pack( side=RIGHT ) # "Fetch suggested word" button self.bind("<Return>", (lambda event, v=vars: self.fetch_and_run(v))) widget2 = Button(self.root, text="Quit", command=self.quit) # "Quit" button widget2.pack(side=RIGHT) margin = 0 # Define the space between each cell of the gameboard cellSize = 60 # Size (in pixels) of the cells canvasWidth = 1100 # Width of the window canvasHeight = 910 # Height of the window self.canvas = Canvas(self.root, width=canvasWidth, height=canvasHeight) self.canvas.pack() self.root.resizable(width=0, height=0) # Store canvas in root and in canvas itself for callbacks self.root.canvas = self.canvas.canvas = self.canvas # Set up canvas data and call init self.canvas.data = {} self.canvas.data["margin"] = margin self.canvas.data["cellSize"] = cellSize self.canvas.data["canvasWidth"] = canvasWidth self.canvas.data["canvasHeight"] = canvasHeight self.canvas.data["rows"] = 15 self.canvas.data["cols"] = 15 def quit(self): ans = askokcancel("Verify exit", "Really quit?") # To make sure the player want to exit the game if ans: Frame.quit(self) def fetch_and_run(self, variables): # Each time the user clicks on "Fetch", the program will... horiz_or_vert = ( self.GM.check_aligned() ) # ...Check if the tiles are aligned and determine if the word is put horizontally or vertically (resp, horiz_or_vert will be equal to 0 and 1) self.word = self.GM.check_over_tiles( horiz_or_vert ) # ... Check Scrabble's basic rule for playing : new words must use older words' letter if horiz_or_vert == 2: print "Not aligned!!!" return 0 # ...get the suggested word from the gameboard if self.serv.check_dict(self.word) == False: # ...Check if the word exists in the dictionnary print self.word + " doesn't exist, try another word!" return 0 else: # If all the previous conditions are met, the algorithm will... print self.word + " was found in the dictionnary, well done!" self.serv.scorePL1 = self.serv.get_score( self.word, self.serv.scorePL1 ) # ...Calculate and update the player's score self.GM.check_other_words() print "Your score : " print self.serv.scorePL1 self.serv.remove_used_letters( self.word, self.serv.letter_holderPL1 ) # ...Remove used letters from the letter holder initialpos = self.GM.get_initialpos(horiz_or_vert) self.GM.put_tiles( self.word, initialpos[1], initialpos[0], horiz_or_vert ) # ...Put the suggested word on the gameboard "for real" (i.e. the player won't be able to move them anymore) self.serv.pick_tiles(self.serv.letter_holderPL1) # ...Fill the letter holder with other tiles self.GM.drawGameboard(self.canvas) self.GM.associate_letter_tiles(self.serv.letter_holderPL1) self.GM.draw_letterHolder( self.canvas, self.root, self.serv.letter_holderPL1 ) # ...Print the new updated letter holder on print "Available letters : " # To display first available letters in the holder print self.serv.letter_holderPL1 def run(self): # create the root and the canvas self.GM = Gameboard() self.GM.init(self.canvas, self.root) self.canvas.bind("<Button-1>", self.GM.click) # Bind button to function call self.canvas.tag_bind("DnD", "<ButtonPress-1>", self.GM.down) # Bind button to function call self.canvas.tag_bind("DnD", "<ButtonRelease-1>", self.GM.chkup) # Bind button to function call self.canvas.tag_bind("DnD", "<Enter>", self.GM.enter) # Bind button to function call self.canvas.tag_bind("DnD", "<Leave>", self.GM.leave) # Bind button to function call self.GM.associate_letter_tiles(self.serv.letter_holderPL1) # Diplay first letter holder self.root.mainloop()
def __init__(self): self.grid = Gameboard.Grid() self.enemySquad = []
def setInitailState(self, inputfile, mode, player_next): self.initial_gameboard = g.Gameboard() self.initial_gameboard.setboardfromfile(inputfile, mode, player_next) self.initial_gameboard.printGameBoard() return self.initial_gameboard
def __init__(self): initial_gameboard = g.Gameboard()
def __init__(self, parent=None): super(mainWindow, self).__init__() self.setObjectName("main") self.setStyleSheet("""#main {background-color: #D1E4EB}""") self.game_phase = "" self.player_name = "" self.grid = Gameboard(self) self.grid.setMinimumHeight(SIZE*GRID_GAP + 4) self.grid.setMinimumWidth(SIZE*GRID_GAP + 4) # CHAT PANEL STUFF self.chatPanel = QtGui.QTextEdit(self) self.chatPanel.setMinimumHeight(360) self.chatPanel.setMaximumHeight(600) self.chatPanel.setMinimumWidth(300) self.chatPanel.setMaximumWidth(360) self.chatPanel.setReadOnly(True) self.chatPanel.setStyleSheet("""color: darkblue; background-color : lightgray; border-radius: 3px; border-style : solid; border-width: 5px; border-color : darkred; """) self.chatInput = QtGui.QLineEdit(self) self.chatInput.setMinimumWidth(300) self.chatInput.setMaximumWidth(360) layout = QtGui.QHBoxLayout() # MIDDLE PANEL STUFF grid_layout = QtGui.QVBoxLayout() title = QtGui.QLabel("Robot Ricochet", self) title.setStyleSheet(""" background-color: lightsteelblue; font-family: Tahoma; font-size: 42px; font-weight : bolder; color : black; """) title.setAlignment(QtCore.Qt.AlignCenter) title.setMinimumWidth(200) title.setMinimumHeight(50) grid_layout.addWidget(title) grid_layout.setAlignment(QtCore.Qt.AlignTop) grid_layout.setContentsMargins(GRID_MARGIN_H, 0, GRID_MARGIN_H, 0) grid_layout.addWidget(self.grid) self.timer_bar = QtGui.QProgressBar(self) self.timer_bar.setInvertedAppearance(True) self.timer_bar.setStyleSheet(""" QProgressBar { text-align : center; color: black; font-size:20px; border: 3px solid darkgreen; border-radius: 7px;} """) grid_layout.addWidget(self.timer_bar) timer = QtCore.QTimer() timer.setInterval(1000) timer.timeout.connect(self.timer_tick) self.phase_timer = timer self.active_player_label = QtGui.QLabel("") chat_layout = QtGui.QVBoxLayout() chat_layout.setAlignment(QtCore.Qt.AlignLeft) chat_layout.setSpacing(10) chat_layout.addWidget(self.chatPanel) chat_layout.addWidget(self.chatInput) self.chatInput.returnPressed.connect(self.send_message_chat) # SCOREBOARD STUFF play_layout = QtGui.QVBoxLayout() self.scoreboard = ScoreBoard(self) self.scoreboard.setMinimumHeight(300) self.scoreboard.setMaximumHeight(300) self.scoreboard.setMinimumWidth(200) self.bids_board = BiddingBoard(self) self.bids_board.setMinimumHeight(300) self.bids_board.setMaximumHeight(300) self.bids_board.setMinimumWidth(200) play_layout.addWidget(self.scoreboard) play_layout.addWidget(self.bids_board) self.bidding_label = QtGui.QLabel("Enter your bid") self.bidding_input = QtGui.QLineEdit() self.bidding_input.setMaxLength(2) self.bidding_input.returnPressed.connect(self.send_bid) play_layout.addWidget(self.bidding_label) play_layout.addWidget(self.bidding_input) play_layout.setAlignment(QtCore.Qt.AlignTop) self.disable_bidding_ui() # SOLUTION INPUT STUFF self.pick_robot_buttons = QtGui.QButtonGroup(self) robot_button_layout = QtGui.QHBoxLayout() red_robot = QtGui.QPushButton() blue_robot = QtGui.QPushButton() yellow_robot = QtGui.QPushButton() green_robot = QtGui.QPushButton() red_robot.setStyleSheet("max-width: 30px;background-color:red;") blue_robot.setStyleSheet("max-width: 30px;background-color:blue;") yellow_robot.setStyleSheet("max-width: 30px;background-color:yellow;") green_robot.setStyleSheet("max-width: 30px;background-color:green;") red_robot.setCheckable(True) blue_robot.setCheckable(True) yellow_robot.setCheckable(True) green_robot.setCheckable(True) self.pick_robot_buttons.addButton(red_robot) self.pick_robot_buttons.setId(red_robot, RED) self.pick_robot_buttons.addButton(blue_robot) self.pick_robot_buttons.setId(blue_robot, BLUE) self.pick_robot_buttons.addButton(yellow_robot) self.pick_robot_buttons.setId(yellow_robot, YELLOW) self.pick_robot_buttons.addButton(green_robot) self.pick_robot_buttons.setId(green_robot, GREEN) self.pick_robot_buttons.setExclusive(True) self.pick_direction_buttons = QtGui.QButtonGroup(self) dir_button_layout = QtGui.QHBoxLayout() to_the_top = QtGui.QPushButton('\u2191') to_the_right = QtGui.QPushButton("\u2192") to_the_bottom = QtGui.QPushButton("\u2193") to_the_left = QtGui.QPushButton("\u2190") to_the_top.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_right.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_bottom.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_left.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_top.setCheckable(True) to_the_right.setCheckable(True) to_the_bottom.setCheckable(True) to_the_left.setCheckable(True) self.pick_direction_buttons.addButton(to_the_top) self.pick_direction_buttons.addButton(to_the_right) self.pick_direction_buttons.addButton(to_the_bottom) self.pick_direction_buttons.addButton(to_the_left) # SET ID self.pick_direction_buttons.setId(to_the_top, TOP) self.pick_direction_buttons.setId(to_the_right, RIGHT) self.pick_direction_buttons.setId(to_the_bottom, BOTTOM) self.pick_direction_buttons.setId(to_the_left, LEFT) self.pick_direction_buttons.setExclusive(True) robot_button_layout.addWidget(red_robot) robot_button_layout.addWidget(blue_robot) robot_button_layout.addWidget(yellow_robot) robot_button_layout.addWidget(green_robot) dir_button_layout.addWidget(to_the_top) dir_button_layout.addWidget(to_the_right) dir_button_layout.addWidget(to_the_bottom) dir_button_layout.addWidget(to_the_left) grid_layout.addLayout(robot_button_layout) grid_layout.addLayout(dir_button_layout) add_move_button = QtGui.QPushButton("NEXT MOVE") add_move_button.setStyleSheet("width:40px") add_move_button.clicked.connect(self.add_move) cancel_move_button = QtGui.QPushButton("X") cancel_move_button.setStyleSheet("max-width:20px") cancel_move_button.clicked.connect(self.cancel_move) submit_solution_button = QtGui.QPushButton("SUBMIT") submit_solution_button.setStyleSheet("width:40px;") submit_solution_button.clicked.connect(self.submit_solution) dir_button_layout.addWidget(add_move_button) dir_button_layout.addWidget(submit_solution_button) # TESTING to ease up ui toggling self.pick_direction_buttons.addButton(add_move_button) self.pick_direction_buttons.addButton(cancel_move_button) self.pick_direction_buttons.addButton(submit_solution_button) self.display_solution = QtGui.QLabel() self.display_solution.setStyleSheet("background-color:white;border: 1px solid pink;") self.player_solution = "" self.disable_resolution_ui() robot_button_layout.addWidget(self.display_solution) robot_button_layout.addWidget(cancel_move_button) layout.addLayout(play_layout) # left column layout.addLayout(grid_layout) # center layout.addLayout(chat_layout) # right self.setLayout(layout) self.setup_socket()
class mainWindow(QtGui.QWidget): def __init__(self, parent=None): super(mainWindow, self).__init__() self.setObjectName("main") self.setStyleSheet("""#main {background-color: #D1E4EB}""") self.game_phase = "" self.player_name = "" self.grid = Gameboard(self) self.grid.setMinimumHeight(SIZE*GRID_GAP + 4) self.grid.setMinimumWidth(SIZE*GRID_GAP + 4) # CHAT PANEL STUFF self.chatPanel = QtGui.QTextEdit(self) self.chatPanel.setMinimumHeight(360) self.chatPanel.setMaximumHeight(600) self.chatPanel.setMinimumWidth(300) self.chatPanel.setMaximumWidth(360) self.chatPanel.setReadOnly(True) self.chatPanel.setStyleSheet("""color: darkblue; background-color : lightgray; border-radius: 3px; border-style : solid; border-width: 5px; border-color : darkred; """) self.chatInput = QtGui.QLineEdit(self) self.chatInput.setMinimumWidth(300) self.chatInput.setMaximumWidth(360) layout = QtGui.QHBoxLayout() # MIDDLE PANEL STUFF grid_layout = QtGui.QVBoxLayout() title = QtGui.QLabel("Robot Ricochet", self) title.setStyleSheet(""" background-color: lightsteelblue; font-family: Tahoma; font-size: 42px; font-weight : bolder; color : black; """) title.setAlignment(QtCore.Qt.AlignCenter) title.setMinimumWidth(200) title.setMinimumHeight(50) grid_layout.addWidget(title) grid_layout.setAlignment(QtCore.Qt.AlignTop) grid_layout.setContentsMargins(GRID_MARGIN_H, 0, GRID_MARGIN_H, 0) grid_layout.addWidget(self.grid) self.timer_bar = QtGui.QProgressBar(self) self.timer_bar.setInvertedAppearance(True) self.timer_bar.setStyleSheet(""" QProgressBar { text-align : center; color: black; font-size:20px; border: 3px solid darkgreen; border-radius: 7px;} """) grid_layout.addWidget(self.timer_bar) timer = QtCore.QTimer() timer.setInterval(1000) timer.timeout.connect(self.timer_tick) self.phase_timer = timer self.active_player_label = QtGui.QLabel("") chat_layout = QtGui.QVBoxLayout() chat_layout.setAlignment(QtCore.Qt.AlignLeft) chat_layout.setSpacing(10) chat_layout.addWidget(self.chatPanel) chat_layout.addWidget(self.chatInput) self.chatInput.returnPressed.connect(self.send_message_chat) # SCOREBOARD STUFF play_layout = QtGui.QVBoxLayout() self.scoreboard = ScoreBoard(self) self.scoreboard.setMinimumHeight(300) self.scoreboard.setMaximumHeight(300) self.scoreboard.setMinimumWidth(200) self.bids_board = BiddingBoard(self) self.bids_board.setMinimumHeight(300) self.bids_board.setMaximumHeight(300) self.bids_board.setMinimumWidth(200) play_layout.addWidget(self.scoreboard) play_layout.addWidget(self.bids_board) self.bidding_label = QtGui.QLabel("Enter your bid") self.bidding_input = QtGui.QLineEdit() self.bidding_input.setMaxLength(2) self.bidding_input.returnPressed.connect(self.send_bid) play_layout.addWidget(self.bidding_label) play_layout.addWidget(self.bidding_input) play_layout.setAlignment(QtCore.Qt.AlignTop) self.disable_bidding_ui() # SOLUTION INPUT STUFF self.pick_robot_buttons = QtGui.QButtonGroup(self) robot_button_layout = QtGui.QHBoxLayout() red_robot = QtGui.QPushButton() blue_robot = QtGui.QPushButton() yellow_robot = QtGui.QPushButton() green_robot = QtGui.QPushButton() red_robot.setStyleSheet("max-width: 30px;background-color:red;") blue_robot.setStyleSheet("max-width: 30px;background-color:blue;") yellow_robot.setStyleSheet("max-width: 30px;background-color:yellow;") green_robot.setStyleSheet("max-width: 30px;background-color:green;") red_robot.setCheckable(True) blue_robot.setCheckable(True) yellow_robot.setCheckable(True) green_robot.setCheckable(True) self.pick_robot_buttons.addButton(red_robot) self.pick_robot_buttons.setId(red_robot, RED) self.pick_robot_buttons.addButton(blue_robot) self.pick_robot_buttons.setId(blue_robot, BLUE) self.pick_robot_buttons.addButton(yellow_robot) self.pick_robot_buttons.setId(yellow_robot, YELLOW) self.pick_robot_buttons.addButton(green_robot) self.pick_robot_buttons.setId(green_robot, GREEN) self.pick_robot_buttons.setExclusive(True) self.pick_direction_buttons = QtGui.QButtonGroup(self) dir_button_layout = QtGui.QHBoxLayout() to_the_top = QtGui.QPushButton('\u2191') to_the_right = QtGui.QPushButton("\u2192") to_the_bottom = QtGui.QPushButton("\u2193") to_the_left = QtGui.QPushButton("\u2190") to_the_top.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_right.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_bottom.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_left.setStyleSheet("QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}") to_the_top.setCheckable(True) to_the_right.setCheckable(True) to_the_bottom.setCheckable(True) to_the_left.setCheckable(True) self.pick_direction_buttons.addButton(to_the_top) self.pick_direction_buttons.addButton(to_the_right) self.pick_direction_buttons.addButton(to_the_bottom) self.pick_direction_buttons.addButton(to_the_left) # SET ID self.pick_direction_buttons.setId(to_the_top, TOP) self.pick_direction_buttons.setId(to_the_right, RIGHT) self.pick_direction_buttons.setId(to_the_bottom, BOTTOM) self.pick_direction_buttons.setId(to_the_left, LEFT) self.pick_direction_buttons.setExclusive(True) robot_button_layout.addWidget(red_robot) robot_button_layout.addWidget(blue_robot) robot_button_layout.addWidget(yellow_robot) robot_button_layout.addWidget(green_robot) dir_button_layout.addWidget(to_the_top) dir_button_layout.addWidget(to_the_right) dir_button_layout.addWidget(to_the_bottom) dir_button_layout.addWidget(to_the_left) grid_layout.addLayout(robot_button_layout) grid_layout.addLayout(dir_button_layout) add_move_button = QtGui.QPushButton("NEXT MOVE") add_move_button.setStyleSheet("width:40px") add_move_button.clicked.connect(self.add_move) cancel_move_button = QtGui.QPushButton("X") cancel_move_button.setStyleSheet("max-width:20px") cancel_move_button.clicked.connect(self.cancel_move) submit_solution_button = QtGui.QPushButton("SUBMIT") submit_solution_button.setStyleSheet("width:40px;") submit_solution_button.clicked.connect(self.submit_solution) dir_button_layout.addWidget(add_move_button) dir_button_layout.addWidget(submit_solution_button) # TESTING to ease up ui toggling self.pick_direction_buttons.addButton(add_move_button) self.pick_direction_buttons.addButton(cancel_move_button) self.pick_direction_buttons.addButton(submit_solution_button) self.display_solution = QtGui.QLabel() self.display_solution.setStyleSheet("background-color:white;border: 1px solid pink;") self.player_solution = "" self.disable_resolution_ui() robot_button_layout.addWidget(self.display_solution) robot_button_layout.addWidget(cancel_move_button) layout.addLayout(play_layout) # left column layout.addLayout(grid_layout) # center layout.addLayout(chat_layout) # right self.setLayout(layout) self.setup_socket() def submit_solution(self): self.send("SOLUTION/"+self.player_name+"/"+self.player_solution) def cancel_move(self): if len(self.player_solution) >= 2: self.player_solution = self.player_solution[:-2] self.display_solution.setText(self.player_solution) def add_move(self): id_dir = self.pick_direction_buttons.checkedId() id_color = self.pick_robot_buttons.checkedId() if id_dir == -1 or id_color == -1 : print("ERROR NEED 2 BUTTON PRESSED") return c = '' if id_color == RED: c = 'R' elif id_color == BLUE: c = 'B' elif id_color == YELLOW: c = 'J' elif id_color == GREEN: c = 'V' d = '' if id_dir == TOP: d = 'H' elif id_dir == RIGHT: d = 'D' elif id_dir == BOTTOM: d = 'B' elif id_dir == LEFT: d = 'G' self.player_solution += c+d self.display_solution.setText(self.player_solution) def timer_tick(self): val = self.timer_bar.value() self.timer_bar.setValue(val+1) def init_reflection_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 300) self.timer_bar.setFormat("REFLECTION PHASE : %vs/%ms") self.phase_timer.start() def init_bidding_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 30) self.timer_bar.setFormat("BIDDING PHASE : %vs/%ms") self.phase_timer.start() def init_resolution_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 60) self.timer_bar.setFormat("RESOLUTION PHASE : %vs/%ms") self.phase_timer.start() def setup_socket(self): self.blockSize = 0 self.tcpSocket = QtNetwork.QTcpSocket(self) self.tcpSocket.readyRead.connect(self.readMessage) self.tcpSocket.connected.connect(self.on_connected) self.tcpSocket.error.connect(self.display_connect_error) self.tcpSocket.connectToHost(HOST, PORT) def display_connect_error(self): error = QtGui.QErrorMessage(self) error.showMessage("Error : could not connect to server " + HOST + ":" + str(PORT)) error.exec_() # blocks until user closes the modal self.close() # once the user closes the error window shut down the app def player_authentication(self): self.get_player_name() self.send("CONNEXION/"+self.player_name) def enable_bidding_ui(self): self.bidding_input.show() self.bidding_label.show() def disable_bidding_ui(self): self.bidding_input.hide() self.bidding_label.hide() def disable_resolution_ui(self): for b in self.pick_robot_buttons.buttons(): b.setDisabled(True) for b in self.pick_direction_buttons.buttons(): b.setDisabled(True) def enable_resolution_ui(self): for b in self.pick_robot_buttons.buttons(): b.setDisabled(False) for b in self.pick_direction_buttons.buttons(): b.setDisabled(False) def send_bid(self): bid = self.bidding_input.text() if bid.isdigit(): if self.game_phase == "Reflection": self.send("TROUVE/"+self.player_name+"/"+bid) elif self.game_phase == "Bidding": self.send("ENCHERE/"+self.player_name+"/"+bid) self.bidding_input.clear() self.player_bid = int(bid) def send_message_chat(self): msg = self.chatInput.text() self.send("DIREATOUS/"+msg) self.chatInput.clear() def on_connected(self): print('Now connected to server') self.player_authentication() def readMessage(self): while self.tcpSocket.bytesAvailable(): msg = str(self.tcpSocket.readLine(), "utf-8") print('received from server : ' + msg) self.handle_server_message(msg) # UGLY AS F**K PYTHON Y U NO SWITCH STATEMENT def handle_server_message(self, msg): split_msg = msg.split("/") instr = split_msg[0] params = split_msg[1:] if instr == "SESSION": walls = params[0] self.grid.set_walls(walls) self.grid.repaint() # self.scoreboard # update scorebard elif instr == "VAINQUEUR": bilan = params[0] self.scoreboard.update_scores(bilan) self.announce_winner(bilan) elif instr == "BIENVENUE": self.initUI() self.scoreboard.addPlayer(self.player_name) elif instr == "CONNECTE": name = params[0].rstrip() self.chatPanel.append(name + " has connected !\n") self.scoreboard.addPlayer(name) elif instr == "SORTI": name = params[0].rstrip() self.chatPanel.append(name + " has disconnected..\n") elif instr == "CHAT": name = params[0].rstrip() text = params[1].rstrip() if name == self.player_name: name_style = "style='color:orangered;font-weight:bold;text-decoration:underline'" else: name_style = "style='color:darkblue;font-weight:bold;'" self.chatPanel.insertHtml("<span " + name_style + ">" + name + \ "<span style='color:black;font-weight:normal;text-decoration:none'> : " + text + "</span></span><br>") elif instr == "SERVER": text = params[0].rstrip() self.chatPanel.insertHtml("<span style='color:red;font-style:italic'> SERVER :: " + text + "</span><br>") elif instr == "TOUR": self.grid.set_problem(params[0]) # remove ( ) as always self.scoreboard.update_scores(params[1]) names = re.findall('[a-zA-Z]+', params[1]) # if the client is in the scoreboard : he is a participant self.game_phase = "Reflection" self.disable_resolution_ui() if self.player_name in names: self.bids_board.empty() self.enable_bidding_ui() self.init_reflection_timer() elif instr == "TUASTROUVE": self.chatPanel.append("Proposal accepted.. switching to bidding phase\n") if self.game_phase == "Reflection": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "ILATROUVE": name = params[0].rstrip() bid = int(params[1].rstrip()) self.bids_board.add_bid(name, bid) if self.game_phase == "Reflection": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "ENDREFLEXION": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "TUENCHERE": self.bids_board.add_bid("Your bid", int(self.player_bid)) elif instr == "ECHECENCHERE": name = params[0].rstrip() if name == self.player_name: # self.chatPanel.append("Your bid was refused : incoherent with your previous bid\n") self.bidding_label.setText("Your bid was refused : incoherent with your previous bid") else: # self.chatPanel.append("Your bid was refused : incoherent with " + name + "'s bid\n") self.bidding_label.setText("Your bid was refused : incoherent with " + name + "'s bid") elif instr == "ILENCHERE": name = params[0].rstrip() nb_moves = int(params[1].rstrip()) if name != self.player_name: self.bids_board.add_bid(name, nb_moves) elif instr == "FINENCHERE": name = params[0].rstrip() self.active_player = name # maybe update so active player is highlighted in the bidding board self.active_player_label.setText(name) # need a method to set active user or something self.game_phase = "Resolution" # need to switch the ui and enable it if active player self.disable_bidding_ui() self.chatPanel.insertHtml("<span 'style=color:darkmagenta'>" + self.active_player + " shall send his solution</span><br>") if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() # just in case self.init_resolution_timer() elif instr == "SASOLUTION": name = params[0].rstrip() moves = params[1].rstrip() self.chatPanel.insertHtml("<span style='color:darkmagenta'>" + self.active_player + "'s proposal : " + moves + "</span><br>") self.grid.animate_solution(moves) # we animates no matter if it's correct elif instr == "BONNE": self.chatPanel.insertHtml("<span 'style=color:darkmagenta'>" + self.active_player + " has succeeded </span><br>") # need to put an end to the turn elif instr == "MAUVAISE": name = params[0].rstrip() self.chatPanel.insertHtml("<span 'style=color:purple'>"+ self.active_player + " has failed.. NEXT</span><br>") self.active_player = name self.active_player_label.setText(name) self.chatPanel.insertHtml("<span 'style=color:purple'>"+ name + " shall send his solution</span><br>") self.init_resolution_timer() if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() elif instr == "TROPLONG": name = params[0].rstrip() self.active_player = name self.active_player_label.setText(name) self.chatPanel.insertHtml("<span 'style=color:purple'>"+ self.active_player + " shall send his solution</span><br>") self.init_resolution_timer() if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() elif instr == "FINRESO": self.chatPanel.insertHtml("<span style='color:purple'>No more players.. end of turn</span><br>") def announce_winner(self, report): objective = re.escape(str(OBJECTIVE_SCORE)) # we build our regexp with the global variable regex_winner = r"\w+," + objective winner = re.findall(regex_winner, report)[0].split(',')[0] self.chatPanel.insertHtml("<span style='color:purple'>"+ str(winner).upper() + " HAS WON BITCHES !</span><br>") def send(self, data): self.tcpSocket.write(QtCore.QByteArray((data+"\n").encode())) def initUI(self): self.resize(WINDOW_WIDTH, WINDOW_HEIGHT) self.setWindowTitle("Robot Ricochet") self.show() def get_player_name(self): input_name, ok = QtGui.QInputDialog.getText(self, 'Welcome', 'Pick your name:') while input_name == "": input_name, ok = QtGui.QInputDialog.getText(self, 'Welcome', 'Try again.. Pick your name:') self.player_name = input_name def closeEvent(self, event): print("CLOSING APP") if self.player_name != "": self.send("SORT/"+self.player_name)
def reset_board(): Score.Reset_Combo() Gameboard.random_Gameboard()
def reset_board(): Score.Reset_Combo() Gameboard.random_Gameboard()
import Gameboard from Game import setShips # Ship list 1 is for player 2, and ship list 2 is for player 1, don't get confused =) shipList1 = [] shipList2 = [] newBoard = Gameboard.Board(8, 8) def main(): # Ship lists are switched here to avoid confusion setShips(shipList2, shipList1, newBoard)
class Game(): #Classe représentant une partie de Schotten Totten def __init__(self, ai_opponent, expert, player1_name, player2_name): self.is_ai_opponent = ai_opponent #Booléen indiquant si une ia est présente ou non self.gameboard = Gameboard(expert) #On initialise le plateau de jeu self.player1 = Player( player1_name, 0, self.gameboard, self.gameboard.hands[0]) #On initialise le joueur 1 self.player2 = Player( player2_name, 1, self.gameboard, self.gameboard.hands[1]) #On initialise le joueur 2 self.Turn = 1 #Numéro du tour self.turnIsDone = True #Booléen indiquant si le tour est terminé ou non self.message = "" #Message à afficher sur la fenêtre de jeu self.scene = pygame.Surface #Surface d'affichage principale de la fenêtre de jeu self.selectedCardNumber = -1 #Numéro de carte sélectionnée (-1: pas de carte sélectionnée) self.selectedFrontierNumber = -1 #Numéro de frontière sélectionnée (-1: pas de carte sélectionnée) self.frontierClaimNumber = -1 #Numéro de frontière à revendiquer sélectionnée (-1: pas de carte sélectionnée) self.cards_stack = pygame.image.load( "resources/cards_stack.png") #Visuel de la pile de cartes self.cards_stack_rect = self.cards_stack.get_rect() self.skip_button = pygame.image.load( "resources/button_skip_turn.png") #Bouton SKIP TURN self.skip_button_rect = self.skip_button.get_rect() def displayGame(self): #Fonction d'affichage de la fenêtre de jeu GAME_WIN_H = 800 #Taille de la fenêtre de jeu GAME_WIN_W = 1120 BG_COLOR = (232, 217, 206) #Couleur de l'arrière plan if self.gameboard.expert_mode: #Changement du titre de la fenêtre suivant le mode de jeu if self.is_ai_opponent: print("Game VS AI is launched in expert mode") pygame.display.set_caption( "Schotten Totten - Game VS AI - Expert mode") else: print("Game 1V1 is launched in expert mode") pygame.display.set_caption( "Schotten Totten - Game 1V1 - Expert mode") else: if self.is_ai_opponent: print("Game VS AI is launched in normal mode") pygame.display.set_caption( "Schotten Totten - Game VS AI - Normal mode") else: print("Game 1V1 is launched in normal mode") pygame.display.set_caption( "Schotten Totten - Game 1V1 - Normal mode") print("Player 1 name is " + self.player1.name) print("Player 2 name is " + self.player2.name) self.scene = pygame.display.set_mode((GAME_WIN_W, GAME_WIN_H)) self.cards_stack = pygame.transform.scale( self.cards_stack, (79, 109)) #Placement du visuel de la pile de cartes sur la fenêtre self.cards_stack_rect.x = math.ceil(1020) self.cards_stack_rect.y = math.ceil(300) self.skip_button = pygame.transform.scale( self.skip_button, (214, 60)) #Placement du bouton SKIP sur la fenêtre self.skip_button_rect.x = math.ceil(890) self.skip_button_rect.y = math.ceil(625) game_running = True while game_running: for event in pygame.event.get( ): #Gestionnaires des évènements de jeu if event.type == pygame.QUIT: #Evènement de fermeture du jeu game_running = False pygame.quit() print("Game is closed") if event.type == pygame.MOUSEBUTTONDOWN: #Evènement de type clic souris for i in range(0, 6): if self.gameboard.player1_cards_rect[i].collidepoint( event.pos) and self.Turn % 2: print("card " + str(i + 1) + " has been selected by player1") self.selectedCardNumber = i for i in range(0, 6): if self.gameboard.player2_cards_rect[i].collidepoint( event.pos) and not self.Turn % 2: print("card " + str(i + 1) + " has been selected by player2") self.selectedCardNumber = i for i in range(0, 9): if self.gameboard.frontiers_p0_rect[i].collidepoint( event.pos): print("frontier " + str(i + 1) + " has been selected") self.selectedFrontierNumber = i if self.gameboard.isGameover( ): #Si la partie est gagnée par un joueur self.scene.fill(BG_COLOR) if self.gameboard.winner == 0: self.message = "{} is the WINNER, congratulations!".format( self.player1.name) elif self.gameboard.winner == 1: self.message = "{} is the WINNER, congratulations!".format( self.player2.name) self.displayMessage() pygame.display.flip() else: self.updateScene() #Mise à jour de la fenêtre de jeu self.playTurn( ) #Permet au tour de se jouer le tour si les conditions sont remplies (voir fonction) def updateScene( self ): #Fonction qui crée une nouvelle surface du jeu en la mettant à jour BG_COLOR = (232, 217, 206) self.scene.fill(BG_COLOR) if self.message != "": self.displayMessage() self.scene.blit(self.cards_stack, self.cards_stack_rect) self.scene.blit(self.skip_button, self.skip_button_rect) self.scene = self.gameboard.displaySides(self.scene) self.scene = self.gameboard.displayFrontiers(self.scene) self.scene = self.gameboard.displayHands(self.scene, self.Turn) pygame.display.flip() def displayMessage( self): #Fonction d'affichage du message en attribut de la classe WHITE = (255, 255, 255) BG_COLOR = (232, 217, 206) BROWN = (155, 111, 76) font = pygame.font.Font("resources/Roboto-bold.ttf", 25) block = pygame.Surface( (1110, 100)) #Création de la surface blanche de fond du message block_rect = block.get_rect() block.fill(BG_COLOR) pygame.draw.rect(block, WHITE, block_rect, border_radius=5) block_rect.x = math.ceil(5) block_rect.y = math.ceil(695) if len( self.message ) > 100: #Affichage du message sur deux lignes si il est trop long line1 = self.message[0:90] + '-' line2 = self.message[90:] message2 = font.render( line2, True, BROWN) #Création du visuel du texte du message sur la ligne 2 message2_rect = message2.get_rect() message2_rect.x = math.ceil(10) message2_rect.y = math.ceil(50) block.blit(message2, message2_rect) else: line1 = self.message message1 = font.render(line1, True, BROWN) #Création du visuel du texte du message message1_rect = message1.get_rect() message1_rect.x = math.ceil(10) message1_rect.y = math.ceil(10) block.blit(message1, message1_rect ) #Affichage du texte du message sur la surface blanche self.scene.blit( block, block_rect) #Affichage du bloc message sur la fenêtre de jeu def playTurn( self ): #Fonction qui gère les tours des joueurs et qui appelle la fonction play() if self.is_ai_opponent and not ( self.Turn % 2): #Si c'est au tour de l'IA de jouer (joueur 2) self.turnIsDone = False self.playAI(self.player2) self.Turn += 1 self.selectedCardNumber = -1 self.selectedFrontierNumber = -1 self.turnIsDone = True elif self.selectedCardNumber != -1 and self.selectedFrontierNumber != -1 and self.turnIsDone: #Si une carte et une frontière sont sélectionnées self.turnIsDone = False if (self.Turn % 2): #Tour du joueur 1 self.message = "Player 1 turn: {}. Select a card and a frontier.".format( self.player1.name) self.displayMessage() self.play(self.player1) else: #Tour du joueur 2 (Si le mode IA n'est pas sélectionné) self.message = "Player 2 turn: {}. Select a card and a frontier.".format( self.player2.name) self.displayMessage() self.play(self.player2) self.Turn += 1 self.selectedCardNumber = -1 self.selectedFrontierNumber = -1 self.turnIsDone = True else: if (self.Turn % 2): self.message = "Player 1 turn: {}. Select a card and a frontier.".format( self.player1.name) else: self.message = "Player 2 turn: {}. Select a card and a frontier.".format( self.player2.name) def play( self, player ): #Fonction qui permet au joueur passé en paramètre de jouer son tour if (player.Hand.Cards[(self.selectedCardNumber)].Type == "Clan"): player.playTroop(self.selectedCardNumber, self.selectedFrontierNumber) self.scene = self.gameboard.displaySides(self.scene) self.message = "Do you want to claim a frontier ? If yes, select a frontier, else, you can skip the turn." self.updateScene() while (self.turnIsDone == False): for event in pygame.event.get(): #Gestionnaire d'évènement if event.type == pygame.QUIT: pygame.quit() print("Game is closed") if event.type == pygame.MOUSEBUTTONDOWN: for i in range(0, 9): if self.gameboard.frontiers_p0_rect[i].collidepoint( event.pos ): #Si clic sur une frontière à revendiquer print("frontier " + str(i + 1) + " has been selected") self.frontierClaimNumber = i if self.skip_button_rect.collidepoint( event.pos): #Si clic sur le bouton SKIP self.turnIsDone = True if self.frontierClaimNumber != -1: self.message = player.claimFrontier( self.frontierClaimNumber ) #Tentative de revendication de la frontière sélectionnée self.updateScene() self.frontierClaimNumber = -1 player.draw() def playAI( self, player ): #Fonction qui permet à l'IA (joueur 2 passé en paramètre) de jouer son tour play = alphaBeta(player.number, self.gameboard.generateState(player.number), 2) print(play) self.selectedCardNumber = play[1] self.selectedFrontierNumber = play[2] if (player.Hand.Cards[(self.selectedCardNumber)].Type == "Clan"): player.playTroop(self.selectedCardNumber, self.selectedFrontierNumber) if len(play[3]) != 0: #Revendication des frontières for frontierClaimNumber in play[3]: self.frontierClaimNumber = frontierClaimNumber player.claimFrontier(self.frontierClaimNumber) self.updateScene() self.frontierClaimNumber = -1 player.draw() self.turnIsDone = True
def __init__(self, parent=None): super(mainWindow, self).__init__() self.setObjectName("main") self.setStyleSheet("""#main {background-color: #D1E4EB}""") self.game_phase = "" self.player_name = "" self.grid = Gameboard(self) self.grid.setMinimumHeight(SIZE * GRID_GAP + 4) self.grid.setMinimumWidth(SIZE * GRID_GAP + 4) # CHAT PANEL STUFF self.chatPanel = QtGui.QTextEdit(self) self.chatPanel.setMinimumHeight(360) self.chatPanel.setMaximumHeight(600) self.chatPanel.setMinimumWidth(300) self.chatPanel.setMaximumWidth(360) self.chatPanel.setReadOnly(True) self.chatPanel.setStyleSheet("""color: darkblue; background-color : lightgray; border-radius: 3px; border-style : solid; border-width: 5px; border-color : darkred; """) self.chatInput = QtGui.QLineEdit(self) self.chatInput.setMinimumWidth(300) self.chatInput.setMaximumWidth(360) layout = QtGui.QHBoxLayout() # MIDDLE PANEL STUFF grid_layout = QtGui.QVBoxLayout() title = QtGui.QLabel("Robot Ricochet", self) title.setStyleSheet(""" background-color: lightsteelblue; font-family: Tahoma; font-size: 42px; font-weight : bolder; color : black; """) title.setAlignment(QtCore.Qt.AlignCenter) title.setMinimumWidth(200) title.setMinimumHeight(50) grid_layout.addWidget(title) grid_layout.setAlignment(QtCore.Qt.AlignTop) grid_layout.setContentsMargins(GRID_MARGIN_H, 0, GRID_MARGIN_H, 0) grid_layout.addWidget(self.grid) self.timer_bar = QtGui.QProgressBar(self) self.timer_bar.setInvertedAppearance(True) self.timer_bar.setStyleSheet(""" QProgressBar { text-align : center; color: black; font-size:20px; border: 3px solid darkgreen; border-radius: 7px;} """) grid_layout.addWidget(self.timer_bar) timer = QtCore.QTimer() timer.setInterval(1000) timer.timeout.connect(self.timer_tick) self.phase_timer = timer self.active_player_label = QtGui.QLabel("") chat_layout = QtGui.QVBoxLayout() chat_layout.setAlignment(QtCore.Qt.AlignLeft) chat_layout.setSpacing(10) chat_layout.addWidget(self.chatPanel) chat_layout.addWidget(self.chatInput) self.chatInput.returnPressed.connect(self.send_message_chat) # SCOREBOARD STUFF play_layout = QtGui.QVBoxLayout() self.scoreboard = ScoreBoard(self) self.scoreboard.setMinimumHeight(300) self.scoreboard.setMaximumHeight(300) self.scoreboard.setMinimumWidth(200) self.bids_board = BiddingBoard(self) self.bids_board.setMinimumHeight(300) self.bids_board.setMaximumHeight(300) self.bids_board.setMinimumWidth(200) play_layout.addWidget(self.scoreboard) play_layout.addWidget(self.bids_board) self.bidding_label = QtGui.QLabel("Enter your bid") self.bidding_input = QtGui.QLineEdit() self.bidding_input.setMaxLength(2) self.bidding_input.returnPressed.connect(self.send_bid) play_layout.addWidget(self.bidding_label) play_layout.addWidget(self.bidding_input) play_layout.setAlignment(QtCore.Qt.AlignTop) self.disable_bidding_ui() # SOLUTION INPUT STUFF self.pick_robot_buttons = QtGui.QButtonGroup(self) robot_button_layout = QtGui.QHBoxLayout() red_robot = QtGui.QPushButton() blue_robot = QtGui.QPushButton() yellow_robot = QtGui.QPushButton() green_robot = QtGui.QPushButton() red_robot.setStyleSheet("max-width: 30px;background-color:red;") blue_robot.setStyleSheet("max-width: 30px;background-color:blue;") yellow_robot.setStyleSheet("max-width: 30px;background-color:yellow;") green_robot.setStyleSheet("max-width: 30px;background-color:green;") red_robot.setCheckable(True) blue_robot.setCheckable(True) yellow_robot.setCheckable(True) green_robot.setCheckable(True) self.pick_robot_buttons.addButton(red_robot) self.pick_robot_buttons.setId(red_robot, RED) self.pick_robot_buttons.addButton(blue_robot) self.pick_robot_buttons.setId(blue_robot, BLUE) self.pick_robot_buttons.addButton(yellow_robot) self.pick_robot_buttons.setId(yellow_robot, YELLOW) self.pick_robot_buttons.addButton(green_robot) self.pick_robot_buttons.setId(green_robot, GREEN) self.pick_robot_buttons.setExclusive(True) self.pick_direction_buttons = QtGui.QButtonGroup(self) dir_button_layout = QtGui.QHBoxLayout() to_the_top = QtGui.QPushButton('\u2191') to_the_right = QtGui.QPushButton("\u2192") to_the_bottom = QtGui.QPushButton("\u2193") to_the_left = QtGui.QPushButton("\u2190") to_the_top.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_right.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_bottom.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_left.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_top.setCheckable(True) to_the_right.setCheckable(True) to_the_bottom.setCheckable(True) to_the_left.setCheckable(True) self.pick_direction_buttons.addButton(to_the_top) self.pick_direction_buttons.addButton(to_the_right) self.pick_direction_buttons.addButton(to_the_bottom) self.pick_direction_buttons.addButton(to_the_left) # SET ID self.pick_direction_buttons.setId(to_the_top, TOP) self.pick_direction_buttons.setId(to_the_right, RIGHT) self.pick_direction_buttons.setId(to_the_bottom, BOTTOM) self.pick_direction_buttons.setId(to_the_left, LEFT) self.pick_direction_buttons.setExclusive(True) robot_button_layout.addWidget(red_robot) robot_button_layout.addWidget(blue_robot) robot_button_layout.addWidget(yellow_robot) robot_button_layout.addWidget(green_robot) dir_button_layout.addWidget(to_the_top) dir_button_layout.addWidget(to_the_right) dir_button_layout.addWidget(to_the_bottom) dir_button_layout.addWidget(to_the_left) grid_layout.addLayout(robot_button_layout) grid_layout.addLayout(dir_button_layout) add_move_button = QtGui.QPushButton("NEXT MOVE") add_move_button.setStyleSheet("width:40px") add_move_button.clicked.connect(self.add_move) cancel_move_button = QtGui.QPushButton("X") cancel_move_button.setStyleSheet("max-width:20px") cancel_move_button.clicked.connect(self.cancel_move) submit_solution_button = QtGui.QPushButton("SUBMIT") submit_solution_button.setStyleSheet("width:40px;") submit_solution_button.clicked.connect(self.submit_solution) dir_button_layout.addWidget(add_move_button) dir_button_layout.addWidget(submit_solution_button) # TESTING to ease up ui toggling self.pick_direction_buttons.addButton(add_move_button) self.pick_direction_buttons.addButton(cancel_move_button) self.pick_direction_buttons.addButton(submit_solution_button) self.display_solution = QtGui.QLabel() self.display_solution.setStyleSheet( "background-color:white;border: 1px solid pink;") self.player_solution = "" self.disable_resolution_ui() robot_button_layout.addWidget(self.display_solution) robot_button_layout.addWidget(cancel_move_button) layout.addLayout(play_layout) # left column layout.addLayout(grid_layout) # center layout.addLayout(chat_layout) # right self.setLayout(layout) self.setup_socket()
class mainWindow(QtGui.QWidget): def __init__(self, parent=None): super(mainWindow, self).__init__() self.setObjectName("main") self.setStyleSheet("""#main {background-color: #D1E4EB}""") self.game_phase = "" self.player_name = "" self.grid = Gameboard(self) self.grid.setMinimumHeight(SIZE * GRID_GAP + 4) self.grid.setMinimumWidth(SIZE * GRID_GAP + 4) # CHAT PANEL STUFF self.chatPanel = QtGui.QTextEdit(self) self.chatPanel.setMinimumHeight(360) self.chatPanel.setMaximumHeight(600) self.chatPanel.setMinimumWidth(300) self.chatPanel.setMaximumWidth(360) self.chatPanel.setReadOnly(True) self.chatPanel.setStyleSheet("""color: darkblue; background-color : lightgray; border-radius: 3px; border-style : solid; border-width: 5px; border-color : darkred; """) self.chatInput = QtGui.QLineEdit(self) self.chatInput.setMinimumWidth(300) self.chatInput.setMaximumWidth(360) layout = QtGui.QHBoxLayout() # MIDDLE PANEL STUFF grid_layout = QtGui.QVBoxLayout() title = QtGui.QLabel("Robot Ricochet", self) title.setStyleSheet(""" background-color: lightsteelblue; font-family: Tahoma; font-size: 42px; font-weight : bolder; color : black; """) title.setAlignment(QtCore.Qt.AlignCenter) title.setMinimumWidth(200) title.setMinimumHeight(50) grid_layout.addWidget(title) grid_layout.setAlignment(QtCore.Qt.AlignTop) grid_layout.setContentsMargins(GRID_MARGIN_H, 0, GRID_MARGIN_H, 0) grid_layout.addWidget(self.grid) self.timer_bar = QtGui.QProgressBar(self) self.timer_bar.setInvertedAppearance(True) self.timer_bar.setStyleSheet(""" QProgressBar { text-align : center; color: black; font-size:20px; border: 3px solid darkgreen; border-radius: 7px;} """) grid_layout.addWidget(self.timer_bar) timer = QtCore.QTimer() timer.setInterval(1000) timer.timeout.connect(self.timer_tick) self.phase_timer = timer self.active_player_label = QtGui.QLabel("") chat_layout = QtGui.QVBoxLayout() chat_layout.setAlignment(QtCore.Qt.AlignLeft) chat_layout.setSpacing(10) chat_layout.addWidget(self.chatPanel) chat_layout.addWidget(self.chatInput) self.chatInput.returnPressed.connect(self.send_message_chat) # SCOREBOARD STUFF play_layout = QtGui.QVBoxLayout() self.scoreboard = ScoreBoard(self) self.scoreboard.setMinimumHeight(300) self.scoreboard.setMaximumHeight(300) self.scoreboard.setMinimumWidth(200) self.bids_board = BiddingBoard(self) self.bids_board.setMinimumHeight(300) self.bids_board.setMaximumHeight(300) self.bids_board.setMinimumWidth(200) play_layout.addWidget(self.scoreboard) play_layout.addWidget(self.bids_board) self.bidding_label = QtGui.QLabel("Enter your bid") self.bidding_input = QtGui.QLineEdit() self.bidding_input.setMaxLength(2) self.bidding_input.returnPressed.connect(self.send_bid) play_layout.addWidget(self.bidding_label) play_layout.addWidget(self.bidding_input) play_layout.setAlignment(QtCore.Qt.AlignTop) self.disable_bidding_ui() # SOLUTION INPUT STUFF self.pick_robot_buttons = QtGui.QButtonGroup(self) robot_button_layout = QtGui.QHBoxLayout() red_robot = QtGui.QPushButton() blue_robot = QtGui.QPushButton() yellow_robot = QtGui.QPushButton() green_robot = QtGui.QPushButton() red_robot.setStyleSheet("max-width: 30px;background-color:red;") blue_robot.setStyleSheet("max-width: 30px;background-color:blue;") yellow_robot.setStyleSheet("max-width: 30px;background-color:yellow;") green_robot.setStyleSheet("max-width: 30px;background-color:green;") red_robot.setCheckable(True) blue_robot.setCheckable(True) yellow_robot.setCheckable(True) green_robot.setCheckable(True) self.pick_robot_buttons.addButton(red_robot) self.pick_robot_buttons.setId(red_robot, RED) self.pick_robot_buttons.addButton(blue_robot) self.pick_robot_buttons.setId(blue_robot, BLUE) self.pick_robot_buttons.addButton(yellow_robot) self.pick_robot_buttons.setId(yellow_robot, YELLOW) self.pick_robot_buttons.addButton(green_robot) self.pick_robot_buttons.setId(green_robot, GREEN) self.pick_robot_buttons.setExclusive(True) self.pick_direction_buttons = QtGui.QButtonGroup(self) dir_button_layout = QtGui.QHBoxLayout() to_the_top = QtGui.QPushButton('\u2191') to_the_right = QtGui.QPushButton("\u2192") to_the_bottom = QtGui.QPushButton("\u2193") to_the_left = QtGui.QPushButton("\u2190") to_the_top.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_right.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_bottom.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_left.setStyleSheet( "QPushButton{max-width: 30px;}QPushButton:checked{background-color:black}" ) to_the_top.setCheckable(True) to_the_right.setCheckable(True) to_the_bottom.setCheckable(True) to_the_left.setCheckable(True) self.pick_direction_buttons.addButton(to_the_top) self.pick_direction_buttons.addButton(to_the_right) self.pick_direction_buttons.addButton(to_the_bottom) self.pick_direction_buttons.addButton(to_the_left) # SET ID self.pick_direction_buttons.setId(to_the_top, TOP) self.pick_direction_buttons.setId(to_the_right, RIGHT) self.pick_direction_buttons.setId(to_the_bottom, BOTTOM) self.pick_direction_buttons.setId(to_the_left, LEFT) self.pick_direction_buttons.setExclusive(True) robot_button_layout.addWidget(red_robot) robot_button_layout.addWidget(blue_robot) robot_button_layout.addWidget(yellow_robot) robot_button_layout.addWidget(green_robot) dir_button_layout.addWidget(to_the_top) dir_button_layout.addWidget(to_the_right) dir_button_layout.addWidget(to_the_bottom) dir_button_layout.addWidget(to_the_left) grid_layout.addLayout(robot_button_layout) grid_layout.addLayout(dir_button_layout) add_move_button = QtGui.QPushButton("NEXT MOVE") add_move_button.setStyleSheet("width:40px") add_move_button.clicked.connect(self.add_move) cancel_move_button = QtGui.QPushButton("X") cancel_move_button.setStyleSheet("max-width:20px") cancel_move_button.clicked.connect(self.cancel_move) submit_solution_button = QtGui.QPushButton("SUBMIT") submit_solution_button.setStyleSheet("width:40px;") submit_solution_button.clicked.connect(self.submit_solution) dir_button_layout.addWidget(add_move_button) dir_button_layout.addWidget(submit_solution_button) # TESTING to ease up ui toggling self.pick_direction_buttons.addButton(add_move_button) self.pick_direction_buttons.addButton(cancel_move_button) self.pick_direction_buttons.addButton(submit_solution_button) self.display_solution = QtGui.QLabel() self.display_solution.setStyleSheet( "background-color:white;border: 1px solid pink;") self.player_solution = "" self.disable_resolution_ui() robot_button_layout.addWidget(self.display_solution) robot_button_layout.addWidget(cancel_move_button) layout.addLayout(play_layout) # left column layout.addLayout(grid_layout) # center layout.addLayout(chat_layout) # right self.setLayout(layout) self.setup_socket() def submit_solution(self): self.send("SOLUTION/" + self.player_name + "/" + self.player_solution) def cancel_move(self): if len(self.player_solution) >= 2: self.player_solution = self.player_solution[:-2] self.display_solution.setText(self.player_solution) def add_move(self): id_dir = self.pick_direction_buttons.checkedId() id_color = self.pick_robot_buttons.checkedId() if id_dir == -1 or id_color == -1: print("ERROR NEED 2 BUTTON PRESSED") return c = '' if id_color == RED: c = 'R' elif id_color == BLUE: c = 'B' elif id_color == YELLOW: c = 'J' elif id_color == GREEN: c = 'V' d = '' if id_dir == TOP: d = 'H' elif id_dir == RIGHT: d = 'D' elif id_dir == BOTTOM: d = 'B' elif id_dir == LEFT: d = 'G' self.player_solution += c + d self.display_solution.setText(self.player_solution) def timer_tick(self): val = self.timer_bar.value() self.timer_bar.setValue(val + 1) def init_reflection_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 300) self.timer_bar.setFormat("REFLECTION PHASE : %vs/%ms") self.phase_timer.start() def init_bidding_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 30) self.timer_bar.setFormat("BIDDING PHASE : %vs/%ms") self.phase_timer.start() def init_resolution_timer(self): self.timer_bar.setValue(0) self.timer_bar.setRange(0, 60) self.timer_bar.setFormat("RESOLUTION PHASE : %vs/%ms") self.phase_timer.start() def setup_socket(self): self.blockSize = 0 self.tcpSocket = QtNetwork.QTcpSocket(self) self.tcpSocket.readyRead.connect(self.readMessage) self.tcpSocket.connected.connect(self.on_connected) self.tcpSocket.error.connect(self.display_connect_error) self.tcpSocket.connectToHost(HOST, PORT) def display_connect_error(self): error = QtGui.QErrorMessage(self) error.showMessage("Error : could not connect to server " + HOST + ":" + str(PORT)) error.exec_() # blocks until user closes the modal self.close() # once the user closes the error window shut down the app def player_authentication(self): self.get_player_name() self.send("CONNEXION/" + self.player_name) def enable_bidding_ui(self): self.bidding_input.show() self.bidding_label.show() def disable_bidding_ui(self): self.bidding_input.hide() self.bidding_label.hide() def disable_resolution_ui(self): for b in self.pick_robot_buttons.buttons(): b.setDisabled(True) for b in self.pick_direction_buttons.buttons(): b.setDisabled(True) def enable_resolution_ui(self): for b in self.pick_robot_buttons.buttons(): b.setDisabled(False) for b in self.pick_direction_buttons.buttons(): b.setDisabled(False) def send_bid(self): bid = self.bidding_input.text() if bid.isdigit(): if self.game_phase == "Reflection": self.send("TROUVE/" + self.player_name + "/" + bid) elif self.game_phase == "Bidding": self.send("ENCHERE/" + self.player_name + "/" + bid) self.bidding_input.clear() self.player_bid = int(bid) def send_message_chat(self): msg = self.chatInput.text() self.send("DIREATOUS/" + msg) self.chatInput.clear() def on_connected(self): print('Now connected to server') self.player_authentication() def readMessage(self): while self.tcpSocket.bytesAvailable(): msg = str(self.tcpSocket.readLine(), "utf-8") print('received from server : ' + msg) self.handle_server_message(msg) # UGLY AS F**K PYTHON Y U NO SWITCH STATEMENT def handle_server_message(self, msg): split_msg = msg.split("/") instr = split_msg[0] params = split_msg[1:] if instr == "SESSION": walls = params[0] self.grid.set_walls(walls) self.grid.repaint() # self.scoreboard # update scorebard elif instr == "VAINQUEUR": bilan = params[0] self.scoreboard.update_scores(bilan) self.announce_winner(bilan) elif instr == "BIENVENUE": self.initUI() self.scoreboard.addPlayer(self.player_name) elif instr == "CONNECTE": name = params[0].rstrip() self.chatPanel.append(name + " has connected !\n") self.scoreboard.addPlayer(name) elif instr == "SORTI": name = params[0].rstrip() self.chatPanel.append(name + " has disconnected..\n") elif instr == "CHAT": name = params[0].rstrip() text = params[1].rstrip() if name == self.player_name: name_style = "style='color:orangered;font-weight:bold;text-decoration:underline'" else: name_style = "style='color:darkblue;font-weight:bold;'" self.chatPanel.insertHtml("<span " + name_style + ">" + name + \ "<span style='color:black;font-weight:normal;text-decoration:none'> : " + text + "</span></span><br>") elif instr == "SERVER": text = params[0].rstrip() self.chatPanel.insertHtml( "<span style='color:red;font-style:italic'> SERVER :: " + text + "</span><br>") elif instr == "TOUR": self.grid.set_problem(params[0]) # remove ( ) as always self.scoreboard.update_scores(params[1]) names = re.findall( '[a-zA-Z]+', params[1] ) # if the client is in the scoreboard : he is a participant self.game_phase = "Reflection" self.disable_resolution_ui() if self.player_name in names: self.bids_board.empty() self.enable_bidding_ui() self.init_reflection_timer() elif instr == "TUASTROUVE": self.chatPanel.append( "Proposal accepted.. switching to bidding phase\n") if self.game_phase == "Reflection": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "ILATROUVE": name = params[0].rstrip() bid = int(params[1].rstrip()) self.bids_board.add_bid(name, bid) if self.game_phase == "Reflection": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "ENDREFLEXION": self.game_phase = "Bidding" self.init_bidding_timer() elif instr == "TUENCHERE": self.bids_board.add_bid("Your bid", int(self.player_bid)) elif instr == "ECHECENCHERE": name = params[0].rstrip() if name == self.player_name: # self.chatPanel.append("Your bid was refused : incoherent with your previous bid\n") self.bidding_label.setText( "Your bid was refused : incoherent with your previous bid") else: # self.chatPanel.append("Your bid was refused : incoherent with " + name + "'s bid\n") self.bidding_label.setText( "Your bid was refused : incoherent with " + name + "'s bid") elif instr == "ILENCHERE": name = params[0].rstrip() nb_moves = int(params[1].rstrip()) if name != self.player_name: self.bids_board.add_bid(name, nb_moves) elif instr == "FINENCHERE": name = params[0].rstrip() self.active_player = name # maybe update so active player is highlighted in the bidding board self.active_player_label.setText(name) # need a method to set active user or something self.game_phase = "Resolution" # need to switch the ui and enable it if active player self.disable_bidding_ui() self.chatPanel.insertHtml("<span 'style=color:darkmagenta'>" + self.active_player + " shall send his solution</span><br>") if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() # just in case self.init_resolution_timer() elif instr == "SASOLUTION": name = params[0].rstrip() moves = params[1].rstrip() self.chatPanel.insertHtml("<span style='color:darkmagenta'>" + self.active_player + "'s proposal : " + moves + "</span><br>") self.grid.animate_solution( moves) # we animates no matter if it's correct elif instr == "BONNE": self.chatPanel.insertHtml("<span 'style=color:darkmagenta'>" + self.active_player + " has succeeded </span><br>") # need to put an end to the turn elif instr == "MAUVAISE": name = params[0].rstrip() self.chatPanel.insertHtml("<span 'style=color:purple'>" + self.active_player + " has failed.. NEXT</span><br>") self.active_player = name self.active_player_label.setText(name) self.chatPanel.insertHtml("<span 'style=color:purple'>" + name + " shall send his solution</span><br>") self.init_resolution_timer() if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() elif instr == "TROPLONG": name = params[0].rstrip() self.active_player = name self.active_player_label.setText(name) self.chatPanel.insertHtml("<span 'style=color:purple'>" + self.active_player + " shall send his solution</span><br>") self.init_resolution_timer() if self.player_name == self.active_player: self.enable_resolution_ui() else: self.disable_resolution_ui() elif instr == "FINRESO": self.chatPanel.insertHtml( "<span style='color:purple'>No more players.. end of turn</span><br>" ) def announce_winner(self, report): objective = re.escape(str( OBJECTIVE_SCORE)) # we build our regexp with the global variable regex_winner = r"\w+," + objective winner = re.findall(regex_winner, report)[0].split(',')[0] self.chatPanel.insertHtml("<span style='color:purple'>" + str(winner).upper() + " HAS WON BITCHES !</span><br>") def send(self, data): self.tcpSocket.write(QtCore.QByteArray((data + "\n").encode())) def initUI(self): self.resize(WINDOW_WIDTH, WINDOW_HEIGHT) self.setWindowTitle("Robot Ricochet") self.show() def get_player_name(self): input_name, ok = QtGui.QInputDialog.getText(self, 'Welcome', 'Pick your name:') while input_name == "": input_name, ok = QtGui.QInputDialog.getText( self, 'Welcome', 'Try again.. Pick your name:') self.player_name = input_name def closeEvent(self, event): print("CLOSING APP") if self.player_name != "": self.send("SORT/" + self.player_name)