from eventStuff import EventHandler CONST_WINDOW_WIDTH = 1200 CONST_WINDOW_LENGTH = 800 LT_CORNER = (0, 0) RT_CORNER = (800, 0) LB_CORNER = (0, 1200) RB_CORNER = (800, 1200) load = Load() truck = Truck(240, 100, 3) eventHandler = EventHandler() count = 0 num = 0 ux_load = Button("Load an Order", 1000, 200) def ux_loadClickEvent(): global count global num count += 1 print(count) num = load.count_number_of_orders("test_docs/test_doc_1.txt") load.read_in_load("test_docs/test_doc_1.txt", num) print(load.entire_load) eventHandler.registerButton(ux_load, ux_loadClickEvent) ux_simulate = Button("Simulate a Load", 1000, 300)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # players p1 = Player(30, 270, 20, 100) p2 = Player(850, 270, 20, 100) # range for collision range1 = pd.Interval(p1.y, p1.y + 100) range2 = pd.Interval(p2.y, p2.y + 100) # colors color_p1 = (255, 255, 255) color_p2 = (255, 255, 255) # buttons to change color button_red_p1 = Button((10, 490), (100, 100)) button_green_p1 = Button((120, 490), (100, 100)) button_blue_p1 = Button((230, 490), (100, 100)) button_red_p2 = Button((570, 490), (100, 100)) button_green_p2 = Button((680, 490), (100, 100)) button_blue_p2 = Button((790, 490), (100, 100)) # ball ball = Ball(100, 100, 10, 10) # middle line middle_line = Player(450, 0, 1, 600) # booleans for program control menu = True running = False
def __init__(self): self.win = win = GraphWin("Wimbledon Final", 600, 300, autoflush = "False") win.setCoords(0, 100, 100, 0) win.setBackground(color_rgb(0 , 80 , 0)) textData = [ (Point(50, 5), "Final", "white", 24), (Point(50, 15), "Rolex", "gold", 18), (Point(13, 30), "PREVIOUS SETS", "white", 10), (Point(78, 30), "SETS", "white", 10), (Point(86.5, 30), "GAMES", "white", 10), (Point(96, 30), "POINTS", "white", 10), (Point(50, 52), "v", "gold", 17)] textBoxes = [] for p, text, colour, size in textData: textBox = Text(p, text) textBox.setFill(colour) textBox.setSize(size) textBoxes.append(textBox) textBoxes[-1].draw(self.win) entryData = [ (Point(15,15), 5, "19:15", color_rgb (40 , 40 , 40 ), 20, "gold"), (Point(85,15), 5, "3.35", color_rgb (40 , 40 , 40 ), 20, "gold") ] entryBoxes = [] for p, length, text, fill, size, colour in entryData: entryBox = Entry(p, length) entryBox.setText(text) entryBox.setFill(fill) entryBox.setSize(size) entryBox.setTextColor(colour) entryBoxes.append(entryBox) entryBoxes[-1].draw(self.win) Strip = Line(Point(0, 23), Point(100, 23)) Strip.setWidth(4) Strip.setFill("purple") Strip.draw(win) rectangleData = [(Point(2, 48), Point(7, 36)), (Point(8, 48), Point(13, 36)), (Point(14, 48), Point(19, 36)), (Point(20, 48), Point(25, 36)), (Point(2, 68), Point(7, 56)), (Point(8, 68), Point(13, 56)), (Point(14, 68), Point(19, 56)), (Point(20, 68), Point(25, 56)), (Point(8, 48), Point(13, 36)), (Point(27, 48), Point(73, 36)), (Point(27, 68), Point(73, 56)), (Point(75, 48), Point(81, 36)), (Point(83, 48), Point(90, 36)), (Point(92, 48), Point(99, 36)), (Point(75, 68), Point(81, 56)), (Point(83, 68), Point(90, 56)), (Point(92, 68), Point(99, 56)) ] rectangles = [] for p1, p2 in rectangleData: rectangle = Rectangle(p1, p2) rectangle.setFill(color_rgb(40, 40, 40)) rectangles.append(rectangle) rectangles[-1].draw(self.win) self.Player1 = Text(Point(50, 42), "") self.Player2 = Text(Point(50, 62), "") for i in [self.Player1, self.Player2]: i.setFill("gold") i.setSize(22) i.draw(self.win) self.player1Set1 = Text(Point(4.5, 42), "") self.player1Set2 = Text(Point(10.5, 42), "") self.player1Set3 = Text(Point(16.5, 42), "") self.player1Set4 = Text(Point(22.5, 42), "") self.player2Set1 = Text(Point(4.5, 62), "") self.player2Set2 = Text(Point(10.5, 62), "") self.player2Set3 = Text(Point(16.5, 62), "") self.player2Set4 = Text(Point(22.5, 62), "") self.player1Sets = Text(Point(78, 42), "") self.player1Games = Text(Point(86.5, 42), "") self.player1Points = Text(Point(95.5, 42), "") self.player2Sets = Text(Point(78, 62), "") self.player2Games = Text(Point(86.5, 62), "") self.player2Points = Text(Point(95.5, 62), "") for i in [self.player1Set1, self.player1Set2, self.player1Set3, self.player1Set4, self.player2Set1, self.player2Set2, self.player2Set3, self.player2Set4, self.player1Sets, self.player1Games, self.player1Points, self.player2Sets, self.player2Games, self.player2Points]: i.setFill("gold") i.setSize(20) i.draw(self.win) self.player1Tiebreak1 = Text(Point(4.5, 51), "") self.player1Tiebreak2 = Text(Point(10.5, 51), "") self.player1Tiebreak3 = Text(Point(16.5, 51), "") self.player1Tiebreak4 = Text(Point(22.5, 51), "") self.player2Tiebreak1 = Text(Point(4.5, 71), "") self.player2Tiebreak2 = Text(Point(10.5, 71), "") self.player2Tiebreak3 = Text(Point(16.5, 71), "") self.player2Tiebreak4 = Text(Point(22.5, 71), "") for i in [self.player1Tiebreak1, self.player1Tiebreak2, self.player1Tiebreak3, self.player1Tiebreak4, self.player2Tiebreak1, self.player2Tiebreak2, self.player2Tiebreak3, self.player2Tiebreak4]: i.setFill("white") i.setSize(10) i.draw(self.win) self.player1Serving = Oval(Point(70, 40), Point(72,44)) self.player1Serving.setFill("gold") self.player2Serving = self.player1Serving.clone() self.player2Serving.move(0, 20) #Create buttons self.sim = Button(win, Point(14, 78), 20, 10, "Sim Match") self.playPoint = Button(win, Point(38, 78), 20, 10, "Play Point") self.playGame = Button(win, Point(38, 93), 20, 10, "Play Game") self.playSet = Button(win, Point(62, 78), 20, 10, "Play Set") self.playMatch = Button(win, Point(62, 93), 20, 10, "Play Match") self.stopSim = Button(win, Point(86, 85.5), 20, 10, "Stop Sim") self.Exit = Button(win, Point(14, 93), 20, 10, "Quit") self.buttonChoice = None
def run_game(user): '''运行游戏''' global id id = user game_settings = Setting() stats = GameStats() pygame.init() screen = pygame.display.set_mode((game_settings.screen_width,game_settings.screen_height)) pygame.display.set_caption("Gomoku") pygame.mixer.music.set_volume(0.4) FPS = 50 clock = pygame.time.Clock() play_button = Button(screen,"Start",(70,640)) # vshuman_button = Button(screen,"Double",(160,640)) reset_button = Button(screen,"Reset",(160,640)) repent_button = Button(screen,"Repent",(250,640)) quit_button = Button(screen,"Quit",(570,640)) AI_button = Button(screen,"AI",(470,640)) '''初始化棋子序列和黑白棋盘''' movements = [] __white = np.zeros((15,15)) __black = np.zeros((15,15)) board = np.zeros((15,15)) flag = True running = True while running: # clock.tick(FPS) time.sleep(0.75) load_chessboard(screen) play_button.draw_button() # vshuman_button.draw_button() reset_button.draw_button() repent_button.draw_button() quit_button.draw_button() AI_button.draw_button() draw_movements(screen,movements) # pygame.display.flip() gf.print_text(screen,"Welcome",20,700,50,BLACK) gf.print_text(screen,user+"!",20,700,75,BLACK) gf.print_to_screen(stats,screen,flag) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: __white = np.zeros((15,15)) __black = np.zeros((15,15)) movements = [] flag = True pygame.event.set_blocked([1,4,pygame.KEYUP,pygame.JOYAXISMOTION,pygame.JOYBALLMOTION,pygame.JOYBUTTONDOWN,pygame.JOYBUTTONUP,pygame.JOYHATMOTION]) pygame.event.set_allowed([pygame.MOUSEBUTTONDOWN,pygame.MOUSEBUTTONUP,pygame.KEYDOWN]) break; if event.type == pygame.MOUSEBUTTONDOWN: m = event.pos[0] n = event.pos[1] if play_button.rect.collidepoint(m,n): stats.game_active = True if stats.win_stats == True: __white = np.zeros((15,15)) __black = np.zeros((15,15)) movements = [] flag = True stats.win_stats= False pygame.event.set_blocked([1,4,pygame.KEYUP,pygame.JOYAXISMOTION,pygame.JOYBALLMOTION,pygame.JOYBUTTONDOWN,pygame.JOYBUTTONUP,pygame.JOYHATMOTION]) pygame.event.set_allowed([pygame.MOUSEBUTTONDOWN,pygame.MOUSEBUTTONUP,pygame.KEYDOWN]) break if stats.game_active == True: if 20 < m <= 620 and 20 < n <= 620: x = round(m//40.0) y = round(n//40.0) if m % 40 <= 20: x = x - 1 if n % 40 <= 20: y = y - 1 flag = select_pos(screen,x,y,flag,__black,__white,movements,stats) if reset_button.rect.collidepoint(m,n): __white = np.zeros((15,15)) __black = np.zeros((15,15)) movements = [] flag = True stats.win_stats= False pygame.event.set_blocked([1,4,pygame.KEYUP,pygame.JOYAXISMOTION,pygame.JOYBALLMOTION,pygame.JOYBUTTONDOWN,pygame.JOYBUTTONUP,pygame.JOYHATMOTION]) pygame.event.set_allowed([pygame.MOUSEBUTTONDOWN,pygame.MOUSEBUTTONUP,pygame.KEYDOWN]) break if repent_button.rect.collidepoint(m,n): if len(movements) != 0: if flag: last_step = movements.pop() raw = last_step[0][0]//40-1 col = last_step[0][1]//40-1 __white[raw][col] = 0 __black[raw][col] = 0 flag = not flag elif flag == False: last_step = movements.pop() raw = last_step[0][0]//40-1 col = last_step[0][1]//40-1 __white[raw][col] = 0 __black[raw][col] = 0 flag = not flag else: pass if AI_button.rect.collidepoint(m,n): stats.ai_active = True "" if quit_button.rect.collidepoint(m,n): pygame.quit() sys.exit() play_button.draw_button() # vshuman_button.draw_button() reset_button.draw_button() repent_button.draw_button() quit_button.draw_button() AI_button.draw_button() draw_movements(screen,movements) pygame.display.flip() pygame.quit()
We'll use the Button class to create a Play button. Because we need only one Play button, we'll create the button directly in alien_invasion.py as shown here: """ # alien_invasion.py --snip-- from game import GameState from button import Button --snip-- pygame.display.set_caption("Alien Invasion") # Make the play button. play_button = Button(ai_settings, screen, "Play") --snip-- while True: --snip-- gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets, play_button) """ We import Button and create an instance called play_button(line 17), and then we pass play_button to update-screen() so the button appears when the screen updates (line 22). Next, modify update_screen() so the Play button appears only when the game is inactive: """ # game_functions.py
#buliding file_menu up = 1 down = 14 directory = os.path.abspath(os.curdir) file_menu = Menu(screen) file_menu.Rect = ((130, 50), (320, 500)) brx, bry, brl, brh = file_menu.Rect[0][0] + 10, file_menu.Rect[0][ 1] + 5, 300, 20 bsxd, bsyd = file_menu.Rect[0][0] + 10, file_menu.Rect[1][1] + file_menu.Rect[ 0][1] - 25 bsld, bshd = 300, 20 bsxu, bsyu = file_menu.Rect[0][0] + 10, file_menu.Rect[0][1] + 30 bslu, bshu = 300, 20 button_return = Button(screen, brx, bry, brl, brh, (BLACK, WHITE), '. . .', 5) button_scrolld = Button(screen, bsxd, bsyd, bsld, bshd, (GREEN, BLACK), 'SCROLL DOWN', 5) button_scrollu = Button(screen, bsxu, bsyu, bslu, bshu, (GREEN, BLACK), 'SCROLL UP', 5) buttons = get_files(directory, file_menu, up, down) file_menu.add_buttons(buttons) directory = shape(directory) open_file = '' save_file = '' save_menu = False open_menu = False #building hard_drive_menu hard_drive_menu = Menu(screen) ml = 80
def run_game(): # Initialize game and create a screen object. pygame.init() # The line pygame.init() initializes background settings that Pygame needs to work properly. screen=pygame.display.set_mode((1200,800)) #we have used 1200,800 in game_functions.py in number_aliens_x and number_rows methods # here,we call pygame.display.set_mode() to create a display window called #screen(object), on which we’ll draw all of the game’s graphical elements. #The argument (1200, 800) is a tuple that defines the dimensions of the game window. 1200 wide and 800 high #The screen object is called a surface. #A surface in Pygame is a part of the screen where you display a game element. #When we activate the game’s animation loop, #this surface is automatically redrawn on every pass through the loop. pygame.display.set_caption("ALIEN INVASION") bg_color = (230, 230, 230) ai_settings=settings.Settings() play_button=Button(ai_settings,screen,"Go") stats = GameStats(ai_settings) #We import Ship and then make an instance of Ship (named ship) after the screen has been created. ship=Ship(ai_settings.ship_speed_factor,screen) #here,we make an instance of Group and call it bullets. bullets=Group() alien =Alien(ai_settings,screen) aliens=Group() sb=Scoreboard(ai_settings,screen,stats) #######################bullets2=Bullet(ai_settings,screen,ship) gf.create_fleet(ai_settings,screen,ship,aliens) # Start the main loop for the game. #The game is controlled by a while loop that contains an event loop and code that manages screen updates. # An event is an action that the user performs while playing the game, #such as pressing a key or moving the mouse. while True: # Watch for keyboard and mouse events. #To make our program respond to events, we’ll write an event(for)loop to #listen for an event and perform an appropriate task depending on the kind of event that occurred. for event in pygame.event.get(): if event.type==pygame.QUIT: with open("score.json",'w') as file: json.dump(stats.high_score,file) sys.exit() elif event.type==pygame.KEYDOWN: #Each keypress is registered as a KEYDOWN event. if event.key==pygame.K_RIGHT: ship.moving_right=True elif event.key==pygame.K_LEFT: ship.moving_left=True elif event.key==pygame.K_SPACE: # Create a new bullet and add it to the bullets group. #bullets2.shooting=True if len(bullets)<3: new_bullet=Bullet(ai_settings, screen, ship) bullets.add(new_bullet) elif event.type==pygame.KEYUP: if event.key==pygame.K_RIGHT: ship.moving_right=False elif event.key==pygame.K_LEFT: ship.moving_left=False #elif event.key==pygame.K_SPACE: #bullets2.shooting=False elif event.type==pygame.MOUSEBUTTONDOWN: mouse_x,mouse_y=pygame.mouse.get_pos() gf.check_play_button(sb,ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y) if stats.game_active: ship.update() #next code is to remove unnecessary bullets above the screen for bullet in bullets.copy(): if bullet.rect.bottom<=0: bullets.remove(bullet) #print(len(bullets)) #till here bullets.update() gf.update_bullet(sb,stats,ai_settings,screen,ship,aliens,bullets) gf.update_aliens(sb,ai_settings,stats,screen,ship,aliens,bullets) # Redraw the screen during each pass through the loop. screen.fill(bg_color) #We draw the ship onscreen by calling ship.blitme() after filling the background, #so the ship appears on top of the background ship.blitme() # Redraw all bullets behind ship and aliens. for bullet in bullets.sprites(): bullet.draw_bullet() # alien.blitme() aliens.draw(screen) # Make the most recently drawn screen visible. #draw the score info sb.show_score() if not stats.game_active: play_button.draw_button() pygame.display.flip()
def __init__(self, width, height): self.width = width # largeur de la fenêtre self.height = height # hauteur de la fenêtre background_image = pygame.image.load('grille_pain.jpg') # chargement de l'image de fond pygame.init() # lancement de pygame screen = pygame.display.set_mode((self.width, self.height)) # début de la fenêtre arière pygame.display.set_caption(' Bataille navale') # nommage de la fenêtre background_color = (245, 20, 230) # couleur de l'arrière plan rose pour repèrer artéfact graphique screen.fill(background_color) # remplissage de l'arrière plan avec la couleur sélectionnée def redraw_window(): # remplacement de la class Selection par cette variable screen.blit(background_image, (0, 0)) ship.rect_draw() pygame.display.update() i = 0 # varible compteur count = 0 # variable compteur iscomplete = False # état du posage des bateaux client_ship = [] # coordonnées des bateaux confondues ship_list = [('PA.png', 5), ('CR.png', 4), ('SM.png', 3), ('SM.png', 3), ('TP.png', 2)] # liste des bateaux et longueurs coord_list = [] # tuple temporaire running = True # mise en place de la boucle principale while running: pygame.time.delay(1) # délai d'action en milli secondes for event in pygame.event.get(): # détecteur d'évènement if event.type == pygame.QUIT: # condition pour quitter sans crasher le jeux running = False # ligne permettant de quitter sans crasher la fenêtre keys = pygame.key.get_pressed() # détection des touches angle = 0 # première définition de l'angle du bateau if not pygame.mouse.get_pressed()[0]: # condition pour poser un bateau ( clic gauche ) mouse = pygame.mouse.get_pos() # attribution des coordonnées x,y de la souris à la variable mouse x, y = mouse[0], mouse[1] # distribution des valeurs de la variable mouse à x, y else: pos_x, pos_y = int((x - 50) / 42), int((y - 53) / 44) # calcul de la case sur laquelle le bateau se trouve x, y = pos_x*42 + 50, pos_y*44 + 53 # "clippage" de l'image sur le quadrilage if keys[pygame.K_RETURN] and not iscomplete: # condition pour récuperer toutes les coordonnées d'un bateau ( ENTER ) if pygame.mouse.get_pos()[1] > y: # condition pour calculer les coordonnés si l'on veut placer le bateau verticalement for o in range((ship_list[i])[1]): # longueur du bateau en question prise 1:1 coord_temp = (pos_x, pos_y + o) # variable temporaire coord_list.append(coord_temp) # ajout de la variable temporaire à la tuple temporaire for p in coord_list: # détecteur de répétition avec les coordonnés du client for q in client_ship: if p == q: # condition d'égalité entre toutes coordonnés client et coordonnées entrée coord_list.clear() # si chevauchment de coordonnée alors effacer la coordonéé temporaire if len(coord_list) > 0: # si la coordonnée temporaire est différente en tout point de celles du client client_ship = client_ship + coord_list # somme des coordonnées client et celles temporaires del ship_list[i] # supression du bateau déjà placé de la liste des bateaux en attente count += 1 # compteur coord_list.clear() # suppresion de la tuple temporaire pygame.time.wait(125) # délai pour le comfort else: for o in range((ship_list[i])[1]): # même condition qu'à la ligne 53 mais, pour les bateaux horizontaux coord_temp = (pos_x + o, pos_y) coord_list.append(coord_temp) for p in coord_list: for q in client_ship: if p == q: coord_list.clear() if len(coord_list) > 0: client_ship = client_ship + coord_list del ship_list[i] count += 1 coord_list.clear() pygame.time.wait(125) pygame.time.wait(125) if pygame.mouse.get_pos()[1] > y and not iscomplete: # rotation verticale visuelle du bateau angle = 90 if keys[pygame.K_SPACE]: # condition pour changer de bateau pygame.time.wait(125) # délai pour éviter un défilement trop rapide i += 1 # variable compteur de l'emplacement dans la tuple if i > len(ship_list)-1: # condition pour revenir au premier revenir au premier bateau du tuple i = 0 if count == 5: # condition pour savoir quand tout les bateaux sont placés iscomplete = True if not iscomplete: # tant que tout les bateaux ne sont pas placés ship = Button(screen, (ship_list[i])[0], (x, y), angle) # apparition de bateau avec hit box else: ship = Button(screen, 'crosshair.png', (x, y), 0) # mise en place d'un curseur indiquant pour tirer if pygame.mouse.get_pressed()[2]: # d'abord bloquer la case avec clic gauche puis tirer avec clic droit if (pos_x, pos_y) in client_ship: # comparation des coordonnées des bateaux avec celles du curseur temp_image = 'explosion.png' # image en cas de coup sur bateau client_ship.remove((pos_x, pos_y)) # suppression de la coordonnée coulée else: temp_image = 'water_splash.png' # image en cas de coup raté ship = Button(screen, temp_image, (x, y), 0) # affichage de l'image touché ou non pygame.time.delay(300) # délai pour le comfort if len(client_ship) == 0 and iscomplete: # arrêt du jeu si tout les bateau sont touchés pygame.QUIT() redraw_window() # apparition de l'arrière plan
def run_game(): #初始化游戏 pygame.init() ai_settings=Settings() #初始化背景 #screen=pygame.display.set_mode((1200,800)) screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("model-yx") #初始化游戏窗口 # 创建按钮 play_button=Button(ai_settings,screen,"play") #创建飞机 plane=Plane(screen,ai_settings) # 创建储存子弹的编组 bullets = Group() # 创建敌人编组 enemys=Group() #设置背景色 # bg_color=(230,230,231) # 创建一个敌人 # enemy=Enemy(ai_settings,screen) # 创建一群敌人 gf.create_fleet(ai_settings,screen,plane,enemys) # 创建一个用于储存游戏统计信息的实例 stats=GameStats(ai_settings) #开始游戏循环 while True: gf.check_events(ai_settings,screen,stats,play_button,plane,enemys,bullets) # #监视键盘和鼠标事件 # '''for event in pygame.event.get(): # if event.type==pygame.QUIT: #退出事件 # sys.exit()''' if stats.game_active: plane.update() # bullets.update() # 删除已经消失的子弹 防止内存膨胀 # for bullet in bullets.copy(): # if bullet.rect.bottom<=0: # bullets.remove(bullet) #移动到 update_bullets(bullets) gf.update_bullets(ai_settings,screen,plane,enemys,bullets) gf.update_enemys(ai_settings,stats,screen,plane,enemys,bullets) # print(len(bullets)) # 检查子弹是否真的删除 # #重绘屏幕 # screen.fill(bg_color) # screen.fill(ai_settings.bg_color) # plane.blitme() # #绘制飞机 # # # # 更新屏幕 # pygame.display.flip() gf.update_screen(ai_settings,screen,stats,plane,enemys,bullets,play_button)
def finishPage(self): ## check win or lose ## create win or lose texts if self.sudoku.areBoardsSame(self.sudoku.playBoard, self.sudoku.sudokuSol): self.win = True else: self.win = False ## create buttons self.replayButton = Button( self.screen, int((self.WIDTH - self.menuButtonWidth) / 2), 200, self.menuButtonWidth, self.menuButtonHeight, self.BLACK, self.AQUAMARINE, self.CYAN, self.GREEN, lambda: self.creatingSudokuPage(), "Replay", self.medfont) self.mainMenuButton = Button( self.screen, int((self.WIDTH - self.menuButtonWidth) / 2), 320, self.menuButtonWidth, self.menuButtonHeight, self.BLACK, self.AQUAMARINE, self.CYAN, self.GREEN, lambda: self.mainMenu(), "Main Menu", self.medfont) self.exitButton = Button(self.screen, int((self.WIDTH - self.menuButtonWidth) / 2), 440, self.menuButtonWidth, self.menuButtonHeight, self.BLACK, self.LILAC, self.CYAN, self.GREEN, lambda: self.exitProgram(), "Exit", self.medfont) self.finishRun = True while self.finishRun: ## Running speed (fps) self.clock.tick(self.FPS) ## Process inputs (events) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: self.finishRun = False ## Update self.replayButton.update() self.mainMenuButton.update() self.exitButton.update() ## Draw (render) self.screen.fill(self.CREAM) #texts if self.win: self.textToScreen(self.WIDTH / 2, self.HEIGHT / 4, "YOU WIN!", self.BLACK, self.medfont) else: self.textToScreen(self.WIDTH / 2, self.HEIGHT / 4, "YOU LOSE.", self.BLACK, self.medfont) #buttons self.replayButton.draw() self.mainMenuButton.draw() self.exitButton.draw() # after drawing everything, flip the display pygame.display.flip() self.exitProgram()
def rainbow_playground(): global play play = 3 def rainbow_help(): global play play = 7 game_back_button = Button( colors.red, colors.light_red, 15, 10, 75, 35, "Exit", font=30, padding=0, on_click=menu, ) pause_button = Button( colors.blue, colors.light_blue, 340, 10, 110, 35, "Play", font=30,
def __show_score(self): try: scores = pickle.load(open("wyniki.pkl", "rb")) except FileNotFoundError: scores = [] # sorting scores with keeping indexes index = range(len(scores)) scores, index = zip( *reversed(sorted(zip(scores, index), key=lambda x: x[0][0]))) place = np.argmax(index) + 1 # play = False self.__screen.fill(self.__background_colour) self.__update() x_button, y_button = self.__x_screen // 20, self.__y_screen // 20 button_font_size = self.__y_screen // 18 title_font_size = self.__y_screen // 12 subtitle_font_size = self.__y_screen // 14 points_font_size = self.__y_screen // 16 return_btn = Button(self.__screen, 'Menu', (x_button, y_button), (x_button * 2, y_button * 2), button_color=self.__button_colour, label_color=self.__button_text_colour, func=self._menu, font_size=button_font_size) again_btn = Button(self.__screen, 'Zagraj jeszcze raz!', (self.__x_screen // 2, 7 * self.__y_screen // 8), (x_button * 7, y_button * 3), button_color=self.__button_colour, label_color=self.__button_text_colour, func=self.__play, font_size=button_font_size) self.__text('WYNIK', self.__x_screen // 2, self.__y_screen // 4, font_size=title_font_size) self.__text('Punkty', 3 * self.__x_screen // 4, self.__y_screen // 2, font_size=subtitle_font_size) self.__text('Imię', 2 * self.__x_screen // 4, self.__y_screen // 2, font_size=subtitle_font_size) self.__text('Pozycja', self.__x_screen // 4, self.__y_screen // 2, font_size=subtitle_font_size) self.__update() time.sleep(1) self.__text(str(self.__score), 3 * self.__x_screen // 4, self.__y_screen // 2 + 100, font_size=points_font_size) self.__update() time.sleep(1) self.__text(self.__name, 2 * self.__x_screen // 4, self.__y_screen // 2 + 100, font_size=points_font_size) self.__update() time.sleep(1) self.__text(f' {str(place) if place < 10 else str(place)}.', self.__x_screen // 4, self.__y_screen // 2 + 100, font_size=points_font_size) self.__update() return return_btn, again_btn
if Bquitscore.click(pppp)==True: if ppp==True: tsuccess.undraw() for item in textlist: item.undraw() notppp=False wins.close() win=GraphWin("Five balls game",500,650) win.setCoords(1,15,11,1) picture=Image(Point(8,6),"background.gif") #背景图片 picture.draw(win) bstart=Button(win,Point(3,12),Point(5,13)) bquit=Button(win,Point(7,12),Point(9,13)) text1=Text(Point(6,2),"五子彩球") #标题与说明 text2=Text(Point(5,8),'''规则说明:点击彩球将同色球移动到一行或一列, 若每行有五个或每列有五个以上则消去,并 获得相应的分数。若一次移动没有消去彩球, 则会随机出现三个新彩球,若成功消去则此次 不会出现新彩球。 -如果移动路线被其他彩球或砖块挡住,则不能移动 -连续若干次成功消去彩球,会获得相应的combo加分 -随着分数增加彩球颜色会增多,且每移动25次 会有一个砖块产生。所以尽量在少的步数内连 击更多的彩球
def appStarted(mode): mode.backButton = Button('Back', 600, 750, 100, 50)
def run_game(): # 初始化游戏并创建一个屏幕对象 初始化pygame、设置和屏幕对象 pygame.init() # 设置窗口出现的位置 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (40, 55) # 初始化一个设置实例 ai_settings = Settings() # 设置屏幕大小 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # # 设置屏幕大小(全屏) # screen = pygame.display.set_mode( # (ai_settings.screen_width, ai_settings.screen_height), pygame.FULLSCREEN) # 设置标题 pygame.display.set_caption("Thunder Fighters Vs Digital Monsters") # 创建Play按钮 play_button = Button(ai_settings, screen) # 创建一个用于存储游戏统计信息的实例 stats = GameStats(ai_settings) # 创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 创建一个外星人编组 aliens = Group() # # 创建一个外星人 # gf.create_alien(ai_settings, screen, aliens, stats) # 创建存储游戏统计信息的实例,并创建记分牌 sb = Scoreboard(ai_settings, screen, stats) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: # 在更新屏幕之前调用飞船的方法 ship.update() # 更新子弹状态 gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) # 更新外星人 gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) # 更新屏幕 gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def on_message(client, userdata, msg): print("Received message") with Button() as button: button.press() client.publish("teknobyen/doors/front/opening", "opening", 2)
def add_button(): """add button to screen""" return Button(BUTTON_X_POS, BUTTON_Y_POS)
def reset(): global timer timer.deinit() timer = None def debug(): micropython.mem_info() print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) def button_changed(pin): global timer if timer != None: reset() indicator.on() return indicator.on() start() indicator.off() # debug() btn = Button(pin=zero, callback=button_changed)
def loop(): print("Starting up app..") while (True): for btn in btns: btn.read() time.sleep(0.2) spotifyPlayer = SpotifyPlayer() discoverWeekly = "37i9dQZEVXcFDmNVmwGjZd" btnYellow = Button(29, "Yellow") btnRed = Button(31, "Red") btns = [btnYellow, btnRed] ledGreen = LED(11, "Green") ledYellow = LED(13, "Yellow") ledRed = LED(15, "Red") leds = [ledGreen, ledYellow, ledRed] btnYellow.subscribe(toggleLED, ledYellow) btnYellow.subscribe(toggleMirror, ledYellow) btnRed.subscribe(printState, btnRed, ledRed) btnRed.subscribe(toggleSpotifyPlayer, spotifyPlayer, ledRed) if __name__ == '__main__':
GPIO.setup(19, GPIO.IN) # Set Origin switch GPIO.setup(26, GPIO.IN) # Follow switch GPIO.setup(12, GPIO.IN) # Repeat switch GPIO.setup(21, GPIO.OUT) # Blink LED servoGripperPin = 24 # Servo Gripper # - - - - - - - - - - - - - - - - # - - - Global Objects - - - - - # - - - - - - - - - - - - - - - - pi = pigpio.pi('localhost', 8888) blinkLED = BlinkLED(21) stepperArm = StepperRobotArm(blinkLED, pi, servoGripperPin) replicaArm = ReplicaRobotArm() replayButton = Button(20, stepperArm.shortPressAction, lambda: True) deleteButton = Button(16, stepperArm.deleteReplayList, lambda: True) notUsedSwitch = Switch(6, lambda: True, lambda: True) endlessRepeatSwitch = Switch(13, lambda: stepperArm.setEndlessReplay(True), lambda: stepperArm.setEndlessReplay(False)) setOriginSwitch = Switch(19, replicaArm.getCorrValues, lambda: True) followSwitch = Switch(26, lambda: stepperArm.setMode('follow'), lambda: stepperArm.setMode('idle')) repeatSwitch = Switch(12, lambda: stepperArm.setMode('replay'), lambda: stepperArm.setMode('idle')) # - - - - - - - - - - - - - - - - # - - - UPDATE INPUT DEVICES - - # - - - - - - - - - - - - - - - -
def run_game(): # Initialize game pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Space Invaders The Game") spritesheet1 = SpriteSheet('SpriteSheets/alien1.png', screen) spritesheet2 = SpriteSheet('SpriteSheets/alien2.png', screen) spritesheet3 = SpriteSheet('SpriteSheets/alien3.png', screen) spritesheet4 = SpriteSheet('SpriteSheets/alien4.png', screen) spritesheet5 = SpriteSheet('SpriteSheets/player.png', screen) title1 = Titles(screen, "SPACE INVADERS", 0, (255, 0, 0)) title2 = Titles(screen, "The Game", 50, (255, 255, 0)) title3 = Titles(screen, "HIGH SCORES", 0, (200, 200, 200)) alienpoints = AlienPoints(screen, spritesheet1, spritesheet2, spritesheet3, spritesheet4, ai_settings) play_button = Button(ai_settings, screen, "Play", ai_settings.screen_height * 0.75) high_score_button = Button(ai_settings, screen, "High Scores", ai_settings.screen_height * 0.85) back_button = Button(ai_settings, screen, "Back", ai_settings.screen_height * 0.85) stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats, spritesheet5) # Make a ship. ship = Ship(ai_settings, screen, spritesheet5) bullets = Group() alien_bullets = Group() alien1 = Group() alien2 = Group() alien3 = Group() alien4 = AlienFour(ai_settings, screen, spritesheet4) # Creating the fleet of aliens gf.create_fleet(ai_settings, screen, ship, alien1, alien2, alien3, spritesheet1, spritesheet2, spritesheet3) while True: timer = pygame.time.Clock() timer.tick(60) gf.check_events(ai_settings, screen, stats, sb, play_button, high_score_button, ship, alien1, alien2, alien3, bullets, alien_bullets, spritesheet1, spritesheet2, spritesheet3) if stats.game_active: if not alien4.active: if pygame.time.get_ticks() % 10 == 0: if random.randint(1, 150) == 100: alien4.active = True alien4.blitme() ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, alien1, alien2, alien3, alien4, bullets, alien_bullets, spritesheet1, spritesheet2, spritesheet3) gf.update_aliens(ai_settings, screen, stats, sb, ship, alien1, alien2, alien3, alien4, bullets, alien_bullets, spritesheet1, spritesheet2, spritesheet3) gf.update_screen(ai_settings, screen, stats, sb, ship, alien1, alien2, alien3, alien4, bullets, alien_bullets, play_button, high_score_button, back_button, title1, title2, title3, alienpoints)
def main(): pygame.init() pygame.mixer.init() # 创建设置实例 ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.bg_width, ai_settings.bg_height)) background = pygame.image.load("images/background.png").convert() pygame.display.set_caption("飞机大战 -- 代码重构版") # 创建音乐、音效实例 sound = Sound() pygame.mixer.music.play(-1) # 创建游戏状态实例 stats = Stats(ai_settings) # 创建计时器实例 timer = Timer() # 创建button实例 button = Button(ai_settings) # 创建字体实例 font = Font() # 生成我方飞机 me = myplane.MyPlane(ai_settings) # 生成地方飞机 enemies = Group() small_enemies = Group() mid_enemies = Group() big_enemies = Group() gf.add_enemies(ai_settings, small_enemies, mid_enemies, big_enemies, enemies) # 生成子弹 bullet1 = [] bullet2 = [] gf.create_bullets(ai_settings, me, bullet1, bullet2) clock = pygame.time.Clock() # 每30秒发放一个补给包 bullet_supply = supply.BulletSupply(ai_settings) bomb_supply = supply.BombSupply(ai_settings) pygame.time.set_timer(timer.SUPPLY_TIME, 30 * 1000) running = True while running: # 响应鼠标和键盘事件 gf.check_events(ai_settings, me, stats, bomb_supply, bullet_supply, sound, timer, button, enemies) # 根据用户的得分增加难度 gf.level_up(ai_settings, stats, sound, small_enemies, mid_enemies, big_enemies, enemies) # 背景图像先绘制,防止通过暂停作弊 screen.blit(background, (0, 0)) if me.life_num: # 绘制暂停按钮 screen.blit(button.paused_image, button.paused_rect) if me.life_num and not stats.paused: # 控制飞机 gf.control_plane(me) # 绘制全屏炸弹补给并检测是否获得 gf.check_bomb_supply(screen, sound, me, bomb_supply) # 绘制超级子弹补给并检测是否获得 gf.check_bullet_supply(ai_settings, screen, sound, me, timer, bullet_supply) # 发射子弹 if not (ai_settings.delay % 10): bullets = gf.fire_bullets(ai_settings, sound, me, bullet1, bullet2) # 检测子弹是否击中敌机 gf.check_hit_enemies(screen, bullets, mid_enemies, big_enemies, enemies) # 绘制敌机 gf.create_enemies(ai_settings, screen, sound, stats, big_enemies, mid_enemies, small_enemies) # 绘制我方飞机 gf.create_my_plane(ai_settings, screen, sound, me, timer) # 检测我方飞机是否被撞 gf.check_my_plane_hit(me, enemies) # 更新游戏界面 gf.update_play_screen(ai_settings, screen, font, button, stats, me, bomb_supply) # 绘制游戏结束画面 elif me.life_num == 0: gf.update_end_screen(ai_settings, screen, font, button, stats, timer, main) # 切换我方飞机图片 gf.switch_image(ai_settings) gf.change_delay(ai_settings) pygame.display.flip() clock.tick(60)
min_speed = 1 max_speed = 3 clock = pg.time.Clock() font = pg.font.SysFont('arial', 30, True) player = { 'date': '', 'name': '', 'score': 0, } # draw main scene screen = pg.display.set_mode((W, H)) pg.display.set_caption('Barbie') # button draw easy_btn = Button((133, 200), (200, H // 2), 'Easy', GREEN) easy_btn.draw(screen) normal_btn = Button((133, 200), (W // 2, H // 2), 'Normal', ORANGE) normal_btn.draw(screen) hard_btn = Button((133, 200), (W - 200, H // 2), 'Dior', RED) hard_btn.draw(screen) buttons = [easy_btn, normal_btn, hard_btn] # nameBox nameBox = InputBox(W // 2 - 70, 200, 140, 40) txt_name = font.render('Enter your name', True, WHITE) # sky sky = pg.image.load('images/background.jpg').convert() sky = pg.transform.scale(sky, (W, H))
def main(): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" # Initialize Everything pygame.init() width = pygame.display.Info().current_w height = pygame.display.Info().current_h screen = pygame.display.set_mode((1024, 728), RESIZABLE) pygame.display.set_caption("Culling Card") icon = pygame.image.load("data/icon.png") pygame.display.set_icon(icon) pygame.mouse.set_visible(1) fs = False size = startgame(screen) if size == "sm": screen = pygame.display.set_mode((1024, 728), RESIZABLE) elif size == "med": screen = pygame.display.set_mode((1280, 800), RESIZABLE) elif size == "full": screen = pygame.display.set_mode((width, height), FULLSCREEN) fs = True # Create The Backgound background = BackgroundImage('data/background.jpg', [0, 0]) screen.fill([255, 255, 255]) screen.blit(background.image, background.rect) # Display The Background screen.blit(background.image, (0, 0)) pygame.display.flip() # Prepare Game Objects score = 0 mob_mult = 0 clock = pygame.time.Clock() hero = Hero() enemy = get_enemy() health = Health(screen) energy = Energy(screen) shield = Shield(screen) deck = Deck() hand = [] discard = [] if not fs: turn_button = Button(screen, "End Turn", .88, .8) exit_button = Button(screen, "Exit", .9, .05) score_keep = Button(screen, "Score: " + str(score), .5, .1) else: turn_button = Button(screen, "End Turn", .8, .8) exit_button = Button(screen, "Exit", .8, .1) health = Health(screen, .15, .8) energy = Energy(screen, .15, .85) score_keep = Button(screen, "Score: " + str(score), .5, .1) all_sprites = pygame.sprite.RenderPlain((hero, enemy)) ui_elements = [ health, energy, shield, turn_button, score_keep, enemy, exit_button ] #used when checking for clicks on cards, avoid checking clicks on non card elements cards = pygame.sprite.RenderPlain() # Main Loop going = True player_turn = True # Draw Everything all_sprites.update() all_sprites.draw(screen) while going: clock.tick(60) deck.draw_n(5, hand, discard) all_sprites.add(hand) cards.add(hand) redraw_screen(screen, ui_elements, all_sprites) pygame.display.flip() # Handle Input Events while player_turn: # turn doesn't end until player clicks end turn for event in pygame.event.get(): if event.type == QUIT: player_turn = False going = False break elif event.type == MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if turn_button.rect.collidepoint( pos): # player clicked end turn all_sprites.remove(hand) cards.empty() discard.extend(hand) hand = [] player_turn = False elif exit_button.rect.collidepoint(pos): exit() else: for card in hand.copy(): if card.rect.collidepoint(pos): if energy.energy <= 0: alert(screen, "Out of Energy!", 1) else: hand.remove(card) card.kill() discard.append(card) if (type(card) == draw_card.DrawCard): alert(screen, "Player drew two cards!", 1) elif (type(card) == blue_attack.BlueAttack and enemy.type == "red") or ( type(card) == green_attack.GreenAttack and enemy.type == "blue") or ( type(card) == red_attack.RedAttack and enemy.type == "green"): alert( screen, "Player dealt 8 damage! It was super effective!", 1) elif (type(card) == red_attack.RedAttack and enemy.type == "red") or ( type(card) == blue_attack.BlueAttack and enemy.type == "blue") or ( type(card) == green_attack.GreenAttack and enemy.type == "green"): alert(screen, "Player dealt 5 damage!", 1) elif (type(card) == green_attack.GreenAttack and enemy.type == "red") or ( type(card) == red_attack.RedAttack and enemy.type == "blue") or ( type(card) == blue_attack.BlueAttack and enemy.type == "green"): alert( screen, "Player dealt 3 damage! It was not very effective...", 1) elif (type(card) == defend_card.DefendCard ): alert(screen, "Player setup 2 block!", 1) energy.update(-card.en_cost) card.clicked(hero, enemy, deck, hand, discard) shield.defense = hero.defense cards.add(hand) all_sprites.add(hand) break redraw_screen(screen, ui_elements, all_sprites, True) pygame.display.flip() if health.health <= 0: if endgame(screen, False): pass elif enemy.health <= 0: alert(screen, "Player killed the enemy!", 1) score += 50 score_keep.update("Score: " + str(score)) mob_mult += 1 # if endgame(screen,score,True): enemy.kill() hero.defense = 0 shield.defense = hero.defense enemy = get_enemy(mob_mult) ui_elements[-2] = enemy energy.energy = 3 all_sprites.add(enemy) redraw_screen(screen, ui_elements, all_sprites) pygame.display.flip() elif event.type == RESIZABLE and not fs: #redefine screen and fit background to screen width, height = event.size if width < 1024: width = 1024 if height < 768: height = 768 screen = pygame.display.set_mode( (width, height), pygame.RESIZABLE | HWSURFACE | DOUBLEBUF) redraw_screen(screen, ui_elements, all_sprites) pygame.display.flip() if (not going): break energy.energy = 3 enemy.attack() dmg_remaining = enemy.pow - hero.defense if (dmg_remaining > 0): alert(screen, f"Player took {dmg_remaining} damage.", 1) health.update(-dmg_remaining) else: hero.defense = hero.defense - enemy.pow alert(screen, f"Enemy hit player's shield for {enemy.pow} damage.", 1) hero.defense = 0 shield.defense = hero.defense player_turn = True if health.isDead(): going = endgame(screen, score, False) score = 0 health.health = 25 enemy.kill() enemy = get_enemy() all_sprites.add(enemy) ui_elements[-2] = enemy score_keep.update("Score: 0") deck.merge(discard) discard.clear() pygame.quit()
def run_game(): # 初始化游戏并创建一个屏幕对象 #pygame.font.init() #cur_font = pygame.font.SysFont("semiHei",10) pg.init() # 初始化背景设置 ai_settings = Settings() screen = pg.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) screen.fill(ai_settings.bg_color) # 事先填充所需颜色 # 创建一个名为screen的显示窗口,实参(1200,800)是一个元组,指的是游戏窗口尺寸 pg.display.set_caption('外星人入侵!') # 对象screen是一个surface,在这个游戏中,每个元素(外星人,飞船)都是个surface # 我们激活游戏的动画循环后,每经过一次循环都将自动重绘这个surface # 创建一个play按钮,一个继续按钮,一个重新开始按钮 play_button = Button( ai_settings, screen, "开始游戏", [56, 180, 139], # 翠绿 ai_settings.screen_width / 2, ai_settings.screen_height / 2) resume_button = Button( ai_settings, screen, "继续", [42, 146, 165], # 墨绿 ai_settings.screen_width / 2, ai_settings.screen_height / 2 + 50) restart_button = Button( ai_settings, screen, "重新开始", [216, 95, 77], # 红 ai_settings.screen_width / 2, ai_settings.screen_height / 2 - 50) # 创建一个用于存储游戏统计信息的实例和一个计分板实例 stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # 创建一艘飞船,个用于存储子弹和外星人的编组Group ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # 创建一个外星人群 gf.create_fleet(ai_settings, screen, ship, aliens) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 gf.check_events(ai_settings, stats, sb, screen, ship, bullets, aliens, play_button, resume_button, restart_button) if stats.game_active: # 更新飞船、子弹和外星人的位置 ship.update() gf.update_bulltes(ai_settings, sb, screen, ship, aliens, bullets) gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens, bullets) # 更新屏幕 gf.update_screen(ai_settings, stats, sb, screen, ship, aliens, bullets, play_button, resume_button, restart_button)
] list_TileY = [ int((screen.get_height() / 2 - imgtile.get_height() / 2 + 100)), int((screen.get_height() / 2 - imgtile.get_height() / 2)), int((screen.get_height() / 2 - imgtile.get_height() / 2 - 1)), int((screen.get_height() / 2 - imgtile.get_height() / 2 - 100)) ] for i in list_TileX: Shop.list_PosX.append(i) for i in list_TileY: Shop.list_PosY.append(i) # Différent Boutons --------------------------------------------------------------------------------- play_btn = Button((50, 50, 50), int(screen_width / 2) - 100, back_title.get_height() + 100, 200, 75, 'Play') shop_btn = Button((50, 50, 50), int(screen_width / 2) - 100, int(play_btn.getHeight() + screen_heigth / 30), 200, 75, 'Shop') reset_all_btn = Button((50, 50, 50), int(screen_width / 2) - 100, int(shop_btn.getHeight() + screen_heigth / 30), 200, 75, 'Reset All') quitter_btn = Button((50, 50, 50), int(screen_width / 2) - 100, int(reset_all_btn.getHeight() + screen_heigth / 30), 200, 75, 'Quitter') restart_btn = Button((50, 50, 50), 360, 300, 280, 100, 'Restart Game')
def __handleShown(self, options): """Set to fire when keyboard is shown. options is like: { 'focus': False, 'hints': /,\\,\\\\,test,toast,🦇,﷽,ﷺ, 'opener': <line_edit.LineEdit object at 0x46155cb0>, } """ if not options["hints"]: self.uiSuggestionBar.hide() inputGeometry = QtCore.QRect(0, padding, self.uiKeyPanel.width(), self.uiKeyPanel.height()) self.uiKeyPanel.setGeometry(inputGeometry) inputGeometry.setHeight(inputGeometry.height() + padding) #This is like the opposite of a good API. It is minimally expressive. self.setGeometry(inputGeometry) else: self.uiSuggestionBar.show() inputGeometry = QtCore.QRect(0, self.uiSuggestionBar.height(), self.uiKeyPanel.width(), self.uiKeyPanel.height()) self.uiKeyPanel.setGeometry(inputGeometry) inputGeometry.setHeight(inputGeometry.height() + self.uiSuggestionBar.height()) #The lack of padding here is worrying, but works. I think something in the input panel is covering for it. self.setGeometry(inputGeometry) self.uiSuggestionBarLayout.parentWidget().raise_() for i in range(self.uiSuggestionBarLayout.count()): #Clear the existing widgets. self.uiSuggestionBarLayout.itemAt(i).widget().deleteLater() for hint in options["hints"]: print('adding hint', hint) hintButton = Button(self.uiSuggestionBarLayout.parentWidget()) hintButton.setText(hint) hintButton.setFocusPolicy( QtCore.Qt.StrongFocus if options["focus"] else QtCore.Qt.NoFocus ) hintButton.clicked.connect( #We can't inject keystrokes directly, it seems - `self.sendKeystroke(ord(hint[0]), hint) )` is broken? (lambda hint: lambda: options['opener'].insert(hint))(hint) ) #Bind hint from for loop. hintButton.clickMarginLeft = 0 hintButton.clickMarginRight = 0 hintButton.clickMarginTop = hintButton.half hintButton.clickMarginBottom = 0 hintButton.setCustomStyleSheet("Button { border-left-width: 0px; }") #We can't set a border of -1, which is what we actually need, so we remove one border from our buttons to maintain the 1px-wide lines. self.uiSuggestionBarLayout.addWidget(hintButton) hintButton.show() self.setGeometry(0, self.parentWidget().height() - self.height(), self.width(), self.height()) #Calculate content position. openerGeometry = options["opener"].geometry() #Three syntaxes for "give me the member data". contentsGeometry = self.parentWidget().screenContents.geometry() screenGeometry = self.parentWidget().geometry() availableArea = QtCore.QRect(0,0, screenGeometry.width(), screenGeometry.height() - inputGeometry.height() ) targetVerticalLocationForInput = availableArea.height()//2 - openerGeometry.height()//2 #Calculate ideal top of *widget*, since we can't set widget center. idealContentsDeltaToCenter = targetVerticalLocationForInput - openerGeometry.top() #Clamp the screen delta so it never leaves part of the screen undrawn. if contentsGeometry.top() + idealContentsDeltaToCenter >= screenGeometry.top(): contentsDeltaToCenter = screenGeometry.top() #We're already as low as we can go. Go no lower. elif contentsGeometry.bottom() + idealContentsDeltaToCenter <= availableArea.bottom(): contentsDeltaToCenter = availableArea.height() - screenGeometry.height() + padding #Go as high as we can go, less padding so the fade still works. ;) else: contentsDeltaToCenter = idealContentsDeltaToCenter contentsGeometry.moveTop( 0+contentsDeltaToCenter) self.parentWidget().screenContents.setGeometry(contentsGeometry)
def OfflinePropDetails(mainGame, screen, clock): font_40 = pygame.font.SysFont('Arial', 40) #Font for title, money and exit button font_20 = pygame.font.SysFont('Arial', 20) #Font for actual property details font_20b = pygame.font.SysFont('Arial', 20, True) #Font for column headings font_16 = pygame.font.SysFont('Arial', 16) #Font for button captions props_owned = countPropsOwned(mainGame.board, mainGame.cur_player) board_poses = setupBoardPoses( mainGame.board, mainGame.cur_player, props_owned ) #Array containing the board positions of all of the current player's owned properties tit_text = font_40.render('Viewing Property Details:', True, (0, 0, 0)) #Render title at top left of screen headers = [ font_20b.render('Property', True, (0, 0, 0)), font_20b.render('Group', True, (0, 0, 0)), font_20b.render('Rent (£)', True, (0, 0, 0)), font_20b.render('Mortgage(£)', True, (0, 0, 0)), font_20b.render('CH/TB', True, (0, 0, 0)), font_20b.render('Options', True, (0, 0, 0)) ] head_x = [30, 200, 260, 330, 440, 640] #Initialise button arrays buy_buts = np.array([None] * props_owned) sell_buts = np.array([None] * props_owned) mort_buts = np.array([None] * props_owned) deed_buts = np.array([None] * props_owned) exit_but = pygame.Rect(880, 10, 120, 50) y_top = 90 #First y co-ordinate for a row of details y_space = 30 #Co-ordinate spacing between rows #Setup buttons (one element of each array for each property) for counter in range(props_owned): buy_buts[counter] = pygame.Rect(500, y_top + y_space * counter, 60, 25) sell_buts[counter] = pygame.Rect(565, y_top + y_space * counter, 60, 25) mort_buts[counter] = pygame.Rect(630, y_top + y_space * counter, 60, 25) deed_buts[counter] = pygame.Rect(695, y_top + y_space * counter, 75, 25) exit_but = Button(880, 10, 120, 50, "Exit", font_40) fps = 10 cur_deed = None #Image for a title deed that is being displayed at any one moment deed_prop = -1 #Board position of the property whose title deed is currently being shown buy_but_click = -1 #Variables storing when buttons are clicked sell_but_click = -1 #-1 indicates not clicked for this iteration mort_but_click = -1 #Not -1 indicates the integer contents of the variable is the row of whatever of the four types of button was clicked (zero-indexed) deed_but_click = -1 prop_details_running = True while prop_details_running: #Main loop for this part of the program for event in pygame.event.get(): exit_but.handle_input_event(event) if event.type == pygame.QUIT: prop_details_running = False gotoScreen = -1 if event.type == pygame.KEYDOWN: #If any key pressed if event.key == pygame.K_ESCAPE: #Escape key exits the game prop_details_running = False gotoScreen = -1 if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: #Left mouse button mouse_pos = event.pos #Position of the cursor when nouse was clicked for counter in range( props_owned ): #Cycle through all the arrays of buttons ot see if any have been clicked if buy_buts[counter].collidepoint(mouse_pos): buy_but_click = counter if sell_buts[counter].collidepoint(mouse_pos): sell_but_click = counter if mort_buts[counter].collidepoint(mouse_pos): mort_but_click = counter if deed_buts[counter].collidepoint(mouse_pos): deed_but_click = counter screen.fill((255, 255, 255)) screen.blit(tit_text, [10, 0]) pygame.draw.rect( screen, (0, 0, 0), pygame.Rect(10, 50, 770, 700), 10) #Draw black rectangle surrounding the property data mon_text = font_40.render( '£' + str(mainGame.getCurPlayer().player_money), True, (0, 0, 0)) #Render player money on screen f_width, f_height = font_40.size( '£' + str(mainGame.getCurPlayer().player_money)) screen.blit(mon_text, [(770 - f_width), 0]) #Display each of the column headings for counter in range(6): screen.blit(headers[counter], [head_x[counter], 60]) if cur_deed != None: #Can only display a chosen title deed if one has already been chosen screen.blit(cur_deed, [790, 200]) y_pos = y_top #Y co-ordinate of the first row of data for counter in range(props_owned): text_1 = font_20.render( mainGame.board.getProp(board_poses[counter]).prop_title, True, (0, 0, 0)) #Property name/title screen.blit(text_1, [30, y_pos]) if mainGame.board.getProp( board_poses[counter] ).prop_type == Prop_Type.NORMAL: #SCHOOL and STATION properties have no 'Group Colour', Council Houses or Tower Blocks pygame.draw.rect( screen, mainGame.board.getProp(board_poses[counter]).group_col, pygame.Rect(200, y_pos, 30, 20)) show_rent = mainGame.board.getProp( board_poses[counter]).getRent() if mainGame.board.wholeGroupOwned( mainGame.cur_player, board_poses[counter]) and mainGame.board.getProp( board_poses[counter]).C_Houses == 0: show_rent = show_rent * 2 text_2 = font_20.render(str(show_rent), True, (0, 0, 0)) screen.blit(text_2, [260, y_pos]) text_4 = font_20.render( str(mainGame.board.getProp( board_poses[counter]).C_Houses) + '/' + str(mainGame.board.getProp(board_poses[counter]).T_Blocks), True, (0, 0, 0)) screen.blit(text_4, [440, y_pos]) text_3 = font_20.render( str(mainGame.board.getProp(board_poses[counter]).mortgage_val), True, (0, 0, 0)) #Mortgage value of the property screen.blit(text_3, [330, y_pos]) y_pos += y_space #Increment y co-ordinate variable by the difference in co-ordinates between each row, as already defined if mainGame.board.wholeGroupOwned(mainGame.cur_player, board_poses[counter]): if mainGame.board.getProp( board_poses[counter] ).C_Houses < 4: #Council Houses are still available to buy displayButtonRect(screen, buy_buts[counter], (100, 100, 100), font_16, 'Buy CH', (0, 0, 0)) elif mainGame.board.getProp( board_poses[counter] ).T_Blocks == 0: #Player may still buy a Tower Block displayButtonRect(screen, buy_buts[counter], (100, 100, 100), font_16, 'Buy TB', (0, 0, 0)) if mainGame.board.getProp( board_poses[counter] ).T_Blocks > 0: #Player has Tower Blocks available to sell displayButtonRect(screen, sell_buts[counter], (100, 100, 100), font_16, 'Sell TB', (0, 0, 0)) elif mainGame.board.getProp( board_poses[counter] ).C_Houses > 0: #Player has no Tower Blocks, but still has Council Houses which may be sold displayButtonRect(screen, sell_buts[counter], (100, 100, 100), font_16, 'Sell CH', (0, 0, 0)) if mainGame.board.getProp( board_poses[counter] ).mortgage_status: #Properrty is mortgaged, thus it can only be bought back displayButtonRect(screen, mort_buts[counter], (100, 100, 100), font_16, 'Buy-Back', (0, 0, 0)) else: #Property may be mortgaged as it is not currently mortgaged displayButtonRect(screen, mort_buts[counter], (100, 100, 100), font_16, 'Mortgage', (0, 0, 0)) displayButtonRect(screen, deed_buts[counter], (100, 100, 100), font_16, 'View Deed', (0, 0, 0)) if mort_but_click != -1: #One of the mortgaging buttons has been clicked if mainGame.board.getProp(board_poses[mort_but_click] ).mortgage_status == False: #Unmortgaged mainGame.board.getProp( board_poses[mort_but_click] ).mortgage_status = True #Mortgage property mainGame.getCurPlayer().addMoney( mainGame.board.getProp( board_poses[mort_but_click]).mortgage_val ) #Increase the player's money by the mortgage value of the property else: #Mortgaged already if mainGame.getCurPlayer( ).player_money >= mainGame.board.getProp( board_poses[mort_but_click] ).mortgage_val * 1.2: #If the player has 120% of the mortgage value of the property (this is the buy-back cost) mainGame.board.getProp( board_poses[mort_but_click] ).mortgage_status = False #Unmortgage the property mainGame.getCurPlayer().spendMoney( int( mainGame.board.getProp( board_poses[mort_but_click]).mortgage_val * 1.2) ) #Debit the player's money by 120% of the mortgage value if deed_prop == board_poses[ mort_but_click]: #If title deed has changed cur_deed = pygame.transform.smoothscale( mainGame.board.getProp( board_poses[mort_but_click]).getTitleDeed(), [225, 400]) if deed_but_click != -1: #One of the buttons for viewing a title deed has been clicked cur_deed = pygame.transform.smoothscale( mainGame.board.getProp( board_poses[deed_but_click]).getTitleDeed(), [225, 400]) #Scale title deed so it fits in the narrow sidebar deed_prop = board_poses[deed_but_click] if buy_but_click != -1: #One of the buttons for buying CH or TB has been clicked if mainGame.board.getProp( board_poses[buy_but_click] ).C_Houses < 4: #Fewer than 4 Council Houses, so these are the next upgrade to be bought if mainGame.getCurPlayer().player_money >= ( mainGame.board.getProp( board_poses[buy_but_click]).CH_cost * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[buy_but_click]) ): #Player actually has enough money to buy the Council House upgrade mainGame.board.buyCHGroup( mainGame.cur_player, board_poses[buy_but_click] ) #Buy the Council Houses for the whole group mainGame.getCurPlayer().spendMoney( mainGame.board.getProp( board_poses[buy_but_click]).CH_cost * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[buy_but_click]) ) #Decrease the player's money by the cost of a Council House for however many properties are in the group elif mainGame.board.getProp( board_poses[buy_but_click] ).C_Houses == 4 and mainGame.board.getProp( board_poses[buy_but_click] ).T_Blocks == 0: #4 Council Houses and no Tower Blocks, so Tower Block can be bought if mainGame.getCurPlayer().player_money >= ( mainGame.board.getProp( board_poses[buy_but_click]).TB_cost * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[buy_but_click]) ): #Player actually has enough money to buy the Tower Block upgrade mainGame.board.buyTBGroup( mainGame.cur_player, board_poses[buy_but_click] ) #Buy the Council Houses for the whole group mainGame.getCurPlayer().spendMoney( mainGame.board.getProp( board_poses[buy_but_click]).TB_cost * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[buy_but_click]) ) #Decrease the player's money by the cost of a Tower Block for however many properties are in the group if sell_but_click != -1: #One of the buttons for selling CH or TB has been clicked if mainGame.board.getProp( board_poses[sell_but_click] ).T_Blocks > 0: #Property has a Tower Block that can be sold mainGame.board.sellTBGroup( mainGame.cur_player, board_poses[sell_but_click] ) #Sell the Tower Blocks for the whole group mainGame.getCurPlayer().addMoney( int( mainGame.board.getProp( board_poses[sell_but_click]).TB_cost / 2 * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[sell_but_click])) ) #Increase the player's money by half of what the upgrades were bought for elif mainGame.board.getProp( board_poses[sell_but_click] ).C_Houses > 0: #No Tower Blocks, buy some Council Houses which can instead be sold mainGame.board.sellCHGroup( mainGame.cur_player, board_poses[sell_but_click] ) #Sell the Council Houses for the whole group mainGame.getCurPlayer().addMoney( int( mainGame.board.getProp( board_poses[sell_but_click]).CH_cost / 2 * mainGame.board.countGroupSize( mainGame.cur_player, board_poses[sell_but_click])) ) #Increase the player's money by half of what the upgrades were bought for if exit_but.clicked(): prop_details_running = False gotoScreen = 1 exit_but.render(screen) #Reset all button variables so the actions of buttons only happen once buy_but_click = -1 sell_but_click = -1 mort_but_click = -1 deed_but_click = -1 clock.tick( fps ) #10 fps currently, but could easily be changed to update more or less often pygame.display.flip( ) #Refresh display from a pygame perspective, to reflect the screen.blit()s 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
def run_game(): '''Main function to run game''' # Instantiate game pygame.init() # Instantiate settings object to hold game settings ai_settings = Settings() stats = Stats() # Set screen width, height, and settings screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Snake"); # Instantiate snake snake = Snake(ai_settings, screen) # Instatiate fruit object fruit = Fruit(ai_settings, screen, snake) # Institiate clock object to cap FPS clock = pygame.time.Clock() title_card = Button(ai_settings, screen, ai_settings.screen_width / 2, ai_settings.screen_height / 6, (screen.get_rect().centerx, screen.get_rect().centery - 150), (222, 184, 135), (34, 139, 34), "SNAKE") play_button = Button(ai_settings, screen, ai_settings.screen_width / 3, ai_settings.screen_height / 8, (screen.get_rect().centerx, screen.get_rect().centery - 50), (222,184, 135), (34, 139, 34), "PLAY") leaderboard_button = Button(ai_settings, screen, ai_settings.screen_width / 3, ai_settings.screen_height / 8, (screen.get_rect().centerx, screen.get_rect().centery + 25), (222,184, 135), (34, 139, 34), "LEADERBOARD") exit_button = Button(ai_settings, screen, ai_settings.screen_width / 3, ai_settings.screen_height / 8, (screen.get_rect().centerx, screen.get_rect().centery + 100), (222, 184, 135), (34, 139, 34), "EXIT") '''Main game loop''' while True: while stats.main_menu_active: # Check user events and apply them mf.check_events(stats, play_button, leaderboard_button, exit_button) # Render screen mf.update_screen(ai_settings, screen, title_card, play_button, leaderboard_button, exit_button) # Flip to next rendered frame pygame.display.flip() while stats.leaderboard_menu_active: break while stats.game_active: # 12 FPS cap clock.tick(12) # Check user events and apply them gf.check_events(ai_settings, snake) # Update snake according to input snake.update() # Check snake and fruit status gf.check_snake_status(ai_settings, stats, screen, snake, fruit) # Render screen gf.update_screen(ai_settings, screen, snake, fruit) # Flip to next rendered frame pygame.display.flip() # Reset game settings before each new game mf.reset_game(ai_settings, screen, snake, fruit)
def options_menu(gameDisplay): music_player = music.Music_Player() music_player.play_options() w, h = pygame.display.get_surface().get_size() gameDisplay.fill(config.black) #buttons = [Button("BACK", white, SPOOKY_SMALL_FONT, (0,0))] current_volume = music_player.get_volume() volumeDisplay = Button(str(roundup(math.trunc(current_volume * 100))), config.white, config.SPOOKY_SMALL_FONT, (config.display_width /2 , config.display_height /2) ,gameDisplay) volume = Button("VOLUME", config.white, config.SPOOKY_SMALL_FONT, (volumeDisplay.pos[0] - 200, volumeDisplay.pos[1]) ,gameDisplay) buttons =[Button("BACK", config.white, pygame.font.Font("assets/fonts/CHILLER.ttf", 70), (90, 60), gameDisplay), Button("<", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2 - 80, config.display_height / 2), gameDisplay), Button(">", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2 + 80, config.display_height / 2), gameDisplay), Button("MUTE", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2, config.display_height / 2 + 100), gameDisplay), Button("1280 x 768", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2, config.display_height / 2 - 200), gameDisplay), Button("1400 x 900", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2, config.display_height / 2 - 100), gameDisplay), Button("Save", config.white, config.SPOOKY_SMALL_FONT, (config.display_width / 2, config.display_height / 2 + 200), gameDisplay), Button("Load", config.white, config.SPOOKY_SMALL_FONT,(config.display_width / 2, config.display_height / 2 + 300), gameDisplay) ] while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if (event.key == pygame.K_p): print(1111111111) return elif (event.type == pygame.QUIT): pygame.quit() quit() elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[0].rect.collidepoint( pygame.mouse.get_pos())): # if(config.paused == True): # print("proceeding to character selection function") # character_selection(gameDisplay) if(config.paused == False): return elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[1].rect.collidepoint( pygame.mouse.get_pos())): if (buttons[3].text != "UNMUTE"): music_player.set_volume(current_volume - 0.10) # Subtracting two floats isn't exact so multiply by 100 then truncate if (math.trunc(current_volume * 100) > 0): current_volume -= 0.10 # Need to re-render button reRenderVol(volumeDisplay, volume, str(roundup(math.trunc(current_volume * 100))), gameDisplay) elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[2].rect.collidepoint( pygame.mouse.get_pos())): if (buttons[3].text != "UNMUTE" and current_volume <= 100): music_player.set_volume(current_volume + 0.10) if (math.trunc(current_volume * 100) < 100): current_volume += 0.10 reRenderVol(volumeDisplay, volume, str(roundup(math.trunc(current_volume * 100))), gameDisplay) elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[3].text == "MUTE" and buttons[ 3].rect.collidepoint(pygame.mouse.get_pos())): music_player.set_volume(0.0) buttons[3].text = "UNMUTE" reRenderVol(volumeDisplay, volume, str(roundup(math.trunc(current_volume * 100))), gameDisplay) elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[3].text == "UNMUTE" and buttons[3].rect.collidepoint(pygame.mouse.get_pos())): music_player.set_volume(current_volume) buttons[3].text = "MUTE" reRenderVol(volumeDisplay, volume, str(roundup(math.trunc(current_volume * 100))), gameDisplay) elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[4].text == "1280 x 768" and buttons[4].rect.collidepoint(pygame.mouse.get_pos())): config.display_width = 1280 config.display_height = 768 pygame.display.set_mode((config.display_width, config.display_height)) pygame.transform.scale(gameDisplay, (config.display_width, config.display_height)) pygame.display.update() elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and buttons[5].text == "1400 x 900" and buttons[5].rect.collidepoint(pygame.mouse.get_pos())): config.display_height = 1400 config.display_height = 900 pygame.display.set_mode((config.display_width, config.display_height)) pygame.transform.scale(gameDisplay, (config.display_width, config.display_height)) pygame.display.update() pygame.transform.scale(gameDisplay, (config.display_width, config.display_height)) for button in buttons: Button.check_Hover(button, gameDisplay) pygame.display.update() clock.tick(15)