class BattleTargeting(PlayUI): def __init__(self, cardN, cardPos): self.arrow = Arrow(Vector(*pygame.mouse.get_pos())) self.cardN = cardN self.cardPos = cardPos self.arrow.set_destination(cardPos) def draw(self, game): drawBattleScreen(self, game, kwargs={"skips": [self.cardN]}) game.renderer.draw(game.surface, self.cardPos, game.state.hand[self.cardN]) self.arrow.draw(game.surface) def input(self, game, event): self.arrow.set_destination(Vector(*pygame.mouse.get_pos())) hitboxes = self.findHitboxes() targets = self.findTargets(game) if event.type == MOUSEBUTTONUP and event.button == 1: for i in range(len(hitboxes)): if pygame.rect.Rect((hitboxes[i])).collidepoint(*event.pos): self.tryPlayCard(game, targets[i]) break else: game.nextUI = BattleIdle()
def menu(window, clock): arrow_right = Arrow("right", window.get_size()) arrow_left = Arrow("left", window.get_size()) loop = True while loop: for event in pygame.event.get(): if event.type == QUIT: loop = False if event.type == KEYDOWN: if event.key == K_ESCAPE: loop = False if event.key == K_RIGHT: print "right" arrow_right.big = True if event.key == K_LEFT: print "left" arrow_left.big = True window.fill((30,130,184)) arrow_right.draw(window) arrow_left.draw(window) pygame.display.flip() clock.tick(30)
def main(): pygame.init() clock = pygame.time.Clock() board = CreateEmptyBoard() FillBoard(board, COLORS) launchBall = False ball = getBubble(COLORS) ball.rect.centerx = STARTX nextBall = getBubble(COLORS) # board[0][15] = copy.deepcopy(ball) # setPosition(board) arrow = Arrow() while 1: # main game loop display.fill(BEIGE) vector, angle = getVector() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: if not launchBall: ball.shoot(angle) launchBall = True if event.type == MOUSEMOTION: arrow.update(angle, vector) drawBoard(board) nextBall.draw() if ball is not None: ball.update() ball.draw() #print(ball.rect.centerx, ball.rect.centery) ball, board, checkwin = stopBubble(board, ball) else: launchBall = False ball = Bubble(nextBall.color) nextBall = getBubble(COLORS) arrow.draw() if checkwin: return 1 elif checkBottom(board) == False: return 2 pygame.display.update() clock.tick(FPS)
class TheGame: """Make an object that runs the simulation. """ def __init__(self): """Initiate all instances of the classes that are needed for the simulation, and start PyGame. Raises: Exception: If you fail to choose a valid simulation setting, an Exception is raised. """ while True: try: string = str( input('Do you want to take in live GNSS-signals? (y/n)\t')) if string in ('y', 'yes'): self.test_mode_on = False try: self.gps = serial.Serial('/dev/ttyACM0', baudrate=9600) except Exception: print( "The port cannot be opened. Check that your unit is connected to the port you're opening." ) exit() elif string in ('n', 'no'): self.test_mode_on = True else: raise Exception except Exception: print('Please type "y" or "n".') else: break self.clock = pg.time.Clock() self.the_arrow = Arrow() self.map = Map(60.75, 11.99) self.the_text = Text() self.earth = Geodesic(cf.R_E, 0) self.out_q = mp.Manager().Value('i', [0.0, 0.0]) self.NS = self.map.center_y self.EW = self.map.center_x self.the_background = pg.image.load('background.jpg') self.process = False self.background = False self.dot_x, self.dot_y = self.the_arrow.two_d_pos.x, self.the_arrow.two_d_pos.y self.pastNS, self.pastEW = self.NS, self.EW # Create a new log file for this session. with open("log.txt", "w") as log: log.write("") try: what_os = platform.system() if what_os == 'Linux': self.g_earth = subprocess.Popen('google-earth-pro') elif what_os == 'Darwin': subprocess.call([ "/usr/bin/open", "-n", "-a", "/Applications/Google Earth Pro.app" ]) except Exception: pass # Wait for Google Earth Pro to open so that the PyGame window opens as the top layer. time.sleep(5) pg.init() pg.display.set_caption("Real time spoofer") self.screen = pg.display.set_mode((cf.SCREEN_WIDTH, cf.SCREEN_HEIGHT)) def events(self): """Event handling. """ for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: self.logging() pg.quit() quit() if event.type == pg.QUIT: self.logging() pg.quit() quit() pressed = pg.key.get_pressed() if pressed[pg.K_LEFT]: # LEFT rotates 'dir' to the left. 'TURNING' given in degrees. self.the_arrow.dir = self.the_arrow.dir.rotate( -cf.TURNING).normalized() if pressed[pg.K_RIGHT]: # RIGHT rotates 'dir' to the right. 'TURNING' given in degrees. self.the_arrow.dir = self.the_arrow.dir.rotate( cf.TURNING).normalized() if pressed[pg.K_UP] and self.the_arrow.vel < cf.MAX_VEL: # UP increases the speed. self.the_arrow.vel += cf.AXELERATION if pressed[pg.K_DOWN] and self.the_arrow.vel > -cf.MAX_VEL: # DOWN decreases the speed and let you move backwards. self.the_arrow.vel -= cf.AXELERATION if not pressed[pg.K_UP] and self.the_arrow.vel >= 0.0: # When you release the "throttle" (UP), you slowly go to a stop, # but as long as you have some speed, 'two_d_pos' should be updated. self.the_arrow.vel -= cf.GLIDING if not pressed[pg.K_DOWN] and self.the_arrow.vel <= 0.0: self.the_arrow.vel += cf.GLIDING @staticmethod def logging(): """Make a path on a map consisting of the coordinates created during the spoofing. """ logger = [] c = [] with open("log.txt", "r") as log: the_log = log.readlines() # Remove the '\n' (newlines) from the string. the_log = [x.strip() for x in the_log] # Need to put every odd item in first position of a list (latitudes), # and every other item in the second position of a list (longitudes). for b in the_log: if len(c) < 2: c.append(float(b)) else: logger.append(c) c = [] c.append(float(b)) try: mapp = folium.Map(location=logger[0], zoom_start=10) folium.Marker(logger[0], popup='<i>Mt. Hood Meadows</i>', tooltip='Start').add_to(mapp) folium.Marker(logger[-1], popup='<i>Mt. Hood Meadows</i>', tooltip='Slutt').add_to(mapp) folium.vector_layers.PolyLine(logger).add_to(mapp) mapp.save(outfile="log.html") except Exception: print('No logged coordinates to use.') def test_mode(self): """With test mode, you do not check with the receiver what coordinates its got, you just move from the static starting position. """ with open("position.txt", "w") as pos: pos.write("%s\n%s\n" % (str(self.NS), str(self.EW))) with open("position.kml", "w") as kml: kml.write("""<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Placemark> <name>Spoofer Position</name> <description>Track a spoofed GNSS-position</description> <Point> <coordinates>%s,%s,0</coordinates> </Point> </Placemark> </kml> """ % (str(self.EW), str(self.NS))) with open("log.txt", "a") as log: log.write("%s\n%s\n" % (str(self.NS), str(self.EW))) def check_coordinates(self, out_q): """Check GPS/GLONASS-coordinates from the receiver, add the off-set and write it to a file. """ line = self.gps.readline().decode("utf-8") data = line.split(',') if data[0] == "$GNRMC": if data[2] == "A": print("3D fix.", end='\r') with open("position.txt", "w") as pos: # Convert from XXYY.YY... (X: degree, Y: decimal minute) to decimal degree (XX.XX...). DDM_NS = float(data[3]) / 100 DDM_EW = float(data[5]) / 100 # Remove the decimals and then add them again, scaled up correctly. DD_NS = DDM_NS - DDM_NS % 1 + \ (DDM_NS % 1) / 60 * 100 DD_EW = DDM_EW - DDM_EW % 1 + \ (DDM_EW % 1) / 60 * 100 # North in the negative y-direction. NS, EW = DD_NS - self.the_arrow.two_d_pos.y, \ DD_EW + self.the_arrow.two_d_pos.x pos.write("%s\n%s\n" % (str(NS), str(EW))) out_q.value = [NS, EW] # Write a kml-file with the spoofing position. with open("position.kml", "w") as kml: kml.write("""<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Placemark> <name>Spoofer Position</name> <description>Track a spoofed GNSS-position</description> <Point> <coordinates>%s,%s,0</coordinates> </Point> </Placemark> </kml> """ % (str(EW), str(NS))) # Write a log file that can be evaluated after finishing the program. with open("log.txt", "a") as log: log.write("%s\n%s\n" % (str(NS), str(EW))) elif data[2] == "V": print("No fix.", end='\r') def parallel_coordinates(self): """Allow check of coordinates to be done in parallel with the controlling of the arrow, such that updating the coordinates does not interfere and stop the rest of the program. """ if not self.process: # If no process exists, make one and start it off. self.process = mp.Process(target=self.check_coordinates, args=(self.out_q, )) self.process.start() else: try: self.process.start() except Exception: pass if not self.process.is_alive(): # If the process is done, it can be closed/joined to allow a # new one to be opened in the next round of the loop. # Before it is closed, the values returned by 'check_coordinates()' are captured. a = self.out_q self.NS = a.value[0] self.EW = a.value[1] self.process.join() self.process = False def parallel_background(self): """Allow the background that is blitted to the PyGame surface to be updated without interfering and stopping the rest of the program. """ # Make the background update only when you approach the edge of the screen. if (self.pastNS + cf.BOARDER_Y * 0.8) < self.NS or self.NS < (self.pastNS - cf.BOARDER_Y * 0.8) or \ (self.pastEW + cf.BOARDER_X * 0.8) < self.EW or self.EW < (self.pastEW - cf.BOARDER_X * 0.8): if not self.background: # If no process of updating the # background is running, start one now. self.background = mp.Process(target=self.map.map_update, args=(self.NS, self.EW)) self.background.start() else: try: self.background.start() except Exception: pass try: if not self.background.is_alive(): # When the background is updated, reset the dot to the center. self.background.join() self.background = False self.dot_x = self.dot_y = 0 self.pastNS = self.NS self.pastEW = self.EW except Exception: pass def draw_dot(self): """Draw a dot representing the spoofing signal. """ # Need to scale the point according to the # geographical position of the background map. x_ratio = 2 * cf.BOARDER_X / cf.SCREEN_WIDTH y_ratio = 2 * cf.BOARDER_Y / cf.SCREEN_HEIGHT x = int(self.dot_x / x_ratio + cf.SCREEN_WIDTH / 2) y = int(self.dot_y / y_ratio + cf.SCREEN_HEIGHT / 2) pg.draw.circle(self.screen, cf.DOT_COLOR, (x, y), cf.DOT_SIZE, cf.DOT_FILLED) def game_loop(self): """Loop that runs the simulation and calls all methods. """ while 1: self.events() self.NS, self.EW, self.dot_y, self.dot_x = self.the_arrow.globe_motion( self.earth, self.NS, self.EW, self.dot_y, self.dot_x) if self.test_mode_on: self.test_mode() else: self.parallel_coordinates() self.parallel_background() # Prevent irrelevant error from printing to bash. sys.stdout = open(os.devnull, "w") if os.path.exists('background.jpg'): try: self.the_background = pg.image.load('background.jpg') except Exception: pass # Redirect printing back to bash. sys.stdout = sys.__stdout__ self.screen.fill(cf.BLACK) self.screen.blit(self.the_background, (0, 0)) self.the_arrow.draw(self.screen) self.the_text.text_update(self.the_arrow.vel, self.screen) self.draw_dot() pg.display.update() self.clock.tick(cf.FPS)
def scnene_game( gameDisplay ): # create game object # map play_map = GameMap(res.position_game_map, res.size_game_map, res.color_map, res.size_grid, res.game_map_grids, res.width_game_map_wall, res.color_wall) play_map.kit_reset( res.kit_max, res.kit_freq ) play_map.kit_gen() play_map.kit_gen() # player arrow arrow_p1 = Arrow(res.size_arrow, play_map.grid_center(res.grid_position_start_p1), (1,0), 2, res.speed_max, res.color_p1) arrow_p2 = Arrow(res.size_arrow, play_map.grid_center(res.grid_position_start_p2), (-1,0), 2, res.speed_max, res.color_p2) # player panel bar_p1 = PowerBar( res.position_panel_p1+res.size_panel_p1, res.speed_max, res.color_p1, (0,0,0) ) bar_p2 = PowerBar( res.position_panel_p2+res.size_panel_p2, res.speed_max, res.color_p2, (0,0,0) ) panel_p1 = PlayerPanel( res.position_panel_p1, res.size_panel_p1, res.color_p1 ) panel_p1.set_item_slot( res.slot_layout ) panel_p1.set_player( arrow_p1 ) panel_p1.set_power_bar( bar_p1 ) panel_p2 = PlayerPanel( res.position_panel_p2, res.size_panel_p2, res.color_p2 ) panel_p2.set_item_slot( res.slot_layout ) panel_p2.set_player( arrow_p2 ) panel_p2.set_power_bar( bar_p2 ) # add object to game gameArrowList = [] gameArrowList.append( ArrowInGame(arrow_p1) ) gameArrowList.append( ArrowInGame(arrow_p2) ) for gameArrow in gameArrowList: gameArrow.set_grid_position( play_map.detect_grid(gameArrow.arrow.position) ) # register key done event key_control = { res.control_p1['right']:lambda :game_map_turn_correct(arrow_p1, play_map, (1,0)), res.control_p1['left']: lambda :game_map_turn_correct(arrow_p1, play_map, (-1,0)), res.control_p1['up']: lambda :game_map_turn_correct(arrow_p1, play_map, (0,-1)), res.control_p1['down']: lambda :game_map_turn_correct(arrow_p1, play_map, (0,1)), res.control_p1['kit']: lambda :arrow_p1.kit_invoke(), res.control_p2['right']:lambda :game_map_turn_correct(arrow_p2, play_map, (1,0)), res.control_p2['left']: lambda :game_map_turn_correct(arrow_p2, play_map, (-1,0)), res.control_p2['up']: lambda :game_map_turn_correct(arrow_p2, play_map, (0,-1)), res.control_p2['down']: lambda :game_map_turn_correct(arrow_p2, play_map, (0,1)), res.control_p2['kit']: lambda :arrow_p2.kit_invoke() } game_over = False while not game_over: # handle event for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: for key in key_control: if key == event.key: key_control[key]() # print(event) # raise game event if (game_arrow_encounter(arrow_p1, arrow_p2) == res.game_brokeback): return True game_arrow_map_event( gameArrowList, play_map ) # progress game play_map.kit_progress() arrow_p1.progress() game_map_bump_correct( arrow_p1, play_map ) arrow_p2.progress() game_map_bump_correct( arrow_p2, play_map ) # render gameDisplay.fill(res.color_background) play_map.draw( gameDisplay ) panel_p1.draw( gameDisplay ) panel_p2.draw( gameDisplay ) arrow_p1.draw( gameDisplay ) arrow_p2.draw( gameDisplay ) pygame.display.update() res.clock.tick( res.tick_game )