def addClient(self,client): if len(self.gameHandlerList) >= 2: return False client.log('join game') gameHandler = GameHandler() client.setHandler(gameHandler) gameHandler.game = self self.gameHandlerList.append(gameHandler) return True
class Game: fpsClock = pygame.time.Clock() _gameHandler = GameHandler() def __init__(self): pass def run(self): self.loadContent() # Game Loop while (True): self.update() self.draw() self.fpsClock.tick(60) def update(self): self._gameHandler.handleInput() self._gameHandler.update() def draw(self): self._gameHandler.draw() def init(self): pass def loadContent(self): self._gameHandler.loadContent() pygame.init()
def __init__(self,defaultM): self.default_message=defaultM #default message that sends parameter for the roboter self.testHandler=TestHandler(defaultM) self.position = [0,0] #position of robot self.orientation=[1,0] #orientation of robot self.next_corner = [None, None] self.game = GameHandler(defaultM,kfirst="E") self.target=[3,0] self.aktivescan=False self.scanidx = 0 self.Field_to_Table= lookUpTable.LookUpTable() # class to cast from an edge to a field and back if self.game.first =="E": print("human player starts") self.aktion="waitUser" self.nextaktion="findUserInput"
def __init__(self, main_window, window_height, window_width): super().__init__() self.game_handler = GameHandler(self) # lists of 5 widgets self.p2_rows_widgets = self.init_player_rows_widgets(initial_height=0) self.p1_rows_widgets = self.init_player_rows_widgets( initial_height=360) # 2D lists. [row][hand] self.p2_card_widgets = [] self.p1_card_widgets = [] self.dealt_card = self.init_dealt_card_ui() self.instructions_label = self.init_instructions_label( height=window_height - 180) self.init_table_card_widgets() self.pointer = GamePointer(self, POINTER_HEIGHT) self.text_box = self.init_text_box() self.state = 0 # 0: playing, 1-5: showing final hands
class SystemHandler: Table = [['N', 'N', 'N', 'N'], ['N', 'N', 'N', 'N'], ['N', 'N', 'N', 'N'], ['N', 'N', 'N', 'N']] #Table loaded all neutral next_corner=[None,None] neutrals =[] neutral_idx=0 active =None dif=None def __init__(self,defaultM): self.default_message=defaultM #default message that sends parameter for the roboter self.testHandler=TestHandler(defaultM) self.position = [0,0] #position of robot self.orientation=[1,0] #orientation of robot self.next_corner = [None, None] self.game = GameHandler(defaultM,kfirst="E") self.target=[3,0] self.aktivescan=False self.scanidx = 0 self.Field_to_Table= lookUpTable.LookUpTable() # class to cast from an edge to a field and back if self.game.first =="E": print("human player starts") self.aktion="waitUser" self.nextaktion="findUserInput" def getEnemyMove(self): #for testing b = input('Choose a number: ') return b def handleMessage(self,message): #handle message message=json.loads(message.decode('utf-8')) #decode the the message print("message:") print(message) if(message.get('Aktion')=="Test"): # for testing print("in test") return self.testHandler.handleMessage(message) if (message.get('Aktion') == "Befehl"): #determine in what state the server is to correctly respond print(self.game.game_on) if not self.game.game_on: #start new game self.game = GameHandler(self.default_message) if self.game.first == "E": self.aktion = "waitUser" self.nextaktion = "findUserInput" if self.aktion=="waitUser": #send wait return self.sendwait() if self.aktion == "UserInputFind": #look for marked field if self.aktivescan: if message.get('found'): #merked field was found inputvalue =self.Field_to_Table.lookUpTable(self.position) return self.endscan(inputvalue) if self.scanidx >= len(self.neutrals): # walked through whole field and npthing found x = input("where did you play?") return self.endscan(x) if self.position == self.Field_to_Table.lookUpField(self.neutrals[self.scanidx]): #nothing found on the current posiiton print("ist das selbe erhöhen") self.scanidx = self.scanidx + 1 return self.handleScan() #determine where to scan next if self.aktion=="sendprep": print("send prep") return self.sendprep() if (self.aktion == "waiting" and self.nextaktion=="UserInputFind"): if self.nextaktion == "UserInputFind": # wenn nicht weitersuchen print("in findUserInput") self.neutrals = self.game.getNeutral() self.scanidx = 0 self.aktivescan = True self.aktion = "UserInputFind" self.nextaktion = "makemove" return self.handleScan() if message.get('Aktion') == "endwait": print("endwait on server") def handleSystem(self,message): print("System message") def findWay(self): # find next field to go self.dif=[self.target[0]-self.position[0],self.target[1]-self.position[1]] #difference if self.dif == [0,0]: #self.target=[None,None] return True if self.testMove(self.getRight()): #print("in r : "+ str(self.testMove(self.orientation))) return "r" if self.testMove(self.getLeft()): #print("in l : "+ str(self.testMove(self.orientation))) return "l" if self.testMove(self.orientation): return "s" ##straight if self.valid(self.getLeft()): return "l" if self.valid(self.getRight()): return "r" print("ERRRRRRRRRROR") return None def doMove(self,m): #execute the move in self table AND add letter for way command to the path that will be send to roboter if m =="s": self.position[0]=self.position[0]+self.orientation[0] self.position[1] = self.position[1] + self.orientation[1] return 's' if m =="r": print("in r") self.position[0] = self.position[0] + self.getRight()[0] self.position[1] = self.position[1] + self.getRight()[1] self.orientation = self.getRight() return 'r' if m =="l": self.position[0] = self.position[0] + self.getLeft()[0] self.position[1] = self.position[1] + self.getLeft()[1] self.orientation=self.getLeft() return 'l' def testMove(self,testmove): # test the given move if its a improvement testmove = self.valid(testmove) #valid function checks if move is possible or out of bounds if testmove == None: return False else : helpdifx=self.dif[0] helpdify=self.dif[1] if helpdifx < 0: helpdifx = helpdifx *-1 if helpdify < 0: helpdify = helpdify *-1 difsum=helpdifx+helpdify diftestx= testmove[0]-self.target[0] diftesty = testmove[1] - self.target[1] if diftestx <0 : diftestx=diftestx *-1 if diftesty <0 : diftesty=diftesty *-1 testsum= diftestx+diftesty if testsum< difsum: return testmove # if move is a improvemnt return the move, else fasle return False def valid(self,move): # checks if given move is a valid move and not out of bounds if self.position[0]+move[0]>3 or self.position[0]+move[0]<0 or self.position[1]+move[1]>3 or self.position[1]+move[1]<0: return None return [self.position[0]+move[0],self.position[1]+move[1]] def testRight(self): self.testMove(self.getRight()) def getRight(self): #return orientation after turning right if self.orientation[0] == 1: return [0,1] if self.orientation[0] ==-1: return [0,-1] if self.orientation[1] == 1: return [-1,0] if self.orientation[1] ==-1: return [1,0] print("ERROR") return None def getLeft(self): #return orientation after turning left if self.orientation[0] == 1: return [0,-1] if self.orientation[0] ==-1: return [0,1] if self.orientation[1] == 1: return [1,0] if self.orientation[1] ==-1: return [-1,0] print("ERROR") return None def findwholeway(self,scan=False): #finds the whole way from the given position to target & returns the way as string loop = False way="" i = 1 while not loop: x = self.findWay() if x == True: break if x == None: break way=way+self.doMove(x) i=i+1 # i brauc ich nicht if scan: #if scanning the robot should scan the neutral points in between the given position and the target if self.Field_to_Table.lookUpTable(self.position) in self.neutrals: self.neutrals.remove(self.Field_to_Table.lookUpTable(self.position)) break return way #return way as string def sendwait(self): #send a wait to the robot print("in send wait") message = self.default_message message['Aktion'] = 'wait' self.aktion="waiting" self.nextaktion="UserInputFind" return message def sendprep(self): #send a preperation to robot (not used) self.target==[0,0] self.aktion = "waitUser" self.nextaktion = "findUserInput" way=self.findwholeway() message = self.default_message message['Aktion'] = "move" message['way'] = way return message def handleScan(self): # handle the scan algorithm if not self.aktivescan: self.neutrals= self.game.getNeutral() #get array of neutral fields self.scanidx=0 #set index to 0 self.aktivescan=True #set sacn to active self.target=self.Field_to_Table.lookUpField(self.neutrals[self.scanidx]) #target first field of the neutral array way=self.findwholeway(scan=True) #find the way message = self.default_message #build message message['Aktion'] = "scan" message['way'] = way return message def endscan(self,inputvalue): #ends the scan, get print(inputvalue) #check if value was correct x = input("yours?") if x == "": move = self.game.getMove(inputvalue) else: move = self.game.getMove(int(x)) self.target = self.Field_to_Table.lookUpField(move) way = self.findwholeway() message = self.default_message message['Aktion'] = "move" message['way'] = way self.scanidx = 0 self.aktivescan = False self.aktion = "sendprep" self.nextaktion = "sendprep" return message def printPos(self): # print position and orientation of robot print("position and orientation of robot") print(self.position) print(self.orientation)
def handleMessage(self,message): #handle message message=json.loads(message.decode('utf-8')) #decode the the message print("message:") print(message) if(message.get('Aktion')=="Test"): # for testing print("in test") return self.testHandler.handleMessage(message) if (message.get('Aktion') == "Befehl"): #determine in what state the server is to correctly respond print(self.game.game_on) if not self.game.game_on: #start new game self.game = GameHandler(self.default_message) if self.game.first == "E": self.aktion = "waitUser" self.nextaktion = "findUserInput" if self.aktion=="waitUser": #send wait return self.sendwait() if self.aktion == "UserInputFind": #look for marked field if self.aktivescan: if message.get('found'): #merked field was found inputvalue =self.Field_to_Table.lookUpTable(self.position) return self.endscan(inputvalue) if self.scanidx >= len(self.neutrals): # walked through whole field and npthing found x = input("where did you play?") return self.endscan(x) if self.position == self.Field_to_Table.lookUpField(self.neutrals[self.scanidx]): #nothing found on the current posiiton print("ist das selbe erhöhen") self.scanidx = self.scanidx + 1 return self.handleScan() #determine where to scan next if self.aktion=="sendprep": print("send prep") return self.sendprep() if (self.aktion == "waiting" and self.nextaktion=="UserInputFind"): if self.nextaktion == "UserInputFind": # wenn nicht weitersuchen print("in findUserInput") self.neutrals = self.game.getNeutral() self.scanidx = 0 self.aktivescan = True self.aktion = "UserInputFind" self.nextaktion = "makemove" return self.handleScan() if message.get('Aktion') == "endwait": print("endwait on server")
import json import os import sys from flask import abort, Flask, jsonify, request, send_from_directory from flask_cors import CORS from GameHandler import GameHandler if not os.path.exists('react-front-end/build'): print( 'The react frontend is not built yet. Please go into the "react-front-end" folder and run "npm install", "npm run build"' ) sys.exit(1) app = Flask('chess', static_folder='react-front-end/build') CORS(app) games_handler = GameHandler() @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): """ The route to the react frontend. """ if path != "" and os.path.exists(app.static_folder + '/' + path): return send_from_directory(app.static_folder, path) else: return send_from_directory(app.static_folder, 'index.html') @app.route('/api/', methods=['GET', 'POST'])
def __init__(self, log_path): self.lock = threading.Lock() self.last_info = "" self.exit = False self.handler = GameHandler(Log(log_path))
class UI: def __init__(self, log_path): self.lock = threading.Lock() self.last_info = "" self.exit = False self.handler = GameHandler(Log(log_path)) # Clears the output def _clear_output(self): os.system("clear") # Used for printing cards def _pretty_list(self, a): count = 0 a = sorted(a) result = "" for index in range(1,len(a)+1): count += 1; if (str(a[index-1]) == "The Coin"): count = 0 break; if ((index == len(a)) or (str(a[index]) != str(a[index-1]))): if (count == 1): result += str(a[index-1]) + "\n" else: result += str(count) + "x " + str(a[index-1]) + "\n" count = 0 return result # Creates a pretty output string def _info(self): # if : # pretty_coin = "Coin played." + "\n" * 2 # else: # pretty_coin = "Coin not played." + "\n" * 2 cards = self.handler.info() pretty_played_self = "### Self ###\n" + self._pretty_list(cards[0]) + "\n" pretty_played_oppo = "### Opponent ###\n" + self._pretty_list(cards[1]) + "\n" return pretty_played_self + pretty_played_oppo # Input def input_thread(self): while(not (self.exit)): keypress = ord(sys.stdin.read(1)) if keypress==10: self.lock.acquire() self._clear_output() input_command = input('Enter command: ') self._clear_output() self.handler.update() if input_command.startswith("search"): search = input_command[7:] print("You played: ") print([x.lower() for x in self.game.played_self].count(search)) print("Opponent played: ") print([x.lower() for x in self.game.played_oppo].count(search)) elif input_command == "oppo": self._clear_output() print("Opponent played:") print(self._pretty_list(self.game.played_oppo)) elif input_command == "self": self._clear_output() print("You played:") print(self._pretty_list(self.game.played_self)) elif input_command == "exit": exit = True break else: print("Not a valid command") input("\nPress any key to return") self._clear_output() self.last_info = self._info(self.game) print(self.last_info) self.lock.release() # Output def output_thread(self): print(self._info()) while(not self.exit): self.handler.update() current_info = self._info() if (self.last_info != current_info): self.lock.acquire() self._clear_output() print(current_info) self.lock.release() self.last_info = current_info else: time.sleep(0.5)
from GameHandler import GameHandler from Card import Card hand1 = Card.list2hand([0, 2, 4, 6]) hand2 = Card.list2hand([1, 3, 5, 7]) g = GameHandler("Alice", "Bill") g.gameLoop()
import qi import os from GameHandler import GameHandler if __name__ == "__main__": ip = os.environ['PEPPER_IP'] connection_url = ip + ":9559" app = qi.Application(["--qi-url=" + connection_url]) app.start() session = app.session motion = session.service('ALMotion') leds = session.service("ALLeds") motion.setExternalCollisionProtectionEnabled('All', False) motion.setCollisionProtectionEnabled('Arms', True) print('arms collison protection: ' + str(motion.getCollisionProtectionEnabled('Arms'))) print('external collison protection: ' + str(motion.getExternalCollisionProtectionEnabled('All'))) motion.wakeUp() GameHandler = GameHandler(session, ip, motion, leds)
class GameWidget(QWidget): global CARD_IMAGES_PATH global SPACE_BETWEEN_ROWS global SPACE_BETWEEN_CARDS_SAME_ROW global POINTER_HEIGHT global FACED_DOWN_CARD_FILENAME global WINNING_MESSAGE global LOSING_MESSAGE def __init__(self, main_window, window_height, window_width): super().__init__() self.game_handler = GameHandler(self) # lists of 5 widgets self.p2_rows_widgets = self.init_player_rows_widgets(initial_height=0) self.p1_rows_widgets = self.init_player_rows_widgets( initial_height=360) # 2D lists. [row][hand] self.p2_card_widgets = [] self.p1_card_widgets = [] self.dealt_card = self.init_dealt_card_ui() self.instructions_label = self.init_instructions_label( height=window_height - 180) self.init_table_card_widgets() self.pointer = GamePointer(self, POINTER_HEIGHT) self.text_box = self.init_text_box() self.state = 0 # 0: playing, 1-5: showing final hands def init_text_box(self): text_box = QLabel(self) text_box.setWordWrap(True) text_box.setAlignment(Qt.AlignCenter) text_box.setGeometry(QRect(725, 435, 190, 100)) font = QFont() font.setPointSize(12) text_box.setFont(font) text_box.setStyleSheet("color: blue; border: 1px solid blue") return text_box def set_text_box_text(self, text): self.text_box.setText(text) def init_dealt_card_ui(self): dealt_card = QLabel(self) dealt_card.setGeometry(QRect(770, 250, 110, 160)) dealt_card.setMinimumSize(QSize(110, 160)) dealt_card.setMaximumSize(QSize(110, 160)) dealt_card.setScaledContents(True) return dealt_card def set_dealt_card(self, card, faced_up=True): if faced_up: file_name = CardsImagesGenerator.get_card_image_name(card) else: file_name = FACED_DOWN_CARD_FILENAME self.dealt_card.setPixmap(QPixmap(CARD_IMAGES_PATH + file_name)) def init_instructions_label(self, height): game_instructions = QLabel(self) game_instructions.setGeometry(QRect(290, height, 371, 16)) font = QFont() font.setPointSize(9) game_instructions.setFont(font) game_instructions.setStyleSheet(u"color: blue") game_instructions.setText( "Use keyboard arrows and enter key. Press ESC to quit the game.") game_instructions.setWordWrap(True) return game_instructions def init_table_card_widgets(self): for i in range(5): layout = QHBoxLayout(self.p2_rows_widgets[i]) layout.setSizeConstraint(QLayout.SetFixedSize) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(SPACE_BETWEEN_CARDS_SAME_ROW) cards = [] for j in range(5): card = QLabel(self.p2_rows_widgets[i]) card.setMinimumSize(QSize(110, 160)) card.setMaximumSize(QSize(110, 160)) card.setScaledContents(True) layout.addWidget(card) cards.append(card) self.p2_card_widgets.append(cards) for i in range(5): layout = QHBoxLayout(self.p1_rows_widgets[i]) layout.setSizeConstraint(QLayout.SetFixedSize) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(SPACE_BETWEEN_CARDS_SAME_ROW) cards = [] for j in range(5): card = QLabel(self.p1_rows_widgets[i]) card.setMinimumSize(QSize(110, 160)) card.setMaximumSize(QSize(110, 160)) card.setScaledContents(True) layout.addWidget(card) cards.append(card) self.p1_card_widgets.append(cards) def init_player_rows_widgets(self, initial_height): h = initial_height widgets = [] for i in range(5): widget = QWidget(self) widget.setGeometry(QRect(60, h + SPACE_BETWEEN_ROWS, 671, 211)) widgets.append(widget) h = h + SPACE_BETWEEN_ROWS return widgets def set_initial_cards(self, initial_cards): """ :param initial_cards: list, 11 initial cards (5 per player + 1 dealt) """ i = 0 for card in self.p1_card_widgets[0]: file_name = CardsImagesGenerator.get_card_image_name( initial_cards[i]) card.setPixmap(QPixmap(CARD_IMAGES_PATH + file_name)) i += 1 for card in self.p2_card_widgets[0]: file_name = CardsImagesGenerator.get_card_image_name( initial_cards[i]) card.setPixmap(QPixmap(CARD_IMAGES_PATH + file_name)) i += 1 self.set_dealt_card(initial_cards[i]) def start_game(self): self.game_handler.start_game() def key_right(self): self.pointer.move_right() def key_left(self): self.pointer.move_left() def key_enter(self): if self.state == 0: self.pointer.act() elif self.state < 5: self.game_handler.calc_winning_hand(self.state - 1) self.state += 1 elif self.state == 5: self.game_handler.calc_winning_hand(self.state - 1) won = self.game_handler.calc_winner() if won: self.set_text_box_text(WINNING_MESSAGE) else: self.set_text_box_text(LOSING_MESSAGE) self.state = 6 def start_p1_turn(self, available_hands): self.pointer.activate(available_hands) def choose_hand(self, chosen_hand): """ :return: """ self.game_handler.p1_play(chosen_hand) def display_card(self, player_num, row, hand, card): """ :param player_num: int, 1/2 :param row: int :param hand: int, 1-5 :param card: card object """ file_name = CardsImagesGenerator.get_card_image_name(card) if player_num == 1: self.p1_card_widgets[row][hand - 1].setPixmap( QPixmap(CARD_IMAGES_PATH + file_name)) elif player_num == 2: if row == 4: self.p2_card_widgets[row][hand - 1].setPixmap( QPixmap(CARD_IMAGES_PATH + FACED_DOWN_CARD_FILENAME)) else: self.p2_card_widgets[row][hand - 1].setPixmap( QPixmap(CARD_IMAGES_PATH + file_name)) def clear_board(self): self.state = 0 for row in self.p2_card_widgets: for card in row: card.setPixmap(QPixmap()) card.setStyleSheet('') for row in self.p1_card_widgets: for card in row: card.setPixmap(QPixmap()) card.setStyleSheet('') def end_game(self): self.state = 1 self.set_text_box_text("Press enter to reveal hand") def highlight_hand(self, player_number, hand_number, card_to_reveal): if player_number == 1: for i in range(5): self.p1_card_widgets[i][hand_number].setStyleSheet( 'border: 2px solid yellow') elif player_number == 2: for i in range(5): self.p2_card_widgets[i][hand_number].setStyleSheet( 'border: 2px solid yellow') file_name = CardsImagesGenerator.get_card_image_name(card_to_reveal) self.p2_card_widgets[4][hand_number].setPixmap( QPixmap(CARD_IMAGES_PATH + file_name))
def main(): GameHandler()