def __init__(self, view): self.view = view print('Generating world...') Maps.generate_world(self.view.server.numPlayers() + 1) print("Sending world data") self.view.server.sendtoall(Maps.get_world())
def update(self): self.loadPlayers() for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: self.quit() elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: self.playerHost.updateKeyboard() if event.key == pygame.K_w: self.playerHost.direction = 'w' elif event.key == pygame.K_s: self.playerHost.direction = 's' elif event.key == pygame.K_a: self.playerHost.direction = 'a' elif event.key == pygame.K_d: self.playerHost.direction = 'd' elif event.type == pygame.MOUSEMOTION: mouseX, mouseY = event.pos self.playerHost.setMousePosition(mouseX, mouseY) elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP: self.playerHost.updateMouseButtons() Maps.update() threading.Thread(target=self.sendData).start()
def __init__(self): ''' Constructor ''' Maps.generate_world(2) self.player = PlayerHost(0, 300, 300, 0) Maps.maps[0].add_player(self.player)
def get_movie_objs(data_dict): movies = set([]) for theatre in data_dict.keys(): address = data_dict[theatre]['address'] (lat,lng) = Maps.get_coordinates(address) for name in data_dict[theatre]['movies'].keys(): run_time = data_dict[theatre]['movies'][name]['run_time'] for time in data_dict[theatre]['movies'][name]['start_times']: movie_obj = movie(name, time, run_time, theatre, lat, lng) movies.add(movie_obj) return movies
def __init__(self, window): self.screen = window.screen self.width = window.width self.height = window.height self.map = Maps.getMap(2) self.isChest = False self.loadSprites()
def state_loop(self): while self.open: try: data, addr = self.socket.recvfrom(16384) data = msgpack.loads(data) if data == "Sending game data": self.downloading = True self.send("Waiting for data") print(str(data), addr) print("Waiting for data") elif isinstance(data, dict): dataType = data.keys()[0] if dataType == "World": Maps.load_world(data) self.worldLoaded = True self.send("World loaded") print(str(data), addr) print("World loaded") elif dataType == "PlayerDataForClient": if self.playerData is None: self.send("Player loaded") print(str(data), addr) print("Player loaded") self.playerData = data["PlayerDataForClient"] elif dataType == "PlayersNames": self.playersNames = data["PlayersNames"] self.send("Players names loaded") print(str(data), addr) print("Players names loaded") elif dataType == "Map": self.mapData = data["Map"] currentTime = getCurrentTimeMs() Misc.ms = currentTime - self.lastTime self.lastTime = currentTime except socket.error as e: if e.errno == errno.WSAEMSGSIZE: raise (e) if e.errno != errno.WSAEWOULDBLOCK: print(e)
def get_maps(self): maps = Maps.get_maps() random.shuffle(maps) for i in range(4): map = Subclasses.Map(maps[i], i) icon = QtGui.QPixmap("%s%s.png" % (self.maps_directory, maps[i][0])) map.setPixmap(icon) clickable(map).connect(self.click_on_map) self.map_objects.append(map) return self.map_objects
def update(self): global done, mouseX, mouseY, debug for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: done=True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_w: self.p1.direction = 'w' elif event.key == pygame.K_s: self.p1.direction = 's' elif event.key == pygame.K_a: self.p1.direction = 'a' elif event.key == pygame.K_d: self.p1.direction = 'd' elif event.type == pygame.MOUSEMOTION: mouseX, mouseY = event.pos self.p1.setMousePosition(mouseX,mouseY) for enemy in self.enemys: enemy.setMousePosition(self.p1.x,self.p1.y) #p1.update(display, mouseX, mouseY) Maps.update()
def __init__(self, params): ''' Constructor ''' global redShip2, blueShip, display, mouseX, mouseY #p1 = Player1(display, display.get_width()/2-bluShipRect.width/2, display.get_height()/2-bluShipRect.height/2, blueShip) self.p1 = Player1(display, 400, 400, blueShip) self.enemys = [Player2(display, 300, 400, redShip2),Player2(display, 350, 300, redShip2),Player2(display, 400, 200, redShip2)] Maps.generate_world_teaser() map1 = Maps.maps[0] map2 = Maps.maps[2] map1.add_player(self.p1) for enemy in self.enemys: map2.add_player(enemy) mouseX = 0 mouseY = 0
def __init__(self, mesh, mapping=None, indActive=None, **kwargs): Utils.setKwargs(self, **kwargs) assert isinstance(mesh, Mesh.BaseMesh), "mesh must be a SimPEG.Mesh object." if indActive is not None and indActive.dtype != 'bool': tmp = indActive indActive = np.zeros(mesh.nC, dtype=bool) indActive[tmp] = True if indActive is not None and mapping is None: mapping = Maps.IdentityMap(nP=indActive.nonzero()[0].size) self.regmesh = RegularizationMesh(mesh, indActive) self.mapping = mapping or self.mapPair(mesh) self.mapping._assertMatchesPair(self.mapPair) self.indActive = indActive
def update(self): for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: Misc.done = True elif event.type == pygame.KEYDOWN: self.player.updateKeyboard() if event.key == pygame.K_w: self.player.direction = 'w' elif event.key == pygame.K_s: self.player.direction = 's' elif event.key == pygame.K_a: self.player.direction = 'a' elif event.key == pygame.K_d: self.player.direction = 'd' elif event.type == pygame.KEYUP: self.player.updateKeyboard() elif event.type == pygame.MOUSEMOTION: mouseX, mouseY = event.pos self.player.setMousePosition(mouseX, mouseY) elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP: self.player.updateMouseButtons() Maps.update()
def main(): MAP_WIDTH = 25 MAP_HEIGHT = 25 PLAYER = Objects.Player(int(MAP_WIDTH / 2), int(MAP_HEIGHT / 2)) ITEMS = Objects.Items() ENEMIES = Objects.spawnEnemies(5, MAP_WIDTH, MAP_HEIGHT) MAP = Maps.TestMap(MAP_WIDTH, MAP_HEIGHT, PLAYER, ITEMS, ENEMIES) timer = 0 while True: # Print Updated Map MAP.printMap(PLAYER, ITEMS) # Input from User inp = Processing.processInput(PLAYER, MAP, ITEMS, ENEMIES) # TODO: Update Map, based on input and player position MAP.updateMap(inp, PLAYER, ENEMIES, timer) timer += 1 return (0)
def customMap(arg=0): maps = Maps() maps.openMap([0, "custom"])
def adventure(arg=0): maps = Maps() maps.openMap([0, "adventure"])
def createMaps(arg=0): maps = Maps() maps.createMap()
import Maps new_map = Maps.Maps("first", 10) new_map.Create('forrest') events = 0 for i in range(0, new_map.getSize()): line = "" for j in range(0, new_map.getSize()): try: line += new_map.grid[i][j].getGraphic() except: line += new_map.grid[i][j] line += " @endline" if len(line) < new_map.getSize(): print("Line Length error.", end="") print(line) input("This is the map.")
def __init__(self, mesh, mapping=None, **kwargs): Utils.setKwargs(self, **kwargs) assert isinstance(mesh, Mesh.BaseMesh), "mesh must be a SimPEG.Mesh object." self.mesh = mesh self.mapping = mapping or Maps.IdentityMap(mesh)
import pygame, sys, StartUp, Maps pygame.init() screen, clock = StartUp.start() screenW, screenH, fps = StartUp.giveDisplayInfo() editting = True blankMap = Maps.loadEmptyMap((screenW, screenH)) while editting: for event in pygame.event.get(): if event.type == pygame.QUIT or pygame.key.get_pressed( )[27]: # key 27 is escape editting = False screen.blit(blankMap, (0, 0)) pygame.display.update() pygame.quit() sys.exit()
print myLat, myLng #myLatMin = myLat + 0.1 #myLngMin = myLng - 0.1 #myLatMax = myLat - 0.1 #myLngMax = myLng + 0.1 #print myLatMin, myLatMax #print myLngMin, myLngMax myLat = myLat myLng = myLng myFilename = myPlace._name.replace(" ", "_") myFilename = "./" + myFilename + ".bmp" Maps.DrawMap(myLat, myLng, 0.01, 0.02, 16, myFilename) #myPyMap = pymap.Pynoramio() #myMap = myPyMap.get_from_area(myLatMin, myLngMin, myLatMax, myLngMax, picture_size = None) #print type(myMap) #print myMap if myQueryResult.has_attributions: print myQueryResult.html_attributions assert (0) myHeaders, myAirportData = readAirportList() print myHeaders
def seasonal_clusters(tp_da, sliced_dem, N, decades): """ K-means clustering of precipitation data as a function of seasons, decades and number of clusters. Returns spatial graphs, overlayed with the local topography contours. Inputs: UIB_cum: precipitation data (data array) sliced_dem: local topography data (data array) N: number of cluster to perform kmeans on (list) decades: decades to analyse (list ) Returns: FacetGrid plots """ UIB_cum = maps.cumulative_monthly(tp_da) # Seperation into seasons JFM = UIB_cum.where(UIB_cum.time.dt.month <= 3) OND = UIB_cum.where(UIB_cum.time.dt.month >= 10) AMJ = UIB_cum.where(UIB_cum.time.dt.month < 7).where( UIB_cum.time.dt.month > 3) JAS = UIB_cum.where(UIB_cum.time.dt.month < 10).where( UIB_cum.time.dt.month > 6) seasons = [JFM, AMJ, JAS, OND] scmap = {0: "Reds", 1: "Oranges", 2: "Blues", 3: "Greens"} # Loop over seasons, cluster numbers and decades for s in range(4): UIB_cluster_list = [] for n in N: UIB_dec_list = [] for d in decades: # Median cumulative rainfall for decades UIB_d = seasons[s].sel(time=slice( str(d) + "-01-01T12:00:00", str(d + 10) + "-01-01T12:00:00")) UIB_median = UIB_d.median(dim="time") # To DataFrame multi_index_df = UIB_median.to_dataframe("Precipitation") df = multi_index_df.reset_index() df_clean = df[df["Precipitation"] > 0] X = (df_clean["Precipitation"].values).reshape(-1, 1) # K-means kmeans = KMeans(n_clusters=n, random_state=0).fit(X) df_clean["Labels"] = kmeans.labels_ # To DataArray df_plot = df_clean[["Labels", "latitude", "longitude"]] df_pv = df_plot.pivot(index="latitude", columns="longitude") df_pv = df_pv.droplevel(0, axis=1) da = xr.DataArray(data=df_pv, name=str(d) + "s") UIB_dec_list.append(da) UIB_cluster_list.append( xr.concat( UIB_dec_list, pd.Index(["1980s", "1990s", "2000s", "2010s"], name="Decade"), )) # Combine data for plot formatting UIB_clusters1 = xr.concat(UIB_cluster_list[0:3], pd.Index(np.arange(2, 5), name="N")) UIB_clusters2 = xr.concat(UIB_cluster_list[3:6], pd.Index(np.arange(5, 8), name="N")) UIB_clusters3 = xr.concat(UIB_cluster_list[6:9], pd.Index(np.arange(8, 11), name="N")) # Plots g = UIB_clusters1.plot( x="longitude", y="latitude", col="Decade", row="N", vmin=-2, vmax=10, subplot_kws={"projection": ccrs.PlateCarree()}, cmap=scmap[s], add_colorbar=False, ) for ax in g.axes.flat: ax.set_extent([71, 83, 30, 38]) sliced_dem.plot.contour(x="lon", y="lat", ax=ax, cmap="bone_r") g = UIB_clusters2.plot( x="longitude", y="latitude", col="Decade", row="N", vmin=-2, vmax=10, subplot_kws={"projection": ccrs.PlateCarree()}, cmap=scmap[s], add_colorbar=False, ) for ax in g.axes.flat: ax.set_extent([71, 83, 30, 38]) sliced_dem.plot.contour(x="lon", y="lat", ax=ax, cmap="bone_r") g = UIB_clusters3.plot( x="longitude", y="latitude", col="Decade", row="N", vmin=-2, vmax=10, subplot_kws={"projection": ccrs.PlateCarree()}, cmap=scmap[s], add_colorbar=False, ) for ax in g.axes.flat: ax.set_extent([71, 83, 30, 38]) sliced_dem.plot.contour(x="lon", y="lat", ax=ax, cmap="bone_r") plt.show()
for i in range(SPOTNUM): #Swaps genetic information from each parent AKA Crossover childSpotList = crossover(population) #Spawn a new child child = iMap(tilemap,childSpotList) #Apply random genetic variation mutate(child) #Evaluate fitness of mutant child child.mapFitness() #Add mutant child to new population newPopulation.append(child) return newPopulation #Initialisations DISPLAYSURF = Maps.uiInit() #Generates new random map for algorithm to run inside tilemap = Maps.createMap() population = generatePopulation(50,tilemap) highscore = 0 generation = 0 #Genetic Algorithm runs, displays every 10 generations while True: for i in range(10): population = reproduce(population,tilemap) #Gets best child for display bestFitness = 0 for x,imap in enumerate(population): if imap.fitness > bestFitness: bestIndex = x bestFitness = imap.fitness
import Maps distance_km = 50 lats = [-23.5515, -23.4209995, -23.3209995, -23.65515] longs = [-51.4614, -51.9330558, -51.3614, -51.59330558] gmap, distances = Maps.buildMapWithConditionalMarkers(map_name="testMap", lats=lats, longs=longs, distance_km=distance_km) Maps.printDistancesMatrix(distances=distances)
def run(displayInfo): screen = displayInfo[0] clock = displayInfo[1] screenW = displayInfo[2] screenH = displayInfo[3] fps = displayInfo[4] font = pygame.font.Font('freesansbold.ttf', 64) p1ChooseText = font.render('Player 1 Ban', True, Colors.BLUE) p2ChooseText = font.render('Player 2 Ban', True, Colors.RED) bo5Text = font.render('BEST of 5', True, Colors.BLACK) bo9Text = font.render('BEST of 9', True, Colors.BLACK) textCoords = ((screenW // 2) - (p1ChooseText.get_width() // 2), 0) previewWidth = screenW // 6 previewHeight = screenH // 5 widthUnit = previewWidth // 6 midH = screenH // 2 mapH = midH - (previewHeight // 2) map1Preview = Maps.loadMap1((previewWidth, previewHeight))[1] map2Preview = Maps.loadMap2((previewWidth, previewHeight))[1] map3Preview = Maps.loadMap3((previewWidth, previewHeight))[1] map4Preview = Maps.loadMap4((previewWidth, previewHeight))[1] map5Preview = Maps.loadMap5((previewWidth, previewHeight))[1] preview1Rect = pygame.Rect(widthUnit, mapH, previewWidth, previewHeight) preview2Rect = pygame.Rect(2 * widthUnit + previewWidth, mapH, previewWidth, previewHeight) preview3Rect = pygame.Rect(3 * widthUnit + 2 * previewWidth, mapH, previewWidth, previewHeight) preview4Rect = pygame.Rect(4 * widthUnit + 3 * previewWidth, mapH, previewWidth, previewHeight) preview5Rect = pygame.Rect(5 * widthUnit + 4 * previewWidth, mapH, previewWidth, previewHeight) screen.fill(Colors.WHITE) screen.blit(map1Preview, (widthUnit, mapH)) screen.blit(map2Preview, (2 * widthUnit + previewWidth, mapH)) screen.blit(map3Preview, (3 * widthUnit + 2 * previewWidth, mapH)) screen.blit(map4Preview, (4 * widthUnit + 3 * previewWidth, mapH)) screen.blit(map5Preview, (5 * widthUnit + 4 * previewWidth, mapH)) picking = True mapsBanned = 0 totalMaps = 5 mouseWasDown = True lastX = 0 map1Banned = False map2Banned = False map3Banned = False map4Banned = False map5Banned = False player1Picking = True mapOn = 1 p1First = random.randint(0, 1) if p1First == 1: cont1 = pygame.joystick.Joystick(0) cont2 = pygame.joystick.Joystick(1) else: cont1 = pygame.joystick.Joystick(1) cont2 = pygame.joystick.Joystick(0) lastFrameToggle = False bestOfToggle = True while picking: if (cont1.get_button(4) or cont2.get_button(4) or cont1.get_button(5) or cont2.get_button(5)) and not lastFrameToggle: bestOfToggle = not bestOfToggle lastFrameToggle = (cont1.get_button(4) or cont2.get_button(4) or cont1.get_button(5) or cont2.get_button(5)) if player1Picking: contUsing = cont1 else: contUsing = cont2 for event in pygame.event.get(): # This if statement checks when to stop running the game code if event.type == pygame.QUIT or pygame.key.get_pressed( )[27]: # key 27 is escape picking = False return -1, 0, 0 currentX = contUsing.get_axis(0) if lastX > -0.8 and currentX < -0.8: if mapOn != 1: mapOn -= 1 else: mapOn = 5 if lastX < 0.8 and currentX > 0.8: if mapOn != 5: mapOn += 1 else: mapOn = 1 if not mouseWasDown and contUsing.get_button(0): if not map1Banned and mapOn == 1: map1Banned = True mapsBanned += 1 if mapsBanned == 1: player1Picking = False elif mapsBanned == 3: player1Picking = True elif not map2Banned and mapOn == 2: map2Banned = True mapsBanned += 1 if mapsBanned == 1: player1Picking = False elif mapsBanned == 3: player1Picking = True elif not map3Banned and mapOn == 3: map3Banned = True mapsBanned += 1 if mapsBanned == 1: player1Picking = False elif mapsBanned == 3: player1Picking = True elif not map4Banned and mapOn == 4: map4Banned = True mapsBanned += 1 if mapsBanned == 1: player1Picking = False elif mapsBanned == 3: player1Picking = True elif not map5Banned and mapOn == 5: map5Banned = True mapsBanned += 1 if mapsBanned == 1: player1Picking = False elif mapsBanned == 3: player1Picking = True if mapsBanned >= totalMaps - 1: picking = False mouseWasDown = contUsing.get_button(0) lastX = contUsing.get_axis(0) screen.fill(Colors.WHITE) if mapOn == 1: pygame.draw.rect(screen, Colors.YELLOW, preview1Rect.inflate(10, 10)) elif mapOn == 2: pygame.draw.rect(screen, Colors.YELLOW, preview2Rect.inflate(10, 10)) elif mapOn == 3: pygame.draw.rect(screen, Colors.YELLOW, preview3Rect.inflate(10, 10)) elif mapOn == 4: pygame.draw.rect(screen, Colors.YELLOW, preview4Rect.inflate(10, 10)) elif mapOn == 5: pygame.draw.rect(screen, Colors.YELLOW, preview5Rect.inflate(10, 10)) screen.blit(map1Preview, (widthUnit, mapH)) screen.blit(map2Preview, (2 * widthUnit + previewWidth, mapH)) screen.blit(map3Preview, (3 * widthUnit + 2 * previewWidth, mapH)) screen.blit(map4Preview, (4 * widthUnit + 3 * previewWidth, mapH)) screen.blit(map5Preview, (5 * widthUnit + 4 * previewWidth, mapH)) if map1Banned: pygame.draw.rect(screen, Colors.RED, preview1Rect) if map2Banned: pygame.draw.rect(screen, Colors.RED, preview2Rect) if map3Banned: pygame.draw.rect(screen, Colors.RED, preview3Rect) if map4Banned: pygame.draw.rect(screen, Colors.RED, preview4Rect) if map5Banned: pygame.draw.rect(screen, Colors.RED, preview5Rect) if bestOfToggle: screen.blit(bo5Text, (0, 0)) else: screen.blit(bo9Text, (0, 0)) if p1First: if player1Picking: screen.blit(p1ChooseText, textCoords) else: screen.blit(p2ChooseText, textCoords) else: if player1Picking: screen.blit(p2ChooseText, textCoords) else: screen.blit(p1ChooseText, textCoords) pygame.display.update() mapNum = -1 if not map1Banned: mapNum = 1 elif not map2Banned: mapNum = 2 elif not map3Banned: mapNum = 3 elif not map4Banned: mapNum = 4 elif not map5Banned: mapNum = 5 if bestOfToggle: bo = 5 else: bo = 9 return 2, mapNum, bo
import os import time import subprocess import cv2 from Initial import Main import Maps from OCR import ocr if __name__=="__main__": start = Main() maps = Maps.Maps() start.tts("welcome back") while True: start.tts("Choose a function") operation = start.stt("shortanswer") if operation in start.getcommand("maps"): maps.mapsloop() elif operation in start.getcommand("facerec"): start.writefunction("f") while (not (start.readfunction()=="a")): time.sleep(0.1) //delay start.writefunction("r") start.modeluse = True elif operation in start.getcommand("ocr"): start.writefunction("f") time.sleep(1) img = cv2.imread("./frame.jpg") output = ocr(img) read_short = output.split("\n") start.tts(",".join(read_short[0:start.getconfig("minreadlines")]))
ytSearch.searchingVideo(command) elif 'weather' in command: Weather.GetWeather() elif "restart" in command: restart.Logout() elif "hibernate" in command or "sleep" in command: hibernate.Logout() elif "log off" in command or "sign out" in command: LogOff.Logout() elif "where is" in command or "locate" in command: Maps.Maps(command) elif 'shutdown' in command or 'power off' in command: shutdown.Logout() elif 'excel' in command: openExcel.openProgram() elif 'powerpoint' in command: openPowerpoint.openProgram() elif 'word' in command: openWord.openProgram() elif 'one note' in command: openOneNote.openProgram()
import Maps mapobj = Maps.Map21x21() gameover = False while gameover == False: print('Actions: find, viewmap, exit') action = input('What would you like to do?: ') if (action == 'find'): print('Object Found at: ' + str( mapobj.findValue( input('What value would you like to find? '), input( 'How many times would you like to skip until you find your value? ' )))) elif (action == 'viewmap'): mapobj.printMap(1) elif (action == 'exit'): gameover = True else: print('That is not an action!') input('Press [ENTER] to exit...')
def addSample(self, Length: int): fArray = Maps.randFloats(Length) ω = [Maps.float2HT(fArray[i]) for i in range(Length)] self.SampleSpace.append(ω) self.RandVariables.append(self.RandVariable(ω))
def run(displayInfo, score, char1, char2, boNum): p1BallColor = Colors.WHITE p2BallColor = Colors.WHITE sprite1 = char1.sprite sprite2 = char2.sprite pygame.mouse.set_visible(False) # Unpackaging all of the information screen = displayInfo[0] clock = displayInfo[1] screenW = displayInfo[2] screenH = displayInfo[3] fps = displayInfo[4] # Main gameplay inGameplay = True mouseClick = False matchEnd = False playerObjs = [] X = 0 Y = 1 sc = Scaler.Scaler(screenW, screenH) map1 = Maps.loadSoccer((screenW, screenH)) p1Score = score[0] p2Score = score[1] p1DispScore = pygame.image.load('Images/bo' + str(boNum) + '-' + str(p1Score) + '.png') p2DispScore = pygame.image.load('Images/bo' + str(boNum) + '-' + str(p2Score) + '.png') p1DispScore = pygame.transform.scale( p1DispScore, (rint(screenW / 8), rint(screenH / 13.5))) p2DispScore = pygame.transform.scale( p2DispScore, (rint(screenW / 8), rint(screenH / 13.5))) playerRadius = screenW // 50 lengthUnit = playerRadius // 7.5 # 20 sprite1 = pygame.transform.scale(sprite1, (playerRadius * 2, playerRadius * 2)) sprite2 = pygame.transform.scale(sprite2, (playerRadius * 2, playerRadius * 2)) p1Pos = (int(playerRadius + lengthUnit * 20), int(screenH / 2)) p1 = Player(p1Pos, playerRadius, sprite1, lengthUnit, map1, p1BallColor, 0, 0) p2Pos = (int(screenW - playerRadius - lengthUnit * 20), int(screenH / 2)) p2 = Player(p2Pos, playerRadius, sprite2, lengthUnit, map1, p2BallColor, 1, 0) deadzone = 0.9 # 0.9 normally moveDeadzone = 0.3 # 0 normally I guess triggerDeadzone = 0.4 helpEnabled = False #True helper1 = Bot(p1, p2, map1) helper2 = Bot(p2, p1, map1) players = [] players.append(p1) players.append(p2) projectiles = [] gameBall = Ball((screenW // 2, screenH // 2), playerRadius) frames = 0 maxFrames = 3600 minFrames = 600 maxPerc = 0.5 #maxPerc = 0.6 borderInfo = closeInMap(screen, 0) banter1Played = False banter2Played = False #------------------------------------- CHANGE THIS ------------------------------ doingBanter = False #(score[0] == 0 and score[1] == 0) #-------------------------------------------------------------------------------- p1ZoomScreen = pygame.Surface((screenW, screenH)) p1ZoomScreen.fill(Colors.GREY) bigSprite1 = pygame.transform.scale(sprite1, ((screenH, screenH))) bigSprite1 = pygame.transform.rotate(bigSprite1, 270) draw(p1ZoomScreen, bigSprite1, (screenW // 2, screenH // 2)) p2ZoomScreen = pygame.Surface((screenW, screenH)) p2ZoomScreen.fill(Colors.GREY) bigSprite2 = pygame.transform.scale(sprite2, ((screenH, screenH))) bigSprite2 = pygame.transform.rotate(bigSprite2, 90) draw(p2ZoomScreen, bigSprite2, (screenW // 2, screenH // 2)) while doingBanter: if not banter1Played: char1.playBanterOn(noiseChannel) banter1Played = True if banter1Played and not noiseChannel.get_busy() and not banter2Played: char2.playBanterOn(noiseChannel) banter2Played = True else: screen.blit(p1ZoomScreen, (0, 0)) if banter2Played and noiseChannel.get_busy(): screen.blit(p2ZoomScreen, (0, 0)) elif banter1Played and banter2Played and not noiseChannel.get_busy(): doingBanter = False pygame.display.update() clock.tick(60) while inGameplay: controllersConnected = pygame.joystick.get_count() if controllersConnected != 2: # pause game return -1 else: # Checks if mouse is clicked if matchEnd: return 2 # Player controls inputs = pygame.key.get_pressed() moveStickPos = [] try: lastAimPos = [aimStickPos[0], aimStickPos[1]] except: lastAimPos = [(0, 0), (0, 0)] aimStickPos = [] triggerValues = [] button1 = [] downHat = [] for i in range(controllersConnected): controller = pygame.joystick.Joystick(i) controller.init() movePos = (controller.get_axis(0), controller.get_axis(1)) if math.hypot(movePos[0], movePos[1]) > moveDeadzone: moveStickPos.append(movePos) else: moveStickPos.append((0, 0)) aimPos = (controller.get_axis(3), controller.get_axis(4) ) # 3, 4 if math.hypot(aimPos[0], aimPos[1]) > deadzone: aimStickPos.append(aimPos) else: aimStickPos.append(lastAimPos[i]) downHat.append(controller.get_hat(0)[1] == -1) triggerValues.append(controller.get_axis(2)) button1.append(controller.get_button(0)) # Draws background screen.blit(map1, (0, 0)) # Draws players for i in range(len(players)): player = players[i] if helpEnabled and player.helpToggle and i == 1: if i == 0: helper1.update(projectiles) else: helper2.update(projectiles) projectile = player.update(button1[i], aimStickPos[i], triggerValues[i], moveStickPos[i], downHat[i], borderInfo) player.drawToScreen(screen) if projectile != 0: if i == 0: char1.playShootOn(p1ShootChannel) else: char2.playShootOn(p2ShootChannel) projectiles.append(projectile) # help used to be here # Draw projectiles p1hb = properHitbox(players[0].hitbox, players[0].pos) p2hb = properHitbox(players[1].hitbox, players[1].pos) for i in range(len(projectiles)): if i < len(projectiles): projectile = projectiles[i] result = projectile.update(map1, players, gameBall) if result == -1: projectiles.pop(i) i -= 1 elif result > 0: players[result - 1].resetFrames = 40 #20 projectiles.pop(i) i -= 1 else: projectile.drawToScreen(screen) result = gameBall.update(map1, players) if result == 1: players[0].isDead = True elif result == 2: players[1].isDead = True gameBall.drawToScreen(screen) if players[0].isDead and players[1].isDead: return run(displayInfo, (p1Score, p2Score), char1, char2, mapNum, Colors.YELLOW, Colors.YELLOW, boNum) elif players[0].isDead: char1.playDeathOn(noiseChannel) if p2Score + 1 < (boNum + 1) / 2: return run(displayInfo, (p1Score, p2Score + 1), char1, char2, boNum) else: print('p2 won') return 5 elif players[1].isDead: char2.playDeathOn(noiseChannel) if p1Score + 1 < (boNum + 1) / 2: return run(displayInfo, (p1Score + 1, p2Score), char1, char2, boNum) else: print('p1 won') return 4 # Updates screen frames += 1 if frames > minFrames: currentPerc = min(((frames - minFrames) / maxFrames), maxPerc) # minX, maxX, minY, maxY = closeInMap(map1, currentPerc) #borderInfo = closeInMap(screen, currentPerc) screen.blit(p1DispScore, (0, 0)) screen.blit(p2DispScore, (screenW - p2DispScore.get_width(), 0)) pygame.display.update() clock.tick(60) mouseClick = False # Exit code for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: mouseClick = True if event.type == pygame.QUIT or pygame.key.get_pressed( )[27]: # key 27 is escape inGameplay = False return -1