def interface(heights, widths, game_boards, chibi = False, game_solve = None): """ Function that render and allow to interact with the interface heights, widths: sizes of the board game_board: object of the actual game chibi: if True icons start with easter egg """ global height, width, grid_x, grid_y, board,path_numbers, game_board grid_x = 0 grid_y = 0 game_board = game_boards path_numbers = "initial" if chibi: path_numbers = "chibi" height = heights width = widths pygame.init() ttt = pygame.display.set_mode ((height, width + 50)) pygame.display.set_caption ('Sudoku') board = initBoard (ttt) board = initStateBoard(board,game_board) board = renderText(board,grid_x,grid_y,game_board) boxtext = TextBox((300,widths + 10,150,30),command=dumb,clear_on_enter=True,inactive_on_enter=False) running = 1 if game_solve == None: #Solve by human if not chibi: path_numbers = "insert" while (running == 1): #Events created by the player for event in pygame.event.get(): if event.type is QUIT: running = 0 elif event.type is MOUSEBUTTONDOWN: (mouseX, mouseY) = pygame.mouse.get_pos() grid_y_aux,grid_x_aux = boardPos(mouseX, mouseY) if grid_x_aux != None: grid_x = grid_x_aux grid_y = grid_y_aux board = renderText(board,grid_x,grid_y,game_board) if game_board.is_win(): path_numbers = "correct" renderBoardAgain(board,game_board) boxtext.get_event(event) showBoard (ttt, board,boxtext) else: #Solve by Machine if game_solve: path_numbers = "correct" else: path_numbers = "wrong" renderBoardAgain(board,game_board) while (running == 1): for event in pygame.event.get(): if event.type is QUIT: running = 0 boxtext.get_event(event) showBoard (ttt, board,boxtext)
class Control(object): def __init__(self): pg.init() pg.mixer.init() pg.display.set_caption("Dub_It") self.screen = pg.display.set_mode((780,220)) self.clock = pg.time.Clock() self.fps = 60.0 self.done = False self.input = TextBox((30,100,715,75),command=self.speech_to_speech, clear_on_enter=True,inactive_on_enter=False) self.color = (100,100,100) self.prompt = self.make_prompt() pg.key.set_repeat(*KEY_REPEAT_SETTING) def make_prompt(self): font = pg.font.SysFont("arial", 60) message = 'WHAT WOULD TRUMP SAY?' rend = font.render(message, True, pg.Color("red")) return (rend, rend.get_rect(topleft=(80,35))) def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def play_speech(self, speech_path): pg.mixer.music.set_volume(1) pg.mixer.init() sounds.append(pg.mixer.Sound(speech_path)) pg.mixer.Sound.play(sounds[len(sounds)-1]) def speech_to_speech(self, speech): texttospeech(speech) self.play_speech('Final product.wav') def main_loop(self): while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() self.clock.tick(self.fps)
class Control(object): def __init__(self): pg.init() pg.display.set_caption("Input Box") self.screen = pg.display.set_mode((500, 500)) self.clock = pg.time.Clock() self.fps = 60.0 self.done = False self.input = TextBox((100, 100, 150, 30), command=self.change_color, clear_on_enter=True, inactive_on_enter=False) self.color = (100, 100, 100) self.prompt = self.make_prompt() pg.key.set_repeat(*KEY_REPEAT_SETTING) def make_prompt(self): font = pg.font.SysFont("arial", 20) message = 'Please type a color name for background (ex. "red"):' rend = font.render(message, True, pg.Color("white")) return (rend, rend.get_rect(topleft=(10, 35))) def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def change_color(self, id, color): try: self.color = pg.Color(str(color)) except ValueError: print("Please input a valid color name.") def main_loop(self): while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() self.clock.tick(self.fps)
class Control(object): def __init__(self): pg.init() pg.display.set_caption("Input Box") self.screen = pg.display.set_mode((500,500)) self.clock = pg.time.Clock() self.fps = 60.0 self.done = False self.input = TextBox((100,100,150,30),command=self.change_color, clear_on_enter=True,inactive_on_enter=False) self.color = (100,100,100) self.prompt = self.make_prompt() pg.key.set_repeat(*KEY_REPEAT_SETTING) def make_prompt(self): font = pg.font.SysFont("arial", 20) message = 'Please type a color name for background (ex. "red"):' rend = font.render(message, True, pg.Color("white")) return (rend, rend.get_rect(topleft=(10,35))) def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def change_color(self,id,color): try: self.color = pg.Color(str(color)) except ValueError: print("Please input a valid color name.") def main_loop(self): while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() self.clock.tick(self.fps)
class Game(object): """docstring for Game""" def __init__(self, window): self.player = Player() self.loop = True self.window = window width, height = self.window.get_size() self.background = pg.image.load(join(DATA_DIR, 'floor-1256804.jpg')).convert() self.background = pg.transform.scale(self.background, (width, height)) self.sheet = pg.Rect(100, 100, 800, 500) self.input = TextBox((110, 110, 150, 30), command=self.player.set_name, inactive_on_enter=False, active_color=pg.Color('gray')) def event_loop(self): """docstring for event_loop""" for evt in pg.event.get(): if evt.type == QUIT or \ (evt.type == KEYDOWN and evt.key == K_ESCAPE): self.loop = False self.input.get_event(evt) def main_loop(self): """docstring for start""" while self.loop: self.event_loop() self.input.update() self.window.blit(self.background, (0, 0)) pg.draw.rect(self.window, (250, 250, 250), (100, 100, 1080, 520)) self.input.draw(self.window) pg.display.flip() def change_color(self, id, color): try: self.color = pg.Color(str(color)) except ValueError: print("Please input a valid color name.")
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = MasterBedroom(screen, text_box) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): driving.enter() driving.input_box(entry) friend_name = driving.get_user_input(entry) # pygame.time.wait(2) if driving.check_scene(): foyer.enter() if foyer.check_scene(): library.enter() pygame.display.flip()
# enter key is pressed. input = TextBox((100, 250, 600, 30), command=process_input, clear_on_enter=True, inactive_on_enter=False) run = True while run: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: run = False # Send all events to the textbox input.get_event(event) # Check for control+v paste keys = pygame.key.get_pressed() if (keys[pygame.K_RCTRL] or keys[pygame.K_LCTRL]): pass #TODO: PASTE FROM CLIPBOARD # Update the textbox and redraw it input.update() input.draw(screen) pygame.display.update() pygame.quit()
timerbox = TextBox((50, 160, 150, 30), command=nic, clear_on_enter=True, inactive_on_enter=False) end = False while not end: for zet in event.get(): if zet.type == QUIT: end = True if zet.type == MOUSEBUTTONUP: s.event() timer.event(timerbox.final) timerbox.get_event(zet) window.fill(black) timerbox.update() timerbox.draw(window) #if : #timer.event(0,timerbox) '''for button in buttons: button.draw() ''' timer.draw() s.draw() s.print_text() clock.tick(20)
def runGame (self): FPSCLOCK = pygame.time.Clock() mouseButton = 0 mouseDown = False pause = True activeFPS = 10 generation = 1 buttons = [] mousey2 = 200 mousex2 = 200 #arbitrary number history = [] lastUpdate = 0 menuHidden = False hideTime = 0 optionsMode = False modeSwitch = False inputDelayStart = 0 cellColor = DARKGREY bgColor = WHITE drawBox = False inPut = TextBox ((116, 483, 492, 41), command=self.getString, clear_on_enter=True) while True: # event loop DISPLAYSURF.fill (bgColor) mousex = None mousey = None hilight = None currentTime = time.time () # needed for time based events with menu hiding # and generations per second if currentTime - inputDelayStart < 0.5: # input delay modeSwitch = False pygame.event.clear () for event in pygame.event.get (): if event.type == QUIT: terminate () elif event.type == KEYUP and not optionsMode: if event.key == K_ESCAPE: terminate () if event.key == K_SPACE: if pause: pause = False else: pause = True if event.key == K_EQUALS: activeFPS = framesPerSecond (activeFPS, UP) elif event.key == K_MINUS: activeFPS = framesPerSecond (activeFPS, DOWN) if event.key == K_r: self.board = set () generation = 1 history = [] # buttons for regulating generations if event.key == K_i and pause: if history != []: poppedBoard = history.pop () if self.board == poppedBoard and history != []: self.board = history.pop () else: self.board = poppedBoard # we dont want negative numbers in gen count generation -= 1 generation = max (1, generation) elif event.key == K_o and pause: self.board = advance (self.board) history.append (self.board) generation += 1 if event.key == K_h: if menuHidden: menuHidden = False hideTime = 0 else: menuHidden = True hideTime = time.time() elif event.type ==KEYUP: if event.key == K_RETURN: drawBox = False self.saveMode = False self.loadMode = False # mouse events elif event.type == MOUSEBUTTONDOWN: mouseDown = True mouseButton = event.button mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseButton = event.button mouseDown = False if event.type == MOUSEMOTION: if mouseDown == True: mousex, mousey = event.pos # for filling/emptying cells mousex2, mousey2 = event.pos # for menu inPut.get_event (event) if pause and not optionsMode: if mousex != None: x, y = convertCellCoords (mousex, mousey, self.cellSize) if mouseButton == 1 and not inMenuZone (mousex, mousey, menuHidden): self.board.add ((x, y)) elif mouseButton == 3: self.board.discard ((x, y)) history.insert (generation - 1, self.board) elif not optionsMode: if history == []: history.append (self.board) if currentTime - lastUpdate > 1.000/activeFPS: self.board = advance (self.board) lastUpdate = time.time () generation += 1 history.append (self.board) # draw everything drawCells (self.board, self.cellSize, cellColor) drawGrid (self.cellSize) if not menuHidden and not optionsMode: if buttons != []: for butt in range (len (buttons)): if buttons[butt][1].collidepoint (mousex2, mousey2): hilight = butt # handles button presses if buttons != []: if buttons[0][1].collidepoint (mousex2, mousey2) and mouseDown: self.board = set () history = [] generation = 1 elif buttons[2][1].collidepoint (mousex2, mousey2) and mouseDown: pause = False elif buttons[3][1].collidepoint (mousex2, mousey2) and mouseDown: pause = True elif buttons[4][1].collidepoint (mousex2, mousey2) and mouseDown: activeFPS = framesPerSecond (activeFPS, DOWN) elif buttons[5][1].collidepoint (mousex2, mousey2) and mouseDown: activeFPS = framesPerSecond (activeFPS, UP) elif buttons[7][1].collidepoint (mousex2, mousey2) and mouseDown: pygame.event.post(pygame.event.Event (KEYUP, {'key':105, 'mod':0})) elif buttons[9][1].collidepoint (mousex2, mousey2) and mouseDown: pygame.event.post(pygame.event.Event (KEYUP, {'key':111, 'mod':0})) elif buttons[11][1].collidepoint (mousex2, mousey2): drawImage ('images/kb.png') elif buttons[1][1].collidepoint (mousex2, mousey2) and mouseDown: optionsMode = True buttons = menuCraft (activeFPS, generation, bgColor, hilight) drawMenu (buttons) else: if currentTime - hideTime < 3 and menuHidden: # hint time drawHint () #options if optionsMode: control = OptControls (mousex2, mousey2, mouseDown) # options class drawImage ('images/sas.png') printText (self.msg) if control.exitOptions (): modeSwitch = True inputDelayStart = time.time () optionsMode = False drawBox = False self.saveMode = False self.loadMode = False mouseDown = False if control.getColors () != None: bgColor, cellColor = control.getColors () if control.getCellSize () != None: self.cellSize = control.getCellSize () if control.loadPat (): drawBox = True self.loadMode = True if control.savePat (): drawBox = True self.saveMode = True if drawBox: inPut.update () inPut.draw (DISPLAYSURF) pygame.display.flip () pygame.display.update () pygame.display.flip () FPSCLOCK.tick (FPS)
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png').convert_alpha() clock = pygame.time.Clock() intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = Bedroom(screen, text_box) kitchen = Kitchen(screen, text_box) final = Final(screen, text_box) library_puzzle = Library_puzzle() ##### NEW CLASS FOR DISPLAY TEXTBOX ######## Text3 = A_textbox(screen) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) foyer = Foyer(screen, text_box) master_list = ['note1', 'note2', 'watch', 'picture', 'phone', 'locket'] player_list = [] # # def compare_list(player_list, master_list): # if player_list == master_list: # return True # else: # return False ##### driving/foyer/etc text1 set true to display only once in its lifetime in the main loop iterations###### drivingtext1 = True drivingtext3 = True foyertext1 = True foyertext3 = True foyertext5 = True librarytext1 = True kitchentext1 = True bedroomtext1 = True finaltext1 = True while 1: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): print "pass intro" driving.enter() # print 1 ######## DISPLAY TEXT FOR DRIVING SCENE####### if drivingtext1: Text3 = A_textbox(screen) Text3.text_generator(driving_script[0:4]) # tells main loop to stop entering drivingtext1 drivingtext1 = False #call function again to draw over drivingtext1 driving.enter() ####set drivingtext2 = true to begin next set of strings####### drivingtext2 = True pygame.time.delay(1000) ###calling the text generator function with script#### Text3.text_generator(driving_script[4:8]) #this delays the text on the screen so reader can read it driving.enter() if drivingtext3: Text3.text_generator(driving_script[8:11]) #this delays the text on the screen so reader can read it pygame.time.delay(3000) pygame.time.wait(2) drivingtext3 = False input_box(entry, screen) driving.next_scene(entry.check_user_input("1")) if driving.check_scene(): foyer.enter() #####displaying foyer text##### if foyertext1: Text3.text_generator(foyer_script[0:4]) foyertext1 = False foyer.enter() foyertext2 = True pygame.time.delay(1000) Text3.text_generator(foyer_script[4:8]) pygame.time.delay(3000) pygame.time.wait(2) foyertext2 = False foyer.enter() if foyertext3: Text3.text_generator(foyer_script[8:12]) foyertext3 = False foyer.enter() foyertext4 = True pygame.time.delay(1000) Text3.text_generator(foyer_script[12:16]) pygame.time.delay(3000) pygame.time.wait(2) foyertext4 = False foyer.enter() if foyertext5: Text3.text_generator(foyer_script[16:20]) pygame.time.delay(3000) pygame.time.wait(2) foyertext5 = False if moving_scene['library']: library.enter() #####displaying foyer text##### if librarytext1: Text3.text_generator(bw_library[0:4]) librarytext1 = False library.enter() librarytext2 = True pygame.time.delay(1000) Text3.text_generator(bw_library[4:8]) pygame.time.delay(4000) pygame.time.wait(2) if library.puzzle1_active: library_puzzle.display_text(puzzletext5) library_puzzle.puzzle1(entry.get_user_input(),puzzletext6, puzzletext7) input_box(entry, screen) if moving_scene['bedroom']: bedroom.enter() if bedroomtext1: Text3.text_generator(oldman_bedroom[0:4]) bedroomtext1 = False bedroom.enter() bedroomtext2 = True pygame.time.delay(1000) Text3.text_generator(oldman_bedroom[4:8]) pygame.time.delay(3000) pygame.time.wait(2) kitchentext2 = False input_box(entry, screen) if moving_scene['kitchen']: print 3 kitchen.enter() if kitchentext1: Text3.text_generator(gothteen_kitchen[0:4]) kitchentext1 = False kitchen.enter() kitchentext2 = True pygame.time.delay(1000) Text3.text_generator(gothteen_kitchen[4:8]) pygame.time.delay(3000) pygame.time.wait(2) kitchentext2 = False input_box(entry, screen) # if compare_list(master_list, player_list): final.enter() if finaltext1: Text3.text_generator(final[0:4]) finaltext1 = False final.enter() finaltext2 = True pygame.time.delay(1000) Text3.text_generator(final[4:8]) pygame.time.delay(3000) pygame.time.wait(2) finaltext2 = False pygame.display.flip() clock.tick(30) pygame.display.flip() clock.tick(30)
class Prediction: def __init__(self, user, mode, password, museID=None): self.user = user self.password = password self.museID = museID pygame.init() self.width = 600 self.height = 600 pygame.display.set_caption(user + ' Prediction Session') self.screen = pygame.display.set_mode((self.width, self.height)) self.mode = mode self.inputSize = (300, 60) self.inputPosition = (self.width / 2 - self.inputSize[0] / 2, self.height / 2 - self.inputSize[1] / 2) font = pygame.font.Font(None, 50) inputRect = pygame.Rect(self.inputPosition[0], self.inputPosition[1], self.inputSize[0], self.inputSize[1]) self.input = TextBox(inputRect, clear_on_enter=True, inactive_on_enter=False, font=font) self.gameRunning = False self.state = PredictionState.MUSE_DISCONNECTED # 0 = Muse Disconnected, 1 = Session Running, 2 = Finished self.setup_marker_streaming() self.markers = [ [] ] # Each item is array of 2 items - timestamp + the key which was pressed. self.eegData = [ [] ] # Each item is array of timestamp + data for each channel. self.get_eeg_stream(0.5) self.startTime = time() # Timestamp of experiment start. self.finishTime = 0 # Timestamp of experiment finish. self.lastEEGSampleTime = self.startTime def setup_marker_streaming(self): streamName = self.user + ' Prediction Session Markers' self.markerInfo = StreamInfo(streamName, 'Keystroke Markers', 1, 0, 'string', str(uuid.uuid1())) self.markerOutlet = StreamOutlet(self.markerInfo) def get_eeg_stream(self, timeout): eeg_inlet_streams: StreamInlet = resolve_byprop('type', 'EEG', timeout=timeout) for stream in eeg_inlet_streams: if self.museID == None or not stream.name().find( self.museID) == -1: self.eegInlet = StreamInlet(stream) self.eegTimeCorrection = self.eegInlet.time_correction() self.state = PredictionState.RUNNING self.doneCheckEEG = True def push_marker(self, timestamp, currentChar): self.markerOutlet.push_sample( currentChar, timestamp ) # Push key marker with timestamp via LSL for other programs. self.markers.append([timestamp, currentChar]) def pull_eeg_data(self, timeout=0.0, max_samples=360): samples, timestamps = self.eegInlet.pull_chunk( timeout, max_samples) # Pull samples. timestampCount = len(timestamps) if (timestampCount > 0): print('Number of samples: {0} | Time since last: {1}'.format( timestampCount, time() - self.lastEEGSampleTime)) self.lastEEGSampleTime = time() for i in range(0, len(timestamps)): self.eegData.append([timestamps[i]] + samples[i]) def check_password(self): passwordInput = ''.join(str(x) for x in self.input.buffer) if passwordInput == self.password: print('correct!') else: print('incorrect!') print(passwordInput) def draw_static_ui(self): fontPassEnt = pygame.font.Font(None, 40) if self.state == PredictionState.RUNNING: instruct = self.user + ' type your password below, press ENTER when done:' elif self.state == PredictionState.MUSE_DISCONNECTED: instruct = 'Error: a Muse LSL stream must be active to continue (Muse ID: {0})'.format( self.museID) else: instruct = 'Finished session. This window will close in a moment.' fontInstruct = pygame.font.Font(None, 24) instructS = fontInstruct.render(instruct, 1, (0, 0, 0)) instructSize = fontInstruct.size(instruct) self.screen.blit(instructS, (self.width / 2 - instructSize[0] / 2, self.height / 4 - instructSize[1] / 2)) def process_input(self): for event in pygame.event.get(): if self.state == PredictionState.RUNNING: if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: self.check_password() self.input.get_event(event) if event.type == pygame.QUIT: pygame.quit() def process_logic(self): if self.state == PredictionState.MUSE_DISCONNECTED: if self.doneCheckEEG == True: self.doneCheckEEG = False threading.Thread(target=self.get_eeg_stream, kwargs={ 'timeout': 5 }).start() elif self.state == PredictionState.RUNNING: self.pull_eeg_data() elif self.state == PredictionState.FINISHED: if self.finishTime == 0: self.finishTime = time() self.save_data() if time() - self.finishTime >= 3: self.gameRunning = False self.input.update() def draw(self): self.screen.fill((255, 255, 255)) self.draw_static_ui() if self.state == PredictionState.RUNNING: self.input.draw(self.screen) pygame.display.flip() def start(self): self.gameRunning = True while self.gameRunning: self.process_input() self.process_logic() self.draw() pygame.quit()
class Control(object): def __init__(self): pg.init() pg.display.set_caption("Online Chat Yeah!!!") self.screen = pg.display.set_mode((500, 500)) self.clock = pg.time.Clock() self.fps = 60.0 self.done = False self.input = TextBox((100, 400, 300, 30), command=self.enter_message, clear_on_enter=True, inactive_on_enter=False) self.color = (100, 100, 100) self.prompt = self.make_prompt() pg.key.set_repeat(*KEY_REPEAT_SETTING) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.connect((IP_ADDRESS, PORT)) self.messages = [] def make_prompt(self): font = pg.font.SysFont("arial", 20) message = 'Please type you message here:' rend = font.render(message, True, pg.Color("white")) return (rend, rend.get_rect(topleft=(10, 35))) def make_messages(self): font = pg.font.SysFont("arial", 20) out = [] y = 65 for message in self.messages: rend = font.render(message, True, pg.Color("white")) out.append((rend, rend.get_rect(topleft=(10, y)))) y += 30 return out def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def update_messages(self, message): while len(self.messages) > 10: self.messages.pop(0) self.messages.append(message) def enter_message(self, id, message): self.update_messages("<You>: {}".format(message)) self.send_message(message) def send_message(self, message): try: message_header = f"{len(message):<{HEADER_LENGTH}}" self.server.send(message_header.encode() + message.encode()) except ValueError: print("Please input a valid message.") def receive_message(self): while True: try: message = self.server.recv(2048) if message: message = message.decode() self.update_messages(message) except: print("Closing", self.server) self.server.close() def start_network_thread(self): t = threading.Thread(target=self.receive_message) t.setDaemon(True) t.start() def main_loop(self): self.start_network_thread() while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) for msg in self.make_messages(): self.screen.blit(*msg) pg.display.update() self.clock.tick(self.fps)
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') final_text_box = pygame.image.load('./images/final_text_box.png') intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = Bedroom(screen, text_box) kitchen = Kitchen(screen, text_box) final = Final(screen, final_text_box) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): driving.enter() input_box(entry, screen) friend_name = get_user_input(entry) if drivingtext1: driving_a.text_generator( "You're driving with your best friend, heading home after a day of hiking.", (100, 460)) driving_b.text_generator( "Rain is beating hard on the roof of your car, the wipers swishing fast.", (100, 490)) driving_c.text_generator( "Your GPS takes you to some backroads, empty of light and other cars.", (100, 520)) driving_d.text_generator( "Suddenly, you and your friend jolt in your seats! You've hit something!", (100, 550)) #tells main loop to stop entering drivingtext1 drivingtext1 = False #call function again to draw over drivingtext1 driving.enter() drivingtext2 = True pygame.time.delay(1000) driving_a.text_generator("What do you do? Enter a number:", (100, 460)) driving_b.text_generator( "1. Get out of the car and check it out.", (100, 490)) driving_c.text_generator("2. Stay in the car.", (100, 520)) driving_d.text_generator("3. Quit Game. This is too scary.", (100, 550)) pygame.time.delay(2000) # if user_input == 1: # if drivingtext3: # driving_a.text_generator("You leave your car, but see nothing What did you hit?", (100,460)) # driving_b.text_generator("When you go back inside the car, it won't start.", (100,490)) # driving_c.text_generator("Nothing you true works. Your and your friend try you phones.", (100,520)) # driving_d.text_generator("No signal. You see a huge house not too far off, its lights on.", (100, 550)) # # drivingtext3 = False # # driving.enter() # # drivingtext4 = True # pygame.time.delay(2000) # # driving_a.text_generator("What do you do next? Enter a number:", (100,460)) # driving_b.text_generator("1. Go the mansion for help.", (100,490)) # driving_d.text_generator("2. Stay in the car.", (100, 550)) # driving_d.text_generator("3. Quit game. This is too scary.", (100, 550)) # # pygame.time.delay(2000) # if user_input == 2: # # if drivingtext4: # driving_a.text_generator("Your friend says,'That sounded awful.' We should check it out.", (100,460)) # driving_b.text_generator("You both leave the car, but see nothing. What did you hit?", (100,490)) # driving_c.text_generator("When you back inside, the car won't start. Nothing you try works.", (100,520)) # driving_d.text_generator("You try your cell phones. No signal. You see a huge house ahead, its lights on.", (100, 550)) # # if user_input == 3: # sys.exit() # # drivingtext4 = False # # driving.enter() # # drivingtext5 = True # pygame.time.delay(2000) # # driving_a.text_generator("What do you do next? Enter a number:", (100,460)) # driving_b.text_generator("1. Go the mansion for help.", (100,490)) # driving_c.text_generator("2. Quit game. This is too scary.", (100, 550)) # # pygame.time.delay(2000) # # # if user_input == 1 #not sure what do here, call the driving.check_scene() function? # if user_input == 3: # sys.exit() # # driving. text_generator("") # pygame.time.delay(60) pygame.time.wait(2) if driving.check_scene(): foyer.enter() if foyertext1: driving_a.text_generator( "You enter the house with your friend and ring the bell. No answer.", (100, 460)) driving_b.text_generator( "Your friend shrugs and pushes the door. You both enter and see three", (100, 490)) driving_c.text_generator( "people standing in the foyer: an elderly man, a woman in a red dress and heels,", (100, 520)) driving_d.text_generator("and a teenage boy in goth makeup.", (100, 550)) #tells main loop to stop entering foyertext1 foyertext1 = False #call function again to draw over foyertext1 foyer.enter() foyertext2 = True pygame.time.delay(1000) driving_a.text_generator("What do you do? Enter a number:", (100, 460)) driving_b.text_generator("1. Talk to the elderly man", (100, 490)) driving_c.text_generator("2. Talk to the beautiful woman.", (100, 520)) driving_d.text_generator("3. Talk to the gothic teenager.", (100, 550)) pygame.time.delay(2000) # if user_input == 1: # if foyertext3: # driving_a.text_generator("'Well, hello there! Welcome to my home. I'm Sir Rupert Wilkinson,''", (100,460)) # driving_b.text_generator("the old man says. 'What brings you here on such a rainy night as this?'", (100,490)) # driving_a.text_generator("You tell him how your car broke down and need to use a phone.", (100,460)) # driving_b.text_generator("'That's terrible! Of course you can use my phone, of course!''", (100,490)) # # foyertext3 = False # # foyer.enter() # # foyertext4 = True # # pygame.time.delay(2000) # # driving_a.text_generator("Suddenly the lights flicker off and on! Your friend screams!", (100,460)) # driving_b.text_generator("You find your frined splayed on the floor in an X, unconsious.", (100,490)) # driving_a.text_generator("You check your friend's pulse. Nothing. You heartbeat spikes.", (100,460)) # driving_b.text_generator("You panic and run for the door but it's locked! You turn around.", (100,490)) # # # pygame.time.delay(2000) # foyer.enter() # # if foyertext5: # driving_a.text_generator("Sir Wilkinson says,'Now, now. No running away! I'm afraid one", (100,460)) # driving_b.text_generator("of use killed your dear friend. Let's play a game, shall we?'", (100,490)) # driving_c.text_generator("'If you can figure out which one of is the killer, we will let you go.'", (100,520)) # driving_d.text_generator("'However, make the wrong guess and you will die too'", (100, 550)) # driving_e.text_generator("'Now, which room shall you enter to look for clues?'") # # foyertext5 = False # # foyer.enter() # # foyertext6 = True # pygame.time.delay(2000) # # driving_a.text_generator("Which room will you go to? Enter a number.", (100,460)) # driving_b.text_generator("1. Enter the library", (100,490)) # driving_c.text_generator("2. Enter the kitchen", (100,520)) # driving_d.text_generator("3 Enter the master bedroom", (100, 550)) # # pygame.time.delay(2000) if foyer.check_scene(): final.enter() pygame.display.flip()
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') clock = pygame.time.Clock() intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = Bedroom(screen, text_box) kitchen = Kitchen(screen, text_box) final = Final(screen, text_box) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) message = (ScrollText( screen, "You're driving with your best friend, heading home after a day of hiking.", 400, pygame.Color(255, 255, 0)), ) fps = 25 foyer = Foyer(screen, text_box) while 1: clock.tick(fps) events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): driving.enter() for thing in message: thing.update() # driving.text_generator("You're driving with your best friend, heading home after a day of hiking.", (100, 300)) # driving.text_generator("Rain is beating hard on the roof of your car, the wipers swishing fast.", (100,400)) # driving.text_generator("Your GPS takes you to some backroads, empty of light and other cars.", (100,500)) # driving.text_generator("Suddenly, you and your friend jolt in your seats! You've hit something!", (100, 600)) # #tells main loop to stop entering drivingtext1 #call function again to draw over drivingtext1 # driving.text_generator("What do you do? Enter a number:", (100,460)) # driving.text_generator("1. Get out of the car and check it out.", (100,490)) # driving.text_generator("2. Stay in the car.", (100,520)) # driving.text_generator("3. Quit Game. This is too scary.", (100, 550)) # pygame.time.wait(2) if driving.check_scene(): foyer.enter() if driving.check_scene(): foyer.enter() if foyer.check_scene(): library.enter() input_box(entry) pygame.display.flip()
def send(idn, text): #message=raw_input(": ") message = str(text) s = socket(AF_INET, SOCK_STREAM) s.connect((IP, PORT)) s.send(message) datas.append(message) data = s.recv(size) s.close() timerbox = TextBox((0, 590, 840, 40), command=send, clear_on_enter=True, inactive_on_enter=False) end = False while not end: for z in pygame.event.get(): if z.type == pygame.QUIT: end = True timerbox.get_event(z) draw() timerbox.update() timerbox.draw(window) clock.tick(20) pygame.display.flip()
class Control1(object): def __init__(self): pg.init() pg.display.set_caption("Road Runner") self.screen = pg.display.set_mode((800, 600)) self.clock = pg.time.Clock() self.fps = 80.0 self.done = False self.input = TextBox((200, 135, 150, 30), command=self.change_color, clear_on_enter=True, inactive_on_enter=False) self.color = (0, 0, 0) self.prompt = self.make_prompt( 20, 10, 100, 'Enter A Number For Registration Which Will Be Used During Your Login' ) self.prompt1 = self.make_prompt(20, 10, 135, 'Username') self.prompt2 = self.make_prompt(40, 300, 35, 'Road Runner') pg.key.set_repeat(*KEY_REPEAT_SETTING) def make_prompt(self, font, size1, size2, text): font = pg.font.SysFont("arial", font) message = text rend = font.render(message, True, pg.Color("white")) return (rend, rend.get_rect(topleft=(size1, size2))) def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def change_color(self, id, color): zero = 0 app = Control() try: f = open("data/login.dat", "r") #for i in range(2): for columns in (raw.strip().split() for raw in f): if (isinstance(int(color), int)): if (columns[0] != str(color)): f = open("data/login.dat", "a") f.write("%s %s\n" % (color, zero)) drawText( 'Register Successful.Please Press Esc key To start The Level 1', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) pygame.display.update() waitForPlayerToPressKey0() else: drawText('Username Already Exists.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) #drawText('\nPress ESC key to enter new username', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) pygame.display.update() waitForPlayerToPressKey4() else: drawText('Only Digits as Username', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) pygame.display.update() waitForPlayerToPressKey4() except ValueError: drawText('Only Digits as Username', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) pygame.display.update() waitForPlayerToPressKey4() def main_loop(self): while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) self.screen.blit(*self.prompt1) self.screen.blit(*self.prompt2) pg.display.update() self.clock.tick(self.fps)
def OfflinePauseMenu(mainGame, screen, clock): save_file_box = TextBox( (340, 300, 560, 50), clear_on_enter=False, inactive_on_enter=False, active=False, active_color=pygame.Color( "red")) #Create text box for storing save file path save_file_box.buffer = list( mainGame.save_path ) #list() is used to convert string into array of characters music_box = pygame.Rect(100, 200, 40, 40) font_48 = pygame.font.SysFont( 'Arial', 48) #Fonts used for texts, of various sizings font_60 = pygame.font.SysFont('Arial', 60) font_40 = pygame.font.SysFont('Arial', 40) font_28 = pygame.font.SysFont('Arial', 28) enable_txt = "Enable" if mainGame.autosave: enable_txt = "Disable" pause_buts = [ Button(150, 425, 300, 80, "Save and Exit", font_40), Button(600, 425, 300, 80, "Exit Without Saving", font_40), Button(75, 620, 400, 80, "Save and Restart", font_40), Button(550, 620, 400, 80, "Restart Without Saving", font_40), Button(750, 10, 200, 80, "Resume", font_60), Button(910, 300, 90, 50, "Change", font_28), Button(910, 360, 90, 50, enable_txt, font_28) ] msgBox = None #Will become MessageBox object as required pause_title = font_60.render("The Game is Paused", True, (0, 0, 0)) #Generate text for titles settings_txt = font_60.render("Settings:", True, (0, 0, 0)) #Settings sub-heading toggle_txt = font_48.render("Toggle Background Music", True, (0, 0, 0)) #Text next to check box save_txt = font_60.render("Save Game:", True, (0, 0, 0)) #Save Game sub-heading save_file_txt = font_48.render("Save File Path:", True, (0, 0, 0)) #Title of save path text box new_txt = font_60.render("New Game:", True, (0, 0, 0)) #New game sub-heading autosave_txt = [ font_48.render("Autosave is currently off", True, (0, 0, 0)), font_48.render("Autosave is currently on", True, (0, 0, 0)) ] music_box_click = False pause_menu_running = True while pause_menu_running: for event in pygame.event.get(): for but in pause_buts: but.handle_input_event(event) if msgBox != None: #If a MessageBox has been created msgBox.handle_input_event(event) if msgBox.should_exit == False: break #Exit for loop; do not register any other objects if event.type == pygame.QUIT: pause_menu_running = False gotoScreen = -1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: #Escape key exits the game pause_menu_running = False #This screen will no longer run gotoScreen = -1 #Game will completely exit if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: #Left mouse button if music_box.collidepoint( event.pos ): #Check box for toggling background music music_box_click = True save_file_box.get_event( event ) #Function that allows each textbox to register key presses and the like screen.fill((255, 255, 255)) #Clear the screen pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(50, 20, 20, 60)) #Rectangles for pause symbol pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(80, 20, 20, 60)) screen.blit(pause_title, [120, 10]) screen.blit(settings_txt, [10, 110]) pygame.draw.rect(screen, (0, 0, 0), music_box, 2) #Display blank check box if not mainGame.pause: #If music is unpaused, check box needs to be checked pygame.draw.line( screen, (0, 0, 0), [102, 220], [115, 238], 4) #Display two lines corresponding to the two parts of a tick pygame.draw.line(screen, (0, 0, 0), [115, 238], [145, 195], 4) screen.blit(toggle_txt, [150, 190]) screen.blit(save_txt, [10, 240]) screen.blit(save_file_txt, [30, 300]) screen.blit(new_txt, [10, 550]) save_file_box.update() #Update the textbox based on events save_file_box.draw(screen) #Draw the text box and contents on screen screen.blit(autosave_txt[int(mainGame.autosave)], [30, 360]) if pause_buts[5].clicked(): #Button for updating save file path valid = True #Whether the file path entered is valid if save_file_box.getContents()[-3:].lower( ) != "dfo": #Must have correct file ending, or invalid msgBox = MessageBox( screen, 'Invalid file. Please ensure the entered file has the correct .dfo file ending.', 'File Error') valid = False #Path is not valid as wrong file ending if valid: try: os.makedirs(os.path.dirname(save_file_box.getContents()), exist_ok=True) f = open(save_file_box.getContents(), 'w+') except: #Any error occurs in creating the directory or file msgBox = MessageBox( screen, 'Invalid save file entered. Please ensure the path entered exists and you have permissions to access it (the file does not have to)', 'Invalid Save File') valid = False #Path is not valid as cannot be created without error if valid: mainGame.save_path = save_file_box.getContents( ) #Update save file within the Game object mainGame.saveGame() #Save the game in the newly entered file if pause_buts[6].clicked( ): #Button for toggling autosave feature on/off mainGame.autosave = not mainGame.autosave #Toggle the boolean value of autosave if mainGame.autosave: pause_buts[6].updateCap("Disable") else: pause_buts[6].updateCap("Enable") if pause_buts[0].clicked(): #Save and Exit mainGame.saveGame() #Save game pause_menu_running = False #This screen no longer running gotoScreen = -1 #Don't go to any other screen (i.e. exit completely) if pause_buts[1].clicked(): #Exit without saving pause_menu_running = False #This screen no longer running gotoScreen = -1 #Don't go to any other screen (i.e. exit completely) if pause_buts[2].clicked(): #Save and restart mainGame.saveGame() #Save the game pause_menu_running = False #This screen no longer running gotoScreen = 0 if pause_buts[3].clicked(): #Restart without saving pause_menu_running = False #This screen no longer running gotoScreen = 0 #Goto new game screen if pause_buts[4].clicked(): #Resume pause_menu_running = False gotoScreen = 1 if music_box_click: #Check box for background music if mainGame.pause: #Music is currently paused pygame.mixer.music.unpause() #Unpause music else: #Music is currently unpaused pygame.mixer.music.pause() #Pause music mainGame.pause = not mainGame.pause #Toggle state of pause in Game class if msgBox != None: #If a MessageBox has been created msgBox.update() #Update message box with relevant events if msgBox.should_exit == False: #If message box should be showing msgBox.draw(screen) #Draw message box on screen for but in pause_buts: but.render(screen) music_box_click = False clock.tick(10) #10 fps pygame.display.flip() #Refresh screen return mainGame, gotoScreen #Pass the Game object and the integer storing where the game will go to next back out to the main game loop
class Control(object): def __init__(self): pg.init() pg.display.set_caption("Road Runner") self.screen = pg.display.set_mode((800, 600)) self.clock = pg.time.Clock() self.fps = 60.0 self.done = False self.input = TextBox((200, 135, 150, 30), command=self.change_color, clear_on_enter=True, inactive_on_enter=False) self.color = (0, 0, 0) self.prompt = self.make_prompt(20, 10, 100, 'Please Login!') self.prompt1 = self.make_prompt(20, 10, 135, 'Username') self.prompt2 = self.make_prompt(40, 300, 35, 'Road Runner') pg.key.set_repeat(*KEY_REPEAT_SETTING) def make_prompt(self, font, size1, size2, text): font = pg.font.SysFont("arial", font) message = text rend = font.render(message, True, pg.Color("white")) return (rend, rend.get_rect(topleft=(size1, size2))) def event_loop(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def change_color(self, id, color): #zero=0 #try: #if not os.path.exists("data/save.dat"): #f=open("data/login.dat",'w') #f.write(str(zero)) #f.close() #game_intro1() f = open("data/login.dat", 'r+') #topScore = f.readline() #f = open("file.txt", "r") #searchlines = f.readlines() #f.close() for columns in (raw.strip().split() for raw in f): if (columns[0] == str(color)): global abcd abcd = columns[1] print(columns[0]) print(columns[1]) columns[1] = int(columns[1]) #f3=open("data/player.dat",'w') #f3.write(columns[1]) print(columns[1]) intro = True while intro: for event in pygame.event.get(): #print(event) if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(black) largeText = pygame.font.SysFont("comicsansms", 115) TextSurf, TextRect = text_objects("Road Runner", largeText) #TextSurf, TextRect = text_objects("Dodge enemy cars and collect coins to complete a level", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) #f=open("data/player.dat",'r+') #for columns in ( raw.strip().split() for raw in f ): # columns[0]=int(columns[0]) if (columns[1] < 100 and columns[1] >= 0): button("Level1", 150, 450, 100, 50, green, bright_green, game_loop) button("Quit", 550, 450, 100, 50, green, bright_green, quitgame) elif (columns[1] < 200 and columns[1] > 100): button("Level1", 150, 450, 100, 50, green, bright_green, game_loop) button("Quit", 550, 450, 100, 50, green, bright_green, quitgame) button("level2", 350, 450, 100, 50, green, bright_green, game_loop1) #button("Level3",550,450,100,50,green,bright_green,cannot) elif (columns[1] > 200): button("Level1", 150, 450, 100, 50, green, bright_green, game_loop) button("Quit", 350, 550, 100, 50, green, bright_green, quitgame) button("level2", 350, 450, 100, 50, green, bright_green, game_loop1) button("Level3", 550, 450, 100, 50, green, bright_green, game_loop2) pygame.display.update() clock.tick(15) #else: # drawText('Incorrect Username', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3)) # pygame.display.update() # waitForPlayerToPressKey5() #except ValueError: # print("Please input a valid color name.") def main_loop(self): while not self.done: self.event_loop() self.input.update() self.screen.fill(self.color) self.input.draw(self.screen) self.screen.blit(*self.prompt) self.screen.blit(*self.prompt1) self.screen.blit(*self.prompt2) pg.display.update() self.clock.tick(self.fps)
def NewNet(screen, clock): font_48 = pygame.font.SysFont('Arial', 48) font_40 = pygame.font.SysFont('Arial', 40) font_28 = pygame.font.SysFont('Arial', 28) pieces_x = 350 pieces_y = 450 name_box = TextBox((320, 400, 380, 50), clear_on_enter=False, inactive_on_enter=True, active=True, active_color=pygame.Color("red")) name_text = font_48.render("Enter your Name (max 12 characters):", True, (0, 0, 0)) n_width, n_height = font_48.size("Enter your Name (max 12 characters):") name_button = Button(400, 460, 200, 80, "Confirm", font_48) ready_up_but = Button(400, 460, 200, 80, "Ready Up", font_48) start_game_but = Button(400, 460, 200, 80, "Start Game", font_48) ready_up_but.hideBut() start_game_but.hideBut() piece_rects = [None] * 6 piece_imgs_lobby = [None] * 6 for n in range(6): piece_rects[n] = pygame.Rect(pieces_x + 110 * (n % 3), pieces_y + 110 * int(n / 3), 100, 100) piece_imgs_lobby[n] = pygame.transform.smoothscale( pygame.image.load("img/Pieces/" + str(n + 1) + ".png"), [30, 30]) choose_text = font_40.render("Choose Your Piece:", True, (0, 0, 0)) pieces_large = np.array([None] * 6) #Load 6 available player pieces for p_counter in range(6): pieces_large[p_counter] = pygame.transform.smoothscale( pygame.image.load("img/Pieces/" + str(p_counter + 1) + ".png"), [100, 100]) #Load image into pygame and resize # Read in host (server) IP and port from file. # This means that the server IP and port do not have to be hard-coded. f = open("data/Host_Data.txt", "r") host_dat = f.readline().split(",") # Some setup code that was previously run while the screen was active. # Having it here instead streamlines things a bit. ip_text = font_48.render( "Your IP: " + socket.gethostbyname(socket.gethostname()), True, (0, 0, 0)) lobby = Pyro4.Proxy("PYRO:dfo.game@" + host_dat[0] + ":" + host_dat[1]) # Okay, this is actually a Game() class object, but the Lobby() part is the only part actually used here, # and I wrote everything here with lobby separate first, so why bother changing it? ready_up_texts = [ font_48.render("Waiting for players to ready up.", True, (0, 0, 0)), font_48.render("Waiting for players to ready up..", True, (0, 0, 0)), font_48.render("Waiting for players to ready up...", True, (0, 0, 0)) ] waiting_texts = [ font_48.render("Waiting to start.", True, (0, 0, 0)), font_48.render("Waiting to start..", True, (0, 0, 0)), font_48.render("Waiting to start...", True, (0, 0, 0)) ] newnet_running = True piece_choice = -1 piece_chosen = False name_chosen = False ready_up = False start_game = False while newnet_running: for event in pygame.event.get(): if name_box.visible: name_box.get_event(event) name_button.handle_input_event(event) ready_up_but.handle_input_event(event) start_game_but.handle_input_event(event) if event.type == pygame.QUIT: newnet_running = False gotoScreen = -1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: #Escape key exits the game newnet_running = False #This screen will no longer run gotoScreen = -1 #Game will completely exit if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: #Left mouse button if not piece_chosen and name_chosen: for n in range(6): if piece_rects[n].collidepoint(event.pos): piece_choice = n screen.fill((255, 255, 255)) if not name_box.visible: #Player has entered name; show lobby and following game setup screen.blit(ip_text, [10, 10]) screen.blit(host_text, [10, 60]) renderLobby(screen, lobby, 10, 110, font_40, font_28, piece_imgs_lobby) if not piece_chosen: renderPieces(screen, pieces_large, lobby, pieces_x, pieces_y, choose_text) ready_up_but.render(screen) start_game_but.render(screen) if ready_up and not start_game and not lobby.allReadyUp(): screen.blit( ready_up_texts[int(pygame.time.get_ticks() / 500) % 3], [235, 460]) if start_game and not lobby.allReadyToStart(): screen.blit( waiting_texts[int(pygame.time.get_ticks() / 500) % 3], [375, 460]) if name_box.visible: #Player is entering name name_box.update() name_box.draw(screen) name_button.render(screen) screen.blit(name_text, [(1024 - n_width) / 2, 335]) if name_button.clicked(): #Determine if the name entered is valid. Will try and do something to prevent duplicate naming... if len(name_box.getContents()) <= 12 and len( name_box.getContents()) != 0: #Name is valid #Display your IP and name, and connect to server using Pyro4 module host_text = font_48.render( "Your Name: " + name_box.getContents(), True, (0, 0, 0)) lobby.connect(socket.gethostbyname(socket.gethostname()), name_box.getContents()) name_box.hide() name_chosen = True name_button.hideBut() if piece_choice != -1 and name_chosen: if not (piece_choice + 1 in lobby.getUsedPieces()): lobby.setPiece(socket.gethostbyname(socket.gethostname()), piece_choice + 1) piece_chosen = True ready_up_but.showBut() piece_choice = -1 if ready_up_but.clicked(): lobby.readyUp(socket.gethostbyname(socket.gethostname())) ready_up = True ready_up_but.hideBut() if start_game_but.clicked(): lobby.readyToStart(socket.gethostbyname(socket.gethostname())) start_game = True start_game_but.hideBut() if not start_game and name_chosen and not start_game_but.visible and ready_up: if lobby.allReadyUp() and dim( lobby.getLobby() )[0] >= 2: #May not proceed until at least two players have joined start_game_but.showBut() if start_game and name_chosen and ready_up: if lobby.allReadyToStart() and dim(lobby.getLobby( ))[0] >= 2: #At least two players required for a game (duh!) #Creation of localGame object first players = createLocalPlayers( pieces_large, lobby.getLobby()) #Create array of LocalPlayer objects prop_arr = createLocalProperties( "data/Property Values.txt" ) #Create array of Property objects Pot_Luck_Deck = createLocalDeck("Pot Luck", "img/PL/Pot Luck ", "data/Card_Texts.txt", "data/PL Master.txt", 16) #Create Card_Deck object Council_Chest_Deck = createLocalDeck( "Council Chest", "img/CC/Council Chest ", "data/Card_Texts.txt", "data/CC Master.txt", 16) #Create Card_Deck object game_board = createLocalBoard("data/Board_Data.txt", prop_arr, Pot_Luck_Deck, Council_Chest_Deck, "img/Board.png", 600) #Create Board object this_player_num = findPlayerNum(lobby) localGame = createLocalGame( players, game_board, "img/Dice/", this_player_num ) #Finally create the single, cohesive Game object that is the sole purpose of this screen/part of the game if lobby.getGameSetup() == False: fh = open("data/Property Values.txt", "r") prop_data = fh.read() lobby.setupGame(prop_data) newnet_running = False gotoScreen = 6 clock.tick(10) #10 fps pygame.display.flip() #Refresh screen return lobby, localGame, gotoScreen
def main(): lefff = io.load_lefff() citiesList = io.load_city_names() keywords = io.load_keywords("Keywords.txt") bank = io.load_responses() #Dictionnaires utilisés request = ut.resetdict() #Dictionnaire principal tmprequest = ut.resetdict() #Dictionnaire de la dernière saisie utilisateur prerequest = ut.resetdict() #Trace #Historique log = [] #Variables de choix ask = 0 #1 si l'utilisateur doit répondre à une question du bot, 0 sinon phase = 0 #Phase dans laquelle se situe le bot #Tablaux temporaires TravelList = [] #Liste des vols trouvés #Initialisation pygame.init() clock = pygame.time.Clock() FPS = 30 #Window fenetre = pygame.display.set_mode((1280, 720)) pygame.font.init() speech = pygame.font.SysFont('Trebuchet MS', 25) currtime = pygame.font.SysFont('Trebuchet MS', 50) history = pygame.font.SysFont('Trebuchet MS', 20) #Variable qui continue la boucle si = 1, stoppe si = 0 loop = 1 index = 0 alpha = 80 coeff = 1 images = [] lydia = pygame.image.load("GraphicalContent/interface.png").convert_alpha() loadingscreen = pygame.image.load("GraphicalContent/blackscreen.png").convert() loadingmessage = pygame.image.load("GraphicalContent/loadingmessage.png").convert_alpha() s = pygame.Surface((1280, 720)) for imgno in os.listdir("GraphicalContent/backgroundAnim/"): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() image = pygame.image.load("GraphicalContent/backgroundAnim/" + imgno).convert() images.append(image) s.set_alpha(alpha) s.fill((0,0,0)) fenetre.blit(loadingscreen, (0,0)) fenetre.blit(loadingmessage, (0,0)) fenetre.blit(s, (0,0)) pygame.display.flip() alpha += coeff if(alpha <= 80): print(imgno) coeff = 5 elif(alpha >= 240): coeff = -5 print("Successfully loaded!") textsurface = speech.render('Bonjour, je suis LYD.IA', False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) textsurface2 = speech.render("", False, (246, 246, 246)) text_rect2 = textsurface2.get_rect(center=(640, 250)) def submit_answer(id, txt): text = "".join(inputbox.buffer) if(text.strip() != ""): hist.append(text) inputbox = TextBox((440,540,400,50),command=submit_answer, clear_on_enter=True,inactive_on_enter=False) last_entry = " " while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: loop = 0 inputbox.get_event(event) inputbox.update() fenetre.blit(images[index], (0,0)) fenetre.blit(lydia, (0,0)) text_rect = textsurface.get_rect(center=(640, 210)) fenetre.blit(textsurface, text_rect) text_rect2 = textsurface2.get_rect(center=(640, 250)) fenetre.blit(textsurface2, text_rect2) #datesurface = currtime.render(datetime.now().strftime('%H:%M:%S'), False, (246, 246, 246)) fenetre.blit(datesurface, (20, 50)) index = (index+1)%1350 if(last_entry != hist[len(hist)-1]): #Si il y a eu une saisie last_entry = hist[len(hist)-1] response = last_entry #Cas de sortie de programme if(response == "q"): break #Cas d'une réponse non vide if(response.strip() != ''): #Tokenisation de la phrase (commune pour toutes les phases) token_user = lex.tokenise(response, 1) #Phase de récolte d'informations if(phase == 0): if(TravelList != []): #Réinitialisaton des vols si régression de phase TravelList = [] normalised_tokens = lex.normalise(token_user, lefff, citiesList, keywords) tmprequest = lex.semantic_analysis(normalised_tokens, tmprequest) #Création de la nouvelle requête if(ut.comparedict(request, tmprequest) == False and ask == 0): #Si aucun changement n'a été apporté à la demande précédente textsurface = speech.render(Lydia(generate_response("NOP", bank), log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) fenetre.blit(textsurface, text_rect) textsurface2 = speech.render(Lydia(generate_response("ASK", bank), log), False, (246, 246, 246)) text_rect2 = textsurface2.get_rect(center=(640, 250)) fenetre.blit(textsurface2, text_rect2) else: #Si l'utilisateur doit confirmer son choix if(ask == 1): if(("K____NEG____",0.3) not in normalised_tokens and ask==1): #Si absence de réponse négative request = prerequest.copy() if(("K____AFF____", 0.2222222222222222) in normalised_tokens): #Si positif textsurface = speech.render(Lydia(generate_response("FIL", bank), log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) fenetre.blit(textsurface, text_rect) textsurface2 = speech.render(Lydia(get_missing(request, bank), log), False, (246, 246, 246)) text_rect2 = textsurface2.get_rect(center=(640, 250)) fenetre.blit(textsurface2, text_rect2) else: textsurface = speech.render(Lydia(generate_response("NFI", bank), log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) fenetre.blit(textsurface, text_rect) textsurface2 = speech.render(Lydia(get_missing(request, bank), log), False, (246, 246, 246)) text_rect2 = textsurface2.get_rect(center=(640, 250)) fenetre.blit(textsurface2, text_rect2) tmprequest = request.copy() ask = 0 #Sinon, c'est que son choix doit être élargi: else: if(ask == 1): textsurface = speech.render(Lydia(get_missing(request, bank), log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) textsurface2 = speech.render("", False, (246, 246, 246)) fenetre.blit(textsurface, text_rect) ask = 0 else: textsurface = speech.render(Lydia(request_toString(request, tmprequest), log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) fenetre.blit(textsurface, text_rect) textsurface2 = speech.render("", False, (246, 246, 246)) prerequest = tmprequest.copy() ask = 1 if(ut.isFull(request)): phase = 1 if(phase == 1): #Seconde phase du chatbot textsurface = speech.render(Lydia("Je suis navrée, mon développeur n'a pas eu lle temps de me terminer...", log), False, (246, 246, 246)) text_rect = textsurface.get_rect(center=(640, 210)) textsurface2 = speech.render("", False, (246, 246, 246)) fenetre.blit(textsurface, text_rect) for i in range (0,3): tmp = history.render(hist[len(hist)-i-1], False, (246-i*30, 246-i*30, 246)) tmp_rect = tmp.get_rect(center=(640, 520-i*30)) fenetre.blit(tmp, tmp_rect) inputbox.draw(fenetre) pygame.display.flip() clock.tick(FPS) pygame.quit()
class Terminar: def __init__(self): self.puntuacion = 0 self.color_fondo = (255, 255, 255) self.construir() self.desactivarTextBox() self.final = False def construir(self): self.titulo = Titulo("KACH!", 320, 50, 70, 1, (126, 81, 9)) self.titulo_terminado = Titulo("Juego Terminado!", 320, 100, 40, 3, (14, 98, 81)) self.titulo_puntaje = Titulo("Su puntaje es:", 320, 150, 30, 4, (36, 32, 163)) self.lblPuntuacion = Titulo("0", 300, 260, 180, 2, (0, 0, 0)) self.lblinstrucciones = Titulo("Presione <Enter> para continuar", 320, 440, 30, 4, (126, 81, 9)) self.lblindicacion = Titulo("Ingrese Alias:", 320, 360, 25, 3, (14, 98, 81)) self.input = TextBox((220, 380, 200, 30), command=self.enviar_reporte, clear_on_enter=True, inactive_on_enter=False) def activarTextBox(self): self.input.active = True def desactivarTextBox(self): self.input.active = False def pintar(self, screen): screen.fill(self.color_fondo) self.titulo.pintar(screen) self.titulo_terminado.pintar(screen) self.titulo_puntaje.pintar(screen) self.lblPuntuacion.pintar(screen) self.lblindicacion.pintar(screen) self.lblinstrucciones.pintar(screen) self.input.update() self.input.draw(screen) def eventos(self, evento): self.input.get_event(evento) def enviar_reporte(self, id, final): if (final != ""): self.conexion = Conexion() fecha = time.strftime("%y-%m-%d") self.conexion.enviar_registro(self.query_envio(), (final, fecha, self.puntuacion)) self.final = True def modificar_puntuacion(self, puntuacion): self.puntuacion = puntuacion self.lblPuntuacion.modificarTexto(str(puntuacion)) def getFinal(self): return self.final def reiniciar(self): self.final = False def query_envio(self): return ( "INSERT INTO Jugador(nombre,fecha,puntuacion) VALUES (%s, %s, %s);" )
class Control(object): def __init__(self): self.screen = pygame.display.set_mode((1300,600)) #self.screen_rect = self.screen.get_rect() self.bnum = 0 self.clock = pygame.time.Clock() self.done = False self.fps = 60.0 self.color = GREEN message, message2, message3, message4, message5, message6, message7, message8 = ("Host", "SensorNode 1", "SensorNode 2","SensorNode 3", "Communication", "Alarm", "Battery", "Change password") #button style self.button = Button((0,0,150,100),RED, self.button_click, text=message, **BUTTON1_STYLE) #button move #self.button.rect.center = (self.screen_rect.centerx,100) self.button2 = Button((0,100,150,100),RED, self.button_click2, text=message2, **BUTTON1_STYLE) self.button3 = Button((0,200,150,100),RED, self.button_click3, text=message3, **BUTTON1_STYLE) self.button4 = Button((0,300,150,100),RED, self.button_click4, text=message4, **BUTTON1_STYLE) self.button5 = Button((0,400,150,100),RED, self.button_click5, text=message5, **BUTTON1_STYLE) self.button6 = Button((0,500,150,100),RED, self.button_click6, text=message6, **BUTTON1_STYLE) self.button7 = Button((0,600,100,100),RED, self.button_click, text=message7, **BUTTON1_STYLE) self.button8= Button((0,700,100,100),RED, self.button_click, text=message8, **BUTTON1_STYLE) #input self.b2_input = TextBox((450,270,150,25),command=self.change_color2, clear_on_enter=True,inactive_on_enter=False) pygame.key.set_repeat(*KEY_REPEAT_SETTING) #mesk self.pnum, self.pnum2, self.pnum3 = 0,0,0 self.photo = pygame.image.load('p1.1.png').convert_alpha() self.photo_pos = (550, 55) self.mask = pygame.mask.from_surface(self.photo) self.photo2 = pygame.image.load('p1.3.png').convert_alpha() self.photo2_pos = (400, 200) self.mask2 = pygame.mask.from_surface(self.photo2) self.photo3 = pygame.image.load('p2.1.png').convert_alpha() self.photo3_pos = (410, 345) self.mask3 = pygame.mask.from_surface(self.photo3) #left button click def button_click(self): self.bnum = 1 print("click") self.color = BLACK#WHITE def button_click2(self): print("click2") #self.color = ORANGE self.bnum = 2 def button_click3(self): self.bnum = 3 print("click3") self.color = GREEN def button_click4(self): self.bnum = 4 print("click3") self.color = GREEN def button_click5(self): self.bnum = 5 self.color = WHITE print("click5") def button_click6(self): self.bnum = 6 self.color = ORANGE print("click6") #text input function def change_color(self,id,color): try: self.color = pygame.Color(str(color)) except ValueError: print("Please input a valid color name.") def change_color2(self,id,color): try: self.color = pygame.Color(str(color)) except ValueError: print("Please input a valid color name.") #event def event_loop(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.done = True self.button.check_event(event) self.button2.check_event(event) self.button3.check_event(event) self.button4.check_event(event) self.button5.check_event(event) self.button6.check_event(event) #self.input.get_event(event) self.b2_input.get_event(event) #mesk x, y=0,0 #進入第一頁才偵測 if(self.bnum == 1): if event.type == pygame.MOUSEBUTTONDOWN:#click to change pages #1 try: if self.mask.get_at((event.pos[0]-self.photo_pos[0], event.pos[1]-self.photo_pos[1])): self.button_click3() except IndexError: pass #2 try: if self.mask2.get_at((event.pos[0]-self.photo2_pos[0], event.pos[1]-self.photo2_pos[1])): self.button_click2() except IndexError: pass #3 try: if self.mask3.get_at((event.pos[0]-self.photo3_pos[0], event.pos[1]-self.photo3_pos[1])): self.button_click6() except IndexError: pass if event.type == pygame.MOUSEMOTION:#移動到上方 hold ###1 try: if self.mask.get_at((event.pos[0]-self.photo_pos[0], event.pos[1]-self.photo_pos[1])): #self.photo2 = pygame.image.load('p1.3.png').convert_alpha() self.pnum = 1 print(self.pnum) else: self.pnum = 2 print(self.pnum, "out") except IndexError: #photo2 = pygame.image.load('/ta-ju/png/4.png').convert_alpha() self.pnum = 2 pass ###2 try: if self.mask2.get_at((event.pos[0]-self.photo2_pos[0], event.pos[1]-self.photo2_pos[1])): self.pnum2 = 1 print(self.pnum) else: self.pnum2 = 2 print(self.pnum, "out") except IndexError: #photo2 = pygame.image.load('/ta-ju/png/4.png').convert_alpha() self.pnum2 = 2 print(self.pnum) pass ###3 try: if self.mask3.get_at((event.pos[0]-self.photo3_pos[0], event.pos[1]-self.photo3_pos[1])): self.pnum3 = 1 print(self.pnum) else: self.pnum3 = 2 except IndexError: #photo2 = pygame.image.load('/ta-ju/png/4.png').convert_alpha() self.pnum3 = 2 print(self.pnum) pass #main interface def main_loop(self): while not self.done: self.event_loop() self.screen.fill(self.color) self.button.update(self.screen) self.button2.update(self.screen) self.button3.update(self.screen) self.button4.update(self.screen) self.button5.update(self.screen) self.button6.update(self.screen) #self.input.update() self.b2_input.update() #self.input.draw(self.screen) if(self.bnum == 1): #self.input.update() #self.input.draw(self.screen) self.screen.blit(self.photo, self.photo_pos) self.screen.blit(self.photo2, self.photo2_pos) self.screen.blit(self.photo3, self.photo3_pos) if(self.pnum == 1): self.photo = pygame.image.load('p1.2.png').convert_alpha() #print(self.pnum, "photo") #self.photo2 = pygame.image.load('p1.3.png').convert_alpha() #self.photo3 = pygame.image.load('p2.1.png').convert_alpha() if(self.pnum == 2): self.photo = pygame.image.load('p1.1.png').convert_alpha() #print(self.pnum, "photo") if(self.pnum2 == 1): self.photo2 = pygame.image.load('p1.4.png').convert_alpha() #print(self.pnum, "photo") if(self.pnum2 == 2): self.photo2 = pygame.image.load('p1.3.png').convert_alpha() if(self.pnum3 == 1): self.photo3 = pygame.image.load('p2.2.png').convert_alpha() #print(self.pnum, "photo") if(self.pnum3 == 2): self.photo3 = pygame.image.load('p2.1.png').convert_alpha() #self.photo3 = pygame.image.load('p2.4.png').convert_alpha() elif(self.bnum == 2): self.screen.blit(pygame.image.load("/ta-ju/png/2.png").convert(), (150,0)) h_text = font.render("Model Name", True, (0,0,0)) h_text2 = font.render("Serial Number", True, (0,0,0)) self.b2_input.draw(self.screen) h_text3 = font.render("Firmware( show Version / upgrade)", True, (0,0,0)) h_text4 = font.render("Upload Interval (System Check): days & hours ", True, (0,0,0)) h_text5 = font.render("Sleep Period ", True, (0,0,0)) self.screen.blit(h_text, (200,240)) self.screen.blit(h_text2, (200,270)) self.screen.blit(h_text3, (200,300)) self.screen.blit(h_text4, (200,330)) self.screen.blit(h_text5, (200,360)) elif(self.bnum == 3): b3_text = font.render("Type", True, (0,0,0)) b3_text2 = font.render("Upload Thresholds Ratio: Concentration", True, (0,0,0)) self.screen.blit(b3_text, (200,240)) self.screen.blit(b3_text2, (200,270)) elif(self.bnum == 4): b3_text = font.render("Type B", True, (0,0,0)) b3_text2 = font.render("Upload Thresholds Ratio: Concentration", True, (0,0,0)) self.screen.blit(b3_text, (200,240)) self.screen.blit(b3_text2, (200,270)) elif(self.bnum == 5): b5_text = font.render("Type: LoRa", True, (0,0,0)) b5_text2 = font.render("FSB", True, (0,0,0)) b5_text3 = font.render("Channel", True, (0,0,0)) b5_text4 = font.render("App name", True, (0,0,0)) b5_text5 = font.render("App Key", True, (0,0,0)) self.screen.blit(b5_text, (200,240)) self.screen.blit(b5_text2, (200,270)) self.screen.blit(b5_text3, (200,300)) self.screen.blit(b5_text4, (200,330)) self.screen.blit(b5_text5, (200,360)) elif(self.bnum == 6): b6_text = font.render("Type: ", True, (0,0,0)) b6_text2 = font.render("NH3", True, (0,0,0)) b6_text3 = font.render("CO2", True, (0,0,0)) b6_text4 = font.render("Humidity", True, (0,0,0)) self.screen.blit(b6_text, (200,240)) self.screen.blit(b6_text2, (200,270)) self.screen.blit(b6_text3, (200,300)) self.screen.blit(b6_text4, (200,330)) #image = pygame.image.load("/ta-ju/png/1.png").convert() #self.screen.blit(image, (150,0)) #self.button7.update(self.screen) #self.bg.update(self.screen) #gameDisplay.blit(TextSurf, TextRect) pygame.display.update() self.clock.tick(self.fps)
class MainProgram(object): def __init__(self): """The initialisation function of key components of the main program""" pg.init() pg.display.set_caption("D5's Bargain Inspector") bg = pg.image.load('mainScreen.png') gameDisplay.blit(bg, (0, 0)) self.red = [] self.blue = [] self.green = [] self.pink = [] self.colourA = [] self.colour = "" self.num_items = 0 self.finishedList = [] self.time = 0 self.frame_count = 0 self.frame_rate = 60 self.start_time = 180 self.screen = menuDisplay self.clock = pg.time.Clock() self.robot_loc = [] self.fps = 60.0 self.done = False self.input = TextBox( (900, 200, 200, 40), command=self. get_input, #setting the size and position of the text box clear_on_enter=True, inactive_on_enter=False) self.user_input = "" self.color = white self.prompt = self.make_prompt( 'Enter Red:BMW, Blue:Vauxhall, Green:Land Rover, Pink:Lexus') pg.key.set_repeat( *KEY_REPEAT_SETTING ) #textbox to appear in the same position after action def make_prompt(self, Message): """ Function to create the labels, called everytime a new input is entered """ pg.draw.rect( menuDisplay, white, (820, 165, 400, 30) ) #1 is left right position, 2 is up down, 3 is width, 4 is height font = pg.font.SysFont("Times", 14) message = Message rend = font.render(message, True, pg.Color("black")) return (rend, rend.get_rect(topleft=(820, 165)) ) #position of the text in the screen def event_loop(self): """ A continuous FOR loop which allows an exit for our main program""" for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def random_types(self): """Randomly generates colours into the screen and randomly gives them a price and a name eg. red-bmw,price """ names = ["BMW", "Vauxhall", "Land Rover", "Lexus"] for i in range(50): item = random.randint(1, 3) radx = random.randint(0, 790) rady = random.randint(0, 590) radp = random.randint(1, 20) radnum = random.randint(1, 4) - 1 radn = names[radnum] coords = [radx, rady, radp, radn] if item == 1: pg.draw.rect(menuDisplay, red, (radx, rady, 10, 10)) self.red.append(coords) elif item == 2: pg.draw.rect(menuDisplay, blue, (radx, rady, 10, 10)) self.blue.append(coords) elif item == 3: pg.draw.rect(menuDisplay, green, (radx, rady, 10, 10)) self.green.append(coords) elif item == 4: pg.draw.rect(menuDisplay, pink, (radx, rady, 10, 10)) self.pink.append(coords) i = i + 1 def get_input(self, id, input): """ allows the user to search for cars by enterin a specific colour """ try: input = input.lower() self.user_input = input self.colour = input if self.user_input == "red" or self.user_input == "blue" or self.user_input == "green" or self.user_input == "pink": self.prompt = self.make_prompt( 'Where do you want to start : e.g. NW') self.input = TextBox( (900, 200, 200, 40), command=self.robot_start, # textbox position clear_on_enter=True, inactive_on_enter=False) if input == "red": for coord in self.red: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, red, (x, y, 15, 15)) self.colourA = self.red elif input == "blue": for coord in self.blue: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, blue, (x, y, 15, 15)) self.colourA = self.blue elif input == "green": for coord in self.green: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, green, (x, y, 15, 15)) self.colourA = self.green elif input == "pink": for coord in self.pink: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, pink, (x, y, 15, 15)) self.colourA = self.pink else: self.prompt = self.make_prompt( 'Please enter the colour type given') self.screen = menuDisplay except ValueError: print("ERROR") def robot_start(self, id, input): """ Allows the user to choose the starting position of the robot""" input = input.upper() self.robot_loc = input if input == "N": pg.draw.rect(menuDisplay, red, (400, 0, 20, 30)) self.robot_loc = [400, 0] elif input == "E": pg.draw.rect(menuDisplay, blue, (750, 300, 20, 30)) self.robot_loc = [750, 300] elif input == "S": pg.draw.rect(menuDisplay, pink, (400, 550, 20, 30)) self.robot_loc = [400, 550] elif input == "W": pg.draw.rect(menuDisplay, green, (10, 300, 20, 30)) self.robot_loc = [10, 300] elif input == "NW": pg.draw.rect(menuDisplay, bright_green, (10, 10, 20, 30)) self.robot_loc = [10, 10] elif input == "NE": pg.draw.rect(menuDisplay, bright_red, (750, 10, 20, 30)) self.robot_loc = [750, 10] elif input == "SW": pg.draw.rect(menuDisplay, red, (10, 550, 20, 30)) self.robot_loc = [10, 550] elif input == "SE": pg.draw.rect(menuDisplay, pink, (750, 550, 20, 30)) self.robot_loc = [750, 550] else: self.prompt = self.make_prompt( 'Please enter a valid co-cordinate for the robot to search') if input == "N" or input == "E" or input == "S" or input == "W" or input == "NW" or input == "NE" or input == "SW" or input == "SE": self.prompt = self.make_prompt( 'Please enter the number of car types you will like to find?') self.input = TextBox( (900, 200, 200, 40), command=self.number_of_items, #textbox position clear_on_enter=True, inactive_on_enter=False) def number_of_items(self, id, input): """ This will allow the user to enter the number of chosen car models they want to find""" if input.isdigit() and (int(input) <= len(self.colourA)): self.num_items = int(input) self.prompt = self.make_prompt( 'Enter the minutes you want the robot to search for?') self.input = TextBox( (900, 200, 200, 40), command=self.input_time, #textbox pisition clear_on_enter=True, inactive_on_enter=False) else: self.prompt = self.make_prompt( 'Please enter how many chosen car models to find?') def input_time(self, id, input): """ Allows the user to enter the time for the robot to search for car types""" if input.isdigit() and int(input) <= 15: self.time = input self.start_time = int(self.time) * 60 else: self.prompt = self.make_prompt( 'Please enter a valid time, e.g 1 for 1 minute') def collide(self, c1, p1, p2, p3, xORy): """ Tests to see if the next pixals are not white""" locations = [p1, p2, p3] self.Collide = False i = 0 if xORy == "X": while i != 3: colour = menuDisplay.get_at( (c1, locations[i] )) # gets the colour of the pixal at the coordinates if (c1 >= self.nextX and c1 <= (self.nextX + 15)) and (p1 >= self.nextY and p1 <= (self.nextY + 15)): i = i + 1 continue elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255): self.Collide = True break else: i = i + 1 continue elif xORy == "Y": while i != 3: colour = menuDisplay.get_at((locations[i], c1)) if (c1 >= self.nextY and c1 <= (self.nextY + 15)) and (p1 >= self.nextX and p1 <= (self.nextX + 1)): i = i + 1 continue elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255): self.Collide = True break else: i = i + 1 continue def bubbleSort(self, colourL): """ Used to sort the list in order of price, cheapest first""" for passnum in range(len(colourL) - 1, 0, -1): for i in range(passnum): if colourL[i][2] > colourL[i + 1][2]: temp = colourL[i] colourL[i] = colourL[i + 1] colourL[i + 1] = temp def binarySearch(self, alist, item): """Used to search a list for the search item and returns all infomation about that item""" first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if alist[midpoint][0] == item: return (alist[midpoint]) else: if item < alist[midpoint][0]: last = midpoint - 1 else: first = midpoint + 1 return found def quick_sort(self, items): """ Used to sort a list in order by x coords for binary search""" if len(items) > 1: pivot_index = len(items) // 2 smaller_items = [] larger_items = [] for i, val in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: larger_items.append(val) self.quick_sort(smaller_items) self.quick_sort(larger_items) items[:] = smaller_items + [items[pivot_index]] + larger_items def robot_move(self): """Makes the robot move visually and makes a countdown timer that countdowns from the users input""" i = 0 if self.colour == "red": self.bubbleSort(self.red) locations = self.red elif self.colour == "blue": self.bubbleSort(self.blue) locations = self.blue elif self.colour == "green": self.bubbleSort(self.green) locations = self.green elif self.colour == "pink": self.bubbleSort(self.pink) locations = self.pink #pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30)) print(locations) while i != self.num_items: #Makes the robot move visually self.event_loop() nextX = locations[i][0] nextY = locations[i][1] if self.robot_loc[0] == nextX and self.robot_loc[1] == nextY: pg.draw.rect(menuDisplay, black, (nextX, nextY, 15, 15)) self.finishedList.append(locations[i][0]) i = i + 1 elif self.robot_loc[0] < nextX: pg.draw.rect(menuDisplay, white, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.robot_loc[0] = self.robot_loc[0] + 1 pg.draw.rect(menuDisplay, pink, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.input.draw(self.screen) elif self.robot_loc[1] < nextY: pg.draw.rect(menuDisplay, white, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.robot_loc[1] = self.robot_loc[1] + 1 pg.draw.rect(menuDisplay, pink, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.input.draw(self.screen) elif self.robot_loc[0] > nextX: pg.draw.rect(menuDisplay, white, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.robot_loc[0] = self.robot_loc[0] - 1 pg.draw.rect(menuDisplay, pink, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.input.draw(self.screen) elif self.robot_loc[1] > nextY: pg.draw.rect(menuDisplay, white, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.robot_loc[1] = self.robot_loc[1] - 1 pg.draw.rect(menuDisplay, pink, (self.robot_loc[0], self.robot_loc[1], 20, 30)) self.input.draw(self.screen) self.event_loop() # Starts the timer countdown pg.draw.rect(menuDisplay, green, (810, 540, 400, 60)) total_seconds = self.frame_count // self.frame_rate total_seconds = self.start_time - (self.frame_count // self.frame_rate) if total_seconds < 0: total_seconds = 0 minutes = total_seconds // 60 seconds = total_seconds % 60 output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) text = font.render(output_string, True, black) menuDisplay.blit(text, [810, 540]) if output_string == "Time left: 00:00": self.done = True self.frame_count += 1 clock.tick(frame_rate) pg.display.flip() self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() if self.colour == "red": self.quick_sort(self.red) elif self.colour == "blue": self.quick_sort(self.blue) elif self.colour == "green": self.quick_sort(self.green) elif self.colour == "pink": self.quick_sort(self.pink) self.clock.tick(self.fps) if self.time != 0: self.done = True def output_lists(self, i, Space): """Displays the list of cheapest items picked up""" if self.colour == "red": output = self.binarySearch(self.red, self.finishedList[i]) elif self.colour == "blue": output = self.binarySearch(self.blue, self.finishedList[i]) elif self.colour == "green": output = self.binarySearch(self.green, self.finishedList[i]) elif self.colour == "pink": output = self.binarySearch(self.pink, self.finishedList[i]) font = pg.font.SysFont("Times", 20) message = str(output[3]) + " | " + str(output[2]) rend = font.render(message, True, pg.Color("black")) return (rend, rend.get_rect(topleft=(820, 35 + Space))) def main_loop(self): """ Makes the program loops and call certain function only if an event has been met""" i = 0 """adds sound to the code""" pg.mixer.music.load('programsound.wav') pg.mixer.music.play(-1) space = 0 self.random_types() while not self.done: self.event_loop() self.input.update() self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() self.clock.tick(self.fps) if self.time != 0: self.done = True self.done = False if self.time != 0: self.robot_move() pg.draw.rect(menuDisplay, green, (810, 0, 450, 540)) pg.display.update() while i != self.num_items: self.prompt = self.output_lists(i, space) self.screen.blit(*self.prompt) space = space + 20 pg.display.update() i = i + 1 self.done = False #self.main_program() while not self.done: self.event_loop()
class DataCollection: def __init__(self, user, mode, iterations, museID = None): self.user = user self.museID = museID pygame.init() self.width = 600 self.height = 600 pygame.display.set_caption(user + ' Data Collection Session') self.screen = pygame.display.set_mode((self.width, self.height)) self.totalIterations = iterations self.passwords = self.generate_passwords(mode, iterations) self.mode = mode self.currentPassIndex = 0 self.currentCharIndex = 0 self.donePass = False self.inputSize = (300, 60) self.inputPosition = (self.width/2 - self.inputSize[0]/2, self.height/2 - self.inputSize[1]/2) font = pygame.font.Font(None, 50) inputRect = pygame.Rect(self.inputPosition[0], self.inputPosition[1], self.inputSize[0], self.inputSize[1]) self.input = TextBox(inputRect, clear_on_enter=True, inactive_on_enter=False, font=font) self.gameRunning = False self.state = DataCollectionState.MUSE_DISCONNECTED # 0 = Muse Disconnected, 1 = Session Running, 2 = Finished self.setup_marker_streaming() self.markers = [[]] # Each item is array of 2 items - timestamp + the key which was pressed. self.eegData = [[]] # Each item is array of timestamp + data for each channel. self.get_eeg_stream(0.5) self.startTime = time() # Timestamp of experiment start. self.finishTime = 0 # Timestamp of experiment finish. self.lastEEGSampleTime = self.startTime def setup_marker_streaming(self): streamName = self.user + ' Training Session Markers' self.markerInfo = StreamInfo(streamName, 'Keystroke Markers', 1, 0, 'string', str(uuid.uuid1())) self.markerOutlet = StreamOutlet(self.markerInfo) def get_eeg_stream(self, timeout): eeg_inlet_streams : StreamInlet = resolve_byprop('type', 'EEG', timeout=timeout) for stream in eeg_inlet_streams: if self.museID == None or not stream.name().find(self.museID) == -1: self.eegInlet = StreamInlet(stream) self.eegTimeCorrection = self.eegInlet.time_correction() self.state = DataCollectionState.RUNNING self.doneCheckEEG = True def push_marker(self, timestamp, currentChar): self.markerOutlet.push_sample(currentChar, timestamp) # Push key marker with timestamp via LSL for other programs. self.markers.append([timestamp, currentChar]) def pull_eeg_data(self, timeout = 0.0, max_samples = 360): samples, timestamps = self.eegInlet.pull_chunk(timeout, max_samples) # Pull samples. timestampCount = len(timestamps) if(timestampCount > 0): print('Number of samples: {0} | Time since last: {1}'.format(timestampCount, time() - self.lastEEGSampleTime)) self.lastEEGSampleTime = time() for i in range(0, len(timestamps)): self.eegData.append([timestamps[i]] + samples[i]) def save_data(self): info = self.eegInlet.info() desc = info.desc() chanNum = info.channel_count() channels = desc.child('channels').first_child() channelNames = [channels.child_value('label')] for i in range(1, chanNum): channels = channels.next_sibling() channelNames.append(channels.child_value('label')) startTime = datetime.datetime.fromtimestamp(self.startTime).strftime(Constants.SESSION_FILE_DATETIME_FORMAT) finishTime = datetime.datetime.fromtimestamp(self.finishTime).strftime(Constants.SESSION_FILE_DATETIME_FORMAT) # Save EEG Data fileBase = os.path.join('session_data', self.user, self.mode.name, self.user + '_' + self.mode.name + '_' + startTime + '_' + finishTime) file = fileBase + '_EEG.csv' helpers.ensure_dir(file) with open(file, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(['timestamp'] + channelNames) for data in self.eegData: writer.writerow(data) print('Saved EEG data to: ' + file) # Save Marker Data file = os.path.join('session_data', self.user, self.mode.name, self.user + '_' + self.mode.name + '_' + startTime + '_' + finishTime).replace(':','\ua789') file = fileBase + '_MRK.csv' helpers.ensure_dir(file) with open(file, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(['timestamp','key marker']) for data in self.markers: writer.writerow(data) print('Saved Marker data to: ' + file) def generate_passwords(self, mode, iterations): passwords = [''] * iterations if mode == PasswordTypes.PIN_FIXED_4: length = 4 poolInit = '0123456789' elif mode == PasswordTypes.MIXED_FIXED_8: length = 8 poolInit = 'abcdefghijklmnopqrstuvwxyz' pool = poolInit # Calculate number of each character required for even distribution. freq = math.floor(iterations * length / len(pool)) poolTrack = [freq] * len(pool) # Keeps track of how many of each letter has been used. for i in range(iterations): for j in range(length): if len(poolTrack) != 0: index = random.randint(0, len(poolTrack) - 1) char = pool[index] poolTrack[index] -= 1 if poolTrack[index] == 0: poolTrack.pop(index) pool = pool.replace(char,'') # Once we've used the minimum required "freq" of each character, we simply do a random choice from the initial pool. else: char = random.choice(poolInit) passwords[i] += char.upper() return passwords def draw_static_ui(self): fontPassEnt = pygame.font.Font(None, 40) passEnt = 'Passwords Entered: ' passEntS = fontPassEnt.render(passEnt, 1, (0,0,0)) iter = str(self.currentPassIndex) + ' / ' + str(self.totalIterations) iterS = fontPassEnt.render(iter, 1, (0,0,0)) iterOffsetX = fontPassEnt.size(iter)[0] + 10 self.screen.blit(passEntS, (self.width - iterOffsetX - fontPassEnt.size(passEnt)[0] - 10, 10)) self.screen.blit(iterS, (self.width - iterOffsetX, 10)) if self.state == DataCollectionState.RUNNING: instruct = 'Type the password below, press ENTER when done:' elif self.state == DataCollectionState.MUSE_DISCONNECTED: instruct = 'Error: a Muse LSL stream must be active to continue (Muse ID: {0})'.format(self.museID) else: instruct = 'Finished session. This window will close in a moment.' fontInstruct = pygame.font.Font(None, 24) instructS = fontInstruct.render(instruct, 1, (0,0,0)) instructSize = fontInstruct.size(instruct) self.screen.blit(instructS, (self.width/2 - instructSize[0]/2, self.height/4 - instructSize[1]/2)) def process_input(self): for event in pygame.event.get(): if self.state == DataCollectionState.RUNNING: currentPass = self.passwords[self.currentPassIndex] currentChar = currentPass[self.currentCharIndex] if event.type == pygame.KEYDOWN: if (event.key == ord(currentChar) or event.key == ord(currentChar.lower())) and not self.donePass: newEvent = pygame.event.Event(pygame.KEYDOWN, {'unicode': currentChar.upper(),'key': ord(currentChar.upper()), 'mod': None}) self.input.get_event(newEvent) self.push_marker(float(time()), currentChar) if self.currentCharIndex < len(currentPass) - 1: self.currentCharIndex += 1 else: self.donePass = True elif event.key == pygame.K_RETURN and self.donePass: self.currentCharIndex = 0 self.currentPassIndex += 1 if self.currentPassIndex == self.totalIterations: self.state = DataCollectionState.FINISHED self.input.get_event(event) self.donePass = False if event.type == pygame.QUIT: pygame.quit() def process_logic(self): if self.state == DataCollectionState.MUSE_DISCONNECTED: if self.doneCheckEEG == True: self.doneCheckEEG = False threading.Thread(target = self.get_eeg_stream, kwargs={'timeout' : 5}).start() elif self.state == DataCollectionState.RUNNING: self.pull_eeg_data() elif self.state == DataCollectionState.FINISHED: if self.finishTime == 0: self.finishTime = time() self.save_data() if time() - self.finishTime >= 3: self.gameRunning = False self.input.update() def draw_password(self): font = pygame.font.Font(None, 50) password = self.passwords[self.currentPassIndex] passwordS = font.render(password, 1, (0,0,0)) passwordSize = font.size(password) self.screen.blit(passwordS, (self.inputPosition[0], self.height/2 - passwordSize[1]/2 - self.inputSize[1])) def draw(self): self.screen.fill((255,255,255)) self.draw_static_ui() if self.state == DataCollectionState.RUNNING: self.draw_password() self.input.draw(self.screen) pygame.display.flip() def start(self): self.gameRunning = True while self.gameRunning: self.process_input() self.process_logic() self.draw() pygame.quit()
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') clock = pygame.time.Clock() intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = Bedroom(screen, text_box) kitchen = Kitchen(screen, text_box) final = Final(screen, text_box) ##### NEW CLASS FOR DISPLAY TEXTBOX ######## Text3 = A_textbox(screen) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) foyer = Foyer(screen, text_box) ##### driving/foyer/etc text1 set true to display only once in its lifetime in the main loop iterations###### drivingtext1 = True while 1: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): print "pass intro" driving.enter() # print 1 ######## DISPLAY TEXT FOR DRIVING SCENE####### if drivingtext1: Text3 = A_textbox(screen) Text3.text_generator(driving_script[0:4]) # tells main loop to stop entering drivingtext1 drivingtext1 = False #call function again to draw over drivingtext1 driving.enter() ####set drivingtext2 = true to begin next set of strings####### drivingtext2 = True pygame.time.delay(1000) ###calling the text generator function with script#### Text3.text_generator(driving_script[4:8]) #this delays the text on the screen so reader can read it pygame.time.delay(3000) pygame.time.wait(2) input_box(entry, screen) driving.next_scene(entry.check_user_input("1")) if driving.check_scene(): foyer.enter() if moving_scene['library']: library.enter() if moving_scene['bedroom']: print 2 bedroom.enter() if moving_scene['kitchen']: print 3 kitchen.enter() pygame.display.flip() clock.tick(30)
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = MasterBedroom(screen, text_box) ##### NEW CLASS FOR DISPLAY TEXTBOX ######## Text3 = A_textbox(screen) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) # driving/foyer/etc text1 set true to display only once in its lifetime in the main loop iterations drivingtext1 = True # foyertext1 = True while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): driving.enter() # input_box(entry) # friend_name = driving.get_user_input(entry) ######## DISPLAY TEXT FOR DRIVING SCENE####### if drivingtext1: show_text = A_textbox(screen) show_text.text_generator(driving_script[0:4]) # tells main loop to stop entering drivingtext1 drivingtext1 = False #call function again to draw over drivingtext1 driving.enter() drivingtext2 = True pygame.time.delay(1000) ###calling the text generator function with script#### Text3.text_generator(driving_script[4:8]) #this delays the text on the screen so reader can read it pygame.time.delay(3000) pygame.time.wait(2) # pygame.time.wait(2) if driving.check_scene(): foyer.enter() # if foyertext1: # text_generator("You enter the house with your friend and ring the bell. No answer.", (100,460)) # text_generator("Your friend shrugs and pushes the door. You both enter and see three", (100,490)) # text_generator("people standing in the foyer: an elderly man, a woman in a red dress and heels,", (100,520)) # text_generator("and a teenage boy in goth makeup.", (100, 550)) # #tells main loop to stop entering foyertext1 # foyertext1 = False # # #call function again to draw over foyertext1 # foyer.enter() # # foyertext2 = True # # pygame.time.delay(1000) # # text_generator("What do you do? Enter a number:", (100,460)) # text_generator("1. Talk to the elderly man", (100,490)) # text_generator("2. Talk to the beautiful woman.", (100,520)) # text_generator("3. Talk to the gothic teenager.", (100, 550)) # pygame.time.delay(2000) if foyer.check_scene(): library.enter() pygame.display.flip()
def run_game(): pygame.init() screen_size = (1200, 750) screen = pygame.display.set_mode(screen_size) screen_rect = screen.get_rect() pygame.display.set_caption("Mystery House") text_box = pygame.image.load('./images/text_box.png') clock = pygame.time.Clock() intro = Scene(screen) driving = DrivingScene(screen, text_box) foyer = Foyer(screen, text_box) library = Library(screen, text_box) bedroom = Bedroom(screen, text_box) kitchen = Kitchen(screen, text_box) final = Final(screen, text_box) pygame.mixer.init() pygame.mixer.music.load('./music/old city theme.ogg') pygame.mixer.music.play(-1) entry = TextBox(rect=(680, 700, 200, 30)) foyer = Foyer(screen, text_box) # pass_intro = True # drivingtext1 = True # drivingtext2 = False # foyertext2 = False # foyertext1 = True while 1: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit() entry.get_event(event) intro.enter() if intro.check_scene(): driving.enter() # if drivingtext1: # print 1 # text_generator(screen, clock, "You're driving with your best friend, heading home after a day of hiking.", (100,460)) # # text_generator(screen, clock, "Rain is beating hard on the roof of your car, the wipers swishing fast.", (100,490)) # # text_generator(screen, clock, "Your GPS takes you to some backroads, empty of light and other cars.", (100,520)) # # text_generator(screen, clock, "Suddenly, you and your friend jolt in your seats! You've hit something!", (100, 550)) # drivingtext1 = False # pygame.time.delay(1000) # pygame.display.update() # elif drivingtext2: # driving.enter() # text_generator(screen, clock, "What do you do? Enter a number:", (100,460)) # text_generator(screen, clock, "1. Get out of the car and check it out.", (100,490)) # text_generator(screen, clock, "2. Stay in the car.", (100,520)) # text_generator(screen, clock, "3. Quit Game. This is too scary.", (100, 550)) # pygame.time.delay(2000) # pygame.time.wait(2) input_box(entry, screen) driving.next_scene(entry.check_user_input("1")) # drivingtext2 = True # clock.tick(30) if driving.check_scene(): foyer.enter() if moving_scene['library']: library.enter() input_box(entry, screen) if moving_scene['bedroom']: bedroom.enter() input_box(entry, screen) if moving_scene['kitchen']: kitchen.enter() input_box(entry, screen) if compare_list(player_list, master_list): final.enter() pygame.display.flip() clock.tick(30)
class MainProgram(object): def __init__(self): """The initialisation function of key components of the main program""" pg.init() pg.display.set_caption("D5's Bargain Inspector") bg = pg.image.load('mainScreen.png') gameDisplay.blit(bg,(0,0)) self.red = [] self.blue = [] self.green = [] self.pink = [] self.colourA =[] self.colour = "" self.num_items = 0 self.finishedList =[] self.time = 0 self.frame_count = 0 self.frame_rate = 60 self.start_time = 180 self.screen = menuDisplay self.clock = pg.time.Clock() self.robot_loc = [] self.fps = 60.0 self.done = False self.input = TextBox((900,200,200,40),command=self.get_input, #setting the size and position of the text box clear_on_enter=True,inactive_on_enter=False) self.user_input = "" self.color = white self.prompt = self.make_prompt('Enter Red:BMW, Blue:Vauxhall, Green:Land Rover, Pink:Lexus') pg.key.set_repeat(*KEY_REPEAT_SETTING) #textbox to appear in the same position after action def make_prompt(self,Message): """ Function to create the labels, called everytime a new input is entered """ pg.draw.rect(menuDisplay , white,(820,165,400,30)) #1 is left right position, 2 is up down, 3 is width, 4 is height font = pg.font.SysFont("Times", 14) message = Message rend = font.render(message, True, pg.Color("black")) return (rend, rend.get_rect(topleft=(820,165)))#position of the text in the screen def event_loop(self): """ A continuous FOR loop which allows an exit for our main program""" for event in pg.event.get(): if event.type == pg.QUIT: self.done = True self.input.get_event(event) def random_types(self): """Randomly generates colours into the screen and randomly gives them a price and a name eg. red-bmw,price """ names = ["BMW", "Vauxhall", "Land Rover", "Lexus"] for i in range(50): item = random.randint(1,3) radx = random.randint(0,790) rady = random.randint(0,590) radp = random.randint(1,20) radnum = random.randint(1,4) - 1 radn = names[radnum] coords = [radx,rady,radp,radn] if item == 1: pg.draw.rect(menuDisplay , red,(radx,rady,10,10)) self.red.append(coords) elif item == 2: pg.draw.rect(menuDisplay , blue,(radx,rady,10,10)) self.blue.append(coords) elif item == 3: pg.draw.rect(menuDisplay, green,(radx,rady,10,10)) self.green.append(coords) elif item == 4: pg.draw.rect(menuDisplay, pink,(radx,rady,10,10)) self.pink.append(coords) i = i +1 def get_input(self,id,input): """ allows the user to search for cars by enterin a specific colour """ try: input = input.lower() self.user_input = input self.colour = input if self.user_input == "red" or self.user_input == "blue" or self.user_input == "green" or self.user_input == "pink": self.prompt = self.make_prompt('Where do you want to start : e.g. NW') self.input = TextBox((900,200,200,40),command=self.robot_start, # textbox position clear_on_enter=True,inactive_on_enter=False) if input == "red": for coord in self.red: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, red,(x,y,15,15)) self.colourA = self.red elif input == "blue": for coord in self.blue: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, blue,(x,y,15,15)) self.colourA = self.blue elif input == "green": for coord in self.green: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, green,(x,y,15,15)) self.colourA = self.green elif input == "pink": for coord in self.pink: x = coord[0] y = coord[1] pg.draw.rect(menuDisplay, pink,(x,y,15,15)) self.colourA = self.pink else: self.prompt = self.make_prompt('Please enter the colour type given') self.screen = menuDisplay except ValueError: print("ERROR") def robot_start(self,id,input): """ Allows the user to choose the starting position of the robot""" input = input.upper() self.robot_loc = input if input == "N": pg.draw.rect(menuDisplay, red,(400,0,20,30)) self.robot_loc = [400,0] elif input == "E": pg.draw.rect(menuDisplay, blue,(750,300,20,30)) self.robot_loc = [750,300] elif input == "S": pg.draw.rect(menuDisplay, pink,(400,550,20,30)) self.robot_loc = [400,550] elif input == "W": pg.draw.rect(menuDisplay, green,(10,300,20,30)) self.robot_loc = [10,300] elif input == "NW": pg.draw.rect(menuDisplay, bright_green,(10,10,20,30)) self.robot_loc = [10,10] elif input == "NE": pg.draw.rect(menuDisplay, bright_red,(750,10,20,30)) self.robot_loc = [750,10] elif input == "SW": pg.draw.rect(menuDisplay, red,(10,550,20,30)) self.robot_loc = [10,550] elif input == "SE": pg.draw.rect(menuDisplay, pink,(750,550,20,30)) self.robot_loc = [750,550] else: self.prompt = self.make_prompt('Please enter a valid co-cordinate for the robot to search') if input == "N" or input == "E" or input == "S" or input == "W" or input == "NW" or input == "NE" or input == "SW" or input == "SE": self.prompt = self.make_prompt('Please enter the number of car types you will like to find?') self.input = TextBox((900,200,200,40),command=self.number_of_items, #textbox position clear_on_enter=True,inactive_on_enter=False) def number_of_items(self,id,input): """ This will allow the user to enter the number of chosen car models they want to find""" if input.isdigit() and (int(input) <= len(self.colourA)): self.num_items = int(input) self.prompt = self.make_prompt('Enter the minutes you want the robot to search for?') self.input = TextBox((900,200,200,40),command=self.input_time, #textbox pisition clear_on_enter=True,inactive_on_enter=False) else: self.prompt = self.make_prompt('Please enter how many chosen car models to find?') def input_time(self,id,input): """ Allows the user to enter the time for the robot to search for car types""" if input.isdigit() and int(input) <= 15: self.time = input self.start_time = int(self.time) * 60 else: self.prompt = self.make_prompt('Please enter a valid time, e.g 1 for 1 minute') def collide(self,c1, p1, p2, p3,xORy): """ Tests to see if the next pixals are not white""" locations = [p1,p2,p3] self.Collide = False i = 0 if xORy == "X": while i != 3: colour = menuDisplay.get_at((c1,locations[i])) # gets the colour of the pixal at the coordinates if (c1 >= self.nextX and c1 <= (self.nextX + 15)) and (p1 >= self.nextY and p1 <= (self.nextY + 15)): i=i+1 continue elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255): self.Collide = True break else: i=i+1 continue elif xORy == "Y": while i != 3: colour = menuDisplay.get_at((locations[i],c1)) if (c1 >= self.nextY and c1 <= (self.nextY + 15)) and (p1 >= self.nextX and p1 <= (self.nextX + 1)): i=i+1 continue elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255): self.Collide = True break else: i=i+1 continue def bubbleSort(self,colourL): """ Used to sort the list in order of price, cheapest first""" for passnum in range(len(colourL)-1,0,-1): for i in range(passnum): if colourL[i][2]>colourL[i+1][2]: temp = colourL[i] colourL[i] = colourL[i+1] colourL[i+1] = temp def binarySearch(self, alist, item): """Used to search a list for the search item and returns all infomation about that item""" first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint][0] == item: return(alist[midpoint]) else: if item < alist[midpoint][0]: last = midpoint-1 else: first = midpoint+1 return found def quick_sort(self,items): """ Used to sort a list in order by x coords for binary search""" if len(items) > 1: pivot_index = len(items) // 2 smaller_items = [] larger_items = [] for i, val in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: larger_items.append(val) self.quick_sort(smaller_items) self.quick_sort(larger_items) items[:] = smaller_items + [items[pivot_index]] + larger_items def robot_move(self): """Makes the robot move visually and makes a countdown timer that countdowns from the users input""" i = 0 if self.colour == "red": self.bubbleSort(self.red) locations = self.red elif self.colour == "blue": self.bubbleSort(self.blue) locations = self.blue elif self.colour == "green": self.bubbleSort(self.green) locations = self.green elif self.colour == "pink": self.bubbleSort(self.pink) locations = self.pink #pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30)) print(locations) while i != self.num_items : #Makes the robot move visually self.event_loop() nextX = locations[i][0] nextY = locations[i][1] if self.robot_loc[0] == nextX and self.robot_loc[1] == nextY: pg.draw.rect(menuDisplay, black,(nextX,nextY ,15,15)) self.finishedList.append(locations[i][0]) i = i + 1 elif self.robot_loc[0] < nextX: pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30)) self.robot_loc[0] = self.robot_loc[0] + 1 pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30)) self.input.draw(self.screen) elif self.robot_loc[1] < nextY: pg.draw.rect(menuDisplay,white,(self.robot_loc[0],self.robot_loc[1],20,30)) self.robot_loc[1] = self.robot_loc[1] + 1 pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30)) self.input.draw(self.screen) elif self.robot_loc[0] > nextX: pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30)) self.robot_loc[0] = self.robot_loc[0] - 1 pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30)) self.input.draw(self.screen) elif self.robot_loc[1] > nextY: pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30)) self.robot_loc[1] = self.robot_loc[1] - 1 pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30)) self.input.draw(self.screen) self.event_loop() # Starts the timer countdown pg.draw.rect(menuDisplay, green,(810,540,400, 60)) total_seconds = self.frame_count // self.frame_rate total_seconds = self.start_time - (self.frame_count // self.frame_rate) if total_seconds < 0: total_seconds = 0 minutes = total_seconds // 60 seconds = total_seconds % 60 output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) text = font.render(output_string, True, black) menuDisplay.blit(text, [810, 540]) if output_string == "Time left: 00:00": self.done = True self.frame_count += 1 clock.tick(frame_rate) pg.display.flip() self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() if self.colour == "red": self.quick_sort(self.red) elif self.colour == "blue": self.quick_sort(self.blue) elif self.colour == "green": self.quick_sort(self.green) elif self.colour == "pink": self.quick_sort(self.pink) self.clock.tick(self.fps) if self.time != 0: self.done = True def output_lists(self,i,Space): """Displays the list of cheapest items picked up""" if self.colour == "red": output = self.binarySearch(self.red, self.finishedList[i]) elif self.colour == "blue": output = self.binarySearch(self.blue, self.finishedList[i]) elif self.colour == "green": output = self.binarySearch(self.green, self.finishedList[i]) elif self.colour == "pink": output = self.binarySearch(self.pink, self.finishedList[i]) font = pg.font.SysFont("Times", 20) message = str(output[3]) + " | " + str(output[2]) rend = font.render(message, True, pg.Color("black")) return (rend, rend.get_rect(topleft=(820,35+Space))) def main_loop(self): """ Makes the program loops and call certain function only if an event has been met""" i = 0 """adds sound to the code""" pg.mixer.music.load('programsound.wav') pg.mixer.music.play(-1) space = 0 self.random_types() while not self.done: self.event_loop() self.input.update() self.input.draw(self.screen) self.screen.blit(*self.prompt) pg.display.update() self.clock.tick(self.fps) if self.time != 0: self.done = True self.done = False if self.time != 0: self.robot_move() pg.draw.rect(menuDisplay , green,(810,0,450,540)) pg.display.update() while i != self.num_items: self.prompt = self.output_lists(i,space) self.screen.blit(*self.prompt) space = space + 20 pg.display.update() i = i+1 self.done = False #self.main_program() while not self.done: self.event_loop()