def start(self): pygame.init() pygame.joystick.init() self.font = pygame.font.Font(None, 24) self.running = True self.initDisplay() self.table = Table() self.consoleThread = Thread(target=self.startInteractiveShell) self.consoleThread.setDaemon(True) self.consoleThread.start() time.sleep(0.1) self.loop()
def __init__(self): self.scroll = 0 self.player = Player(WIN_WIDTH / 2, 360) self.items = [Chest(WIN_WIDTH / 2 + 540, 310, 'images/case.png', "Сейф 1", 320 // 4, 240 // 3), Picture(WIN_WIDTH / 2 - 150, 240, 'images/picture.png', "Картина", 320 // 4, 240 // 3), Books(WIN_WIDTH / 2 + 200, 300, 'images/books.png', "Книги",320 // 2, 240 // 2), Jail(WIN_WIDTH / 2 + 750, 269, 'images/jail.png', "Заключенный", 320, 240), Table(WIN_WIDTH / 2 - 300, 300, 'images/table.png', "Стол", 320 // 2, 240 // 2)] self.dialog = Dialog("- Добро пожаловать в мир твоих самых страшных кошмаров, жалкий офисный червяк.") self.left = self.right = self.up = self.down = False
def __init__(self, game): super().__init__(game) self.table = Table(game) self.gomenu = False self.objects.append( ButtonObject(self.game, self.game.width - 150, self.game.height - 100, 100, 50, RED, self.go_menu, text='MENU')) self.text = TextObject(self.game, self.game.width // 2, self.game.height // 5, self.get_gameover_text_formatted(), (255, 255, 255)) self.objects.append(self.text) self.objects.append(self.table)
class Application: def __init__(self): self.running = True self.mousePos = (1, 1) self.ai = AirHockeyAI() """ Initializes the appropriate stuff. Starts the main loop. """ def start(self): pygame.init() pygame.joystick.init() self.font = pygame.font.Font(None, 24) self.running = True self.initDisplay() self.table = Table() self.consoleThread = Thread(target=self.startInteractiveShell) self.consoleThread.setDaemon(True) self.consoleThread.start() time.sleep(0.1) self.loop() """ Starts interactive console. ai variable avaliable from console. """ def startInteractiveShell(self): vars = globals() ai = self.ai self.rect1 = Rect(Point(0, 0), Point(100, 100)) self.rect2 = Rect(Point(50, 50), Point(150, 150)) rect1 = self.rect1 rect2 = self.rect2 vars.update(locals()) shell = InteractiveConsole(vars) shell.interact() """ See self.loop comment """ def stop(self): self.running = False """ Initializes the display with the appropriate screen resolution Called in self.start """ def initDisplay(self): self.surface = pygame.display.set_mode(SCREEN_RESOLUTION) pygame.display.set_caption('Air Hockey Robot Simulation') """ Main Loop Loops until self.running == false """ def loop(self): while self.running: self.handleEvents() #Handles events self.surface.fill((0, 0, 0)) #Fills display with white #self.drawQuadrants() #self.drawArmAndMallet() #self.drawAngleValues() #self.rect1.draw(self.surface) #self.rect2.draw(self.surface) self.table.tick() surf = self.scaleSurface(self.table.draw()) self.surface.blit(surf, (BORDER_SIZE*SCALE, BORDER_SIZE*SCALE)) pygame.display.flip() #Draws display buffer to display """ Quitting procedure. """ pygame.quit() sys.exit(0) def scaleSurface(self, surf): surf = pygame.transform.scale(surf, (int(surf.get_width()*SCALE), int(surf.get_height()*SCALE))) surf = pygame.transform.flip(surf, False, True) return surf """ Handles pygame events. """ def handleEvents(self): events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.stop() elif event.type == pygame.MOUSEMOTION: self.mousePos = event.dict["pos"] elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.stop() def polarToCartesian(self, length, angle): x = length * math.cos(math.radians(angle)) y = length * math.sin(math.radians(angle)) return(x, y) def drawArmAndMallet(self): base = (0, 0) target = fromPygame(self.mousePos) """Gets angle to the midarm""" self.globalBaseAngle = self.ai.getBaseAngle(target) """Gets angle to the end arm""" self.globalMidArmAngle = self.ai.getMidArmAngle(target) """ Handle Servo controls """ self.lowerArm.set(self.globalBaseAngle) self.upperArm.set(self.globalMidArmAngle) """Deals with the coordinate mid arm""" midArm = self.polarToCartesian(self.ai.upperArmLength, self.globalBaseAngle) """ Deals with the coordinate for the end of the arm: essentially mathematical version of target""" cart = self.polarToCartesian(self.ai.lowerArmLength, self.globalMidArmAngle) endArm = midArm[0]+cart[0], midArm[1]+cart[1] pygame.draw.circle(self.surface, (255,0,0), (int(toPygame(endArm)[0]), int(toPygame(endArm)[1])), 20) pygame.draw.line(self.surface, (0, 255, 255), toPygame(base), toPygame(midArm), 3) pygame.draw.line(self.surface, (0, 255, 0), toPygame(midArm), toPygame(endArm), 3) def drawQuadrants(self): pygame.draw.line(self.surface, (255, 0, 0), (0, SCREEN_RESOLUTION[1]/2), (SCREEN_RESOLUTION[0], SCREEN_RESOLUTION[1]/2)) pygame.draw.line(self.surface, (255, 0, 0), (SCREEN_RESOLUTION[0]/2, 0), (SCREEN_RESOLUTION[0]/2, SCREEN_RESOLUTION[1])) def drawAngleValues(self): baseAngle = self.globalBaseAngle midArmAngle = self.globalMidArmAngle baseAngleText = self.font.render("Base Servo Angle: " + str(baseAngle), True, (255,255,255)) baseAngleTextBox = baseAngleText.get_rect() baseAngleTextBox.centerx = self.surface.get_rect().centerx self.surface.blit(baseAngleText, baseAngleTextBox) midAngleText = self.font.render("Elbow Servo Angle: " + str(midArmAngle - baseAngle + 360), True, (255,255,255)) midAngleTextBox = midAngleText.get_rect() midAngleTextBox.centerx = self.surface.get_rect().centerx midAngleTextBox.centery += 30 self.surface.blit(midAngleText, midAngleTextBox) targetText = self.font.render("Target Pos: " + str(fromPygame(self.mousePos)), True, (255,255,255)) targetTextBox = targetText.get_rect() targetTextBox.centerx = self.surface.get_rect().centerx targetTextBox.centery += 60 self.surface.blit(targetText, targetTextBox) def toPygame(self, pos): return toPygame(pos)
def current_table(self): return Table.by_index(self.cursor)
class VocCreationPanel(Panel): disable_delay = 120 reset_delay_on_interact = False delete_on_disable = True delete_delay_on_disable = 20 one_per_user = True tracked_keys = ['money'] mapping = { '🔼': { 'callback': 'go_up' }, '🟩': { 'callback': 'accept' }, '🟥': { 'callback': 'refuse' }, '🔽': { 'callback': 'go_down' }, } base_buttons = ['🔼', '🟩', '🟥', '🔽'] table_list = [table() for table in Table.tables()] cursor = 0 # used for table selection state = 'selection' # creating, to_slow, leave, refuse finished = False timeout_time = 120 # time before kick you for too long kick_time = 120 # for how much time you should be kick from the voc delete_delay = 15 # time before deleting finished panels @property def voice_channel(self): return self.module.voice_channel @property def current_table(self): return Table.by_index(self.cursor) def embed(self): method = getattr(self, f'{self.state}_embed') return method() def selection_embed(self): embed = discord.Embed( title=narr('voc.creation.title').format( name=self.user.display_name), colour=discord.Colour.blurple(), ) embed.description = f"{narr('voc.creation.desc')}\n\n{self.table_selector()}" table_name, table_desc = self.table_info() embed.add_field(name=table_name, value=table_desc, inline=False) return embed def creating_embed(self): return discord.Embed(title=narr('voc.creation.title').format( name=self.user.display_name), colour=discord.Colour.blurple(), description=narr('voc.creation.creating_desc')) def to_slow_embed(self): return discord.Embed(title=narr('voc.creation.title').format( name=self.user.display_name), colour=discord.Colour.blurple(), description=narr('voc.creation.to_slow_desc')) def leave_embed(self): return discord.Embed(title=narr('voc.creation.title').format( name=self.user.display_name), colour=discord.Colour.blurple(), description=narr('voc.creation.leave_desc')) def refuse_embed(self): return discord.Embed(title=narr('voc.creation.title').format( name=self.user.display_name), colour=discord.Colour.blurple(), description=narr('voc.creation.refuse_desc')) def table_selector(self): out = '' for table in self.table_list: prefix = '◆' if (table.index == self.cursor) else '◇' can_afford = '🟢' if table.can_afford(self.user, self.module) else '🔴' out += f'{prefix} {table.prefix}┃{table.display_name} - {can_afford}\n' return out def table_info(self): """Return a tuple with selected table name and desc""" table = self.current_table desc = table.description desc += '\n\n' # desc += f"{narr('price')} : {table.price}{self.get_emoji('money')}\n" desc += f"{narr('voc.creation.max_size')} : {table.max_size if (table.max_size is not None) else '∞'}\n" desc += f"{narr('voc.creation.allowed_roles')} : " if table.allowed_roles is not None: roles_names = [ self.module.guild.get_role(role_id).mention for role_id in table.allowed_roles ] desc += f"{', '.join(roles_names)}\n" else: desc += f"{narr('voc.creation.everyone')}\n" if table.stats_modifier is not None: title = f"\n{narr('voc.creation.buff_title')} : " add_stats = "\n".join([ f" ▹{narr(f'stats.{stat}')} +{value}" for stat, value in table.stats_modifier.get('add', {}).items() ]) mult_stats = "\n".join([ f" ▹{narr(f'stats.{stat}')} +{value*100}%" for stat, value in table.stats_modifier.get('mult', {}).items() ]) desc += f"{title}\n{add_stats}\n{mult_stats}\n" return ( f"{table.prefix}┃{table.display_name} [ {table.price}{self.get_emoji('money')} ]", desc) async def go_up(self): self.cursor = 0 if ((self.cursor - 1) < 0) else (self.cursor - 1) await self.render() async def go_down(self): self.cursor = (self.cursor + 1) % len(self.table_list) await self.render() async def accept(self): table = self.current_table try: table.can_afford_err(self.user, self.module) except NoRoleException: self.temp_notif = narr('voc.creation.no_role_err') await self.render() except NoMoneyException: self.temp_notif = narr('voc.creation.no_money_err') await self.render() else: self.state = 'creating' await self.disable(delete=True, delay=20) await self.good_end() async def refuse(self): self.state = 'refuse' await self.disable(delete=True, delay=20) await self.bad_end() async def leave(self): self.state = 'leave' await self.disable(delete=True, delay=20) await self.bad_end() async def good_end(self): table = self.current_table await self.module.api.add_money(self.user, -table.price) table_channel = await TableChannel.create(table.index, self.user, self.module) self.module.tables.append(table_channel) async def bad_end(self): if self.user in self.voice_channel.members: await self.module.shared_move_user(self.user, None) await self.deny_create() self.module.loop.create_task(self.allow_create()) async def auto_disable(self): """Called automaticaly when user take to much time""" self.state = 'to_slow' await self.bad_end() async def deny_create(self): overwrites = self.voice_channel.overwrites user_perm = discord.PermissionOverwrite(connect=False) overwrites[self.user] = user_perm await self.module.shared_edit_channel(self.voice_channel, overwrites=overwrites) async def allow_create(self): """Wait for the delay then allop again to join""" await asyncio.sleep(self.kick_time) overwrites = self.voice_channel.overwrites perm = overwrites.pop(self.user, None) if perm is not None: await self.module.shared_edit_channel(self.voice_channel, overwrites=overwrites)