def Game(difficulty, numberofteams): if numberofteams == 1: score = [0] else: score = [0, 0] currentteam = 0 startb = Button(WIDTH - start.get_width(), HEIGHT - start.get_height(), screen, start) if difficulty == 1: words = words1 else: words = words2 global running running = True nextwords = tuple() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.blit(background, (0, 0)) startb.drawbutton() for i in range(len(score)): screen.blit(font.render("Score:" + str(score[i]), True, WHITE), (0, HEIGHT / 2 + 50 * i)) pygame.display.flip() if startb.ispressed(): score[currentteam] += one_round(difficulty) currentteam += 1 currentteam %= numberofteams
def main(): #Creates a greeting window using a image taken from the internet to allow the player to choose to: Play or Quit gameImage = Image(Point(180, 180), "parchessi.png") window = GraphWin("Parcheesi", 360, 360) gameImage.draw(window) #Creates the Buttons for Play or Quit using the Class Button playButton = Button(window, Point(180.0, 200), 80, 30, "Play") quitButton = Button(window, Point(180.0, 240), 80, 30, "QUIT") playButton.activate() quitButton.activate() pt = window.getMouse() #Gets the users click on which button if not quitButton.clicked( pt): #if the Play button is clicked, the game begins window.close( ) #closes the previous window so that the game window in the only one remaining win = GraphWin("Parcheesi", 820, 620) #We declare and define our window field = inheritanceBoard( ) #we make an object from the inheritanceBoard class so that the user may customize the board game (colors) if desired game = Game() #creates the object from Game class field.board(win) #draws the board game.playGame(win) #starts the game
def rulesonscreen(): global running backb = Button(30, HEIGHT - back.get_height() - 30, screen, back) while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() if backb.ispressed(): start_scenery() screen.fill(BLACK) screen.blit(rules_text, (0, 0)) backb.drawbutton() pygame.display.flip()
def __init__(self, width, height): # We create the window self.width = width self.height = height FULLSCREEN = 0 self.dimension = (self.width, self.height) self.screen = pygame.display.set_mode(self.dimension, FULLSCREEN, 32) pygame.display.set_caption("TuxleTriad") elemText = ["Play", "Options", "Rules", "About", "Quit Game"] self.menu = [] for elem in elemText: self.menu.append(Button(elem, "Dearest.ttf", white)) posx = 400 posy = 400 - (60 * len(elemText)) for elem in self.menu: elem.rect.center = ((posx, posy)) posy += 100 self.bkgrnd, self.bkgrndRect = loadImage("background.jpg") self.bkgrndRect = self.bkgrnd.get_rect() # The Clock of the game, to manage the frame-rate self.clock = pygame.time.Clock() self.fps = 60 # We start the Sound object, playing music and sounds. self.sound = Sound() # Needed to keep track of the game if we do a pause during the game. self.app = None self.main()
def __init__(self): """ Create a new MainMenu object. :return: None """ # Setting up the main window self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Create the start button and the settings button self.start_game_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 70, 350, 100, "Start A Game") self.rand_button = SpecialButton(SCREEN_COLOR, 650, 366, 350, 100, "Disabled") self.how_to_play_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 170, 350, 100, "How to play")
def createButtons(self): self.button_list = [] for i in range(0, 3): self.button_list.append(Button(self)) self.button_list[i].setWidth(25) self.button_list[i].setHeight(2) self.button_list[i].setBackgroundColor('black') self.button_list[i].setForegroundColor('white') self.button_list[i].place(x=160, y=100 + (i * 50))
def start_scenery(): global running startb = Button(WIDTH / 2 + 70, HEIGHT / 2, screen, start) rulesb = Button(WIDTH / 2 + 70, HEIGHT / 2 - start.get_height() - 20, screen, rules) screen.blit(background, (0, 0)) startb.drawbutton() rulesb.drawbutton() screen.blit(logo, (10, 10)) # (WIDTH/2-logo.get_width()/2,0)) pygame.display.flip() while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if startb.ispressed(): choose_mode() if rulesb.ispressed(): rulesonscreen()
def win(score): clear() display = pygame.display.set_mode((400, 400)) display.fill(GREY) menu_button = Button(display, 150, 200, 75, 50, "Menu", TEXT, BLACK, GREY2) score_text = Text(display, 200, 125, "Score: " + str(score), TITLE, BLACK) title = Text(display, 200, 50, "Victory!", TITLE, BLACK) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONDOWN: if menu_button.clicked(): channel1.play(click) menu() pygame.display.update()
def lose_screen(wave_number): pygame.mixer.music.stop() pygame.mixer.Sound.play(lose_sound) display.blit(LOSE_BACKGROUND, [0, 0]) title_text = DEATH_MESSAGE title = Text(display, CENTER_X, CENTER_Y - 200, title_text, TITLE, RED) wave_text = "You Got To Wave: " + str(wave_number) wave = Text(display, CENTER_X, CENTER_Y - 100, wave_text, TITLE, RED) x = CENTER_X - 225 y = CENTER_Y start_button = Button(display, x, y, 200, 100, "MENU", TEXT, GREEN, WHITE) x = CENTER_X quit_button = Button(display, x, y, 200, 100, "QUIT", TEXT, RED, WHITE) pygame.mixer.music.load("menu_theme.mp3") pygame.mixer.music.play(-1) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONDOWN: if start_button.clicked(): pygame.mixer.music.stop() menu() elif quit_button.clicked(): pygame.quit() quit() pygame.display.flip()
def add_button(self, callback: Callable, icon_path: str, button_size: int): button = Button( callback, Rectangle( Point(self.next_button_x, self.next_button_y), Point( self.next_button_x + button_size, self.next_button_y + button_size ), ), icon_path, ) self.buttons.append(button) self.next_button_y += int(button_size * 1.5)
def decode(message): # дешифратор m = [] # в данном цикле формируем числовое представление сообщения для дальнейшей дешифровки for mess in message: # перебираем объекты из сообщения m.append(mess.row) # добавляем в список m номер строки объекта из сообщения m.append(mess.col) # добавляем в список m номер столбца объекта из сообщения # делим список пополам mc = m[0:(len(m)//2)] # первая часть списка это номера строк зашифрованного сообщения mc2 = m[(len(m)//2):(len(m))] # вторая часть списка это номера столбцов зашифрованного сообщения simbx = 150 # переменная задающая х-координату формируемым объектам, дабы они отображались друг за дружкой, а не друг на друге for i in range(len(mc)): # так как длины mc и mc2 одинаковы, то в цикле проходим от 0 до длины mc for simb in Alfavit: # перебираем символы из алфавита if simb.col == mc2[i]: # если номер столбца символа равен i-му числу из списка номеров столбцов if simb.row == mc[i]: # если номер строки символа равен i-му числу из списка номеров строк pl = Button(simbx, 290, PL_W, PL_H, simb.text) # то создаем новую кнопку с текстом символа из алфавита pl.row = simb.row # задаем свойство row новому сиволу и присваиваем ему номер строки символа из алфавита pl.col = simb.col # задаем свойство col новому сиволу и присваиваем ему номер столбца символа из алфавита pl.font = simb.font decode_message.add(pl) # добавляем новую кнопку в группу дешифрованного сообщения simbx += PL_W # прибавляем к simbx значение ширины кнопки алфавита, чтобы сдвинуть следующую кнопку в право
def encode(): # процедура шифрования mc = [] # список для номеров строк mc2 = [] # спискок для номеров столбцов for mess in message_list: # перебираем символы из сообщения mc.append(mess.row) # добавляем в список для номеров строк номер строки символа mc2.append(mess.col) # добавляем в список для номеров столбцов номер столбца символ mc += mc2 # склеиваем списки - сначала номера строк, потом номера столбцов rez_message = [] # список для результирующего сообщения simbx = 150 # начальная позиция по Х для вывода сообщения for i in range(1, len(mc), 2): # в данном цикле перебираем попарно символы из mc начиная с первого. for simb in Alfavit: # перебираем символы алфавита if simb.col == mc[i]: # если номер столбца совпадает со вторым числом из пары (перебираем попарно списком mc) if simb.row == mc[i-1]: # если номер строки совпадает с первым числом из пары pl = Button(simbx, 260, PL_W, PL_H, simb.text) # то создаем кнопку с текстом нажатой кнопки из алфавита pl.col = simb.col # новой кнопке назначаем свойства col и row и передаем pl.row = simb.row # соответствующие значения от нажатой кнопки из алфавита pl.font = simb.font encode_message_group.add(pl) # добавляем новую кнопку в группу зашифрованного сообщения rez_message.append(pl) # так же помещаем кнопку в список зашифрованного сообщения simbx += PL_W # прибавляем к simbx значение ширины кнопки алфавита, чтобы сдвинуть следующую кнопку в право return rez_message # передаем результат в виде списка
def encode(): # процедура шифрования mc = [] # список для номеров строк mc2 = [] # спискок для номеров столбцов for mess in message_list: # перебираем символы из сообщения mc.append( mess.row ) # добавляем в список для номеров строк номер строки символа mc2.append( mess.col ) # добавляем в список для номеров столбцов номер столбца символ mc += mc2 # склеиваем списки - сначала номера строк, потом номера столбцов rez_message = [] # список для результирующего сообщения simbx = 150 # начальная позиция по Х для вывода сообщения for i in range( 1, len(mc), 2 ): # в данном цикле перебираем попарно символы из mc начиная с первого. for simb in Alfavit: # перебираем символы алфавита if simb.col == mc[ i]: # если номер столбца совпадает со вторым числом из пары (перебираем попарно списком mc) if simb.row == mc[ i - 1]: # если номер строки совпадает с первым числом из пары pl = Button( simbx, 260, PL_W, PL_H, simb.text ) # то создаем кнопку с текстом нажатой кнопки из алфавита pl.col = simb.col # новой кнопке назначаем свойства col и row и передаем pl.row = simb.row # соответствующие значения от нажатой кнопки из алфавита pl.font = simb.font encode_message_group.add( pl ) # добавляем новую кнопку в группу зашифрованного сообщения rez_message.append( pl ) # так же помещаем кнопку в список зашифрованного сообщения simbx += PL_W # прибавляем к simbx значение ширины кнопки алфавита, чтобы сдвинуть следующую кнопку в право return rez_message # передаем результат в виде списка
def decode(message): # дешифратор m = [] # в данном цикле формируем числовое представление сообщения для дальнейшей дешифровки for mess in message: # перебираем объекты из сообщения m.append( mess.row) # добавляем в список m номер строки объекта из сообщения m.append(mess.col ) # добавляем в список m номер столбца объекта из сообщения # делим список пополам mc = m[0:( len(m) // 2)] # первая часть списка это номера строк зашифрованного сообщения mc2 = m[(len(m) // 2):( len(m) )] # вторая часть списка это номера столбцов зашифрованного сообщения simbx = 150 # переменная задающая х-координату формируемым объектам, дабы они отображались друг за дружкой, а не друг на друге for i in range( len(mc) ): # так как длины mc и mc2 одинаковы, то в цикле проходим от 0 до длины mc for simb in Alfavit: # перебираем символы из алфавита if simb.col == mc2[ i]: # если номер столбца символа равен i-му числу из списка номеров столбцов if simb.row == mc[ i]: # если номер строки символа равен i-му числу из списка номеров строк pl = Button( simbx, 290, PL_W, PL_H, simb.text ) # то создаем новую кнопку с текстом символа из алфавита pl.row = simb.row # задаем свойство row новому сиволу и присваиваем ему номер строки символа из алфавита pl.col = simb.col # задаем свойство col новому сиволу и присваиваем ему номер столбца символа из алфавита pl.font = simb.font decode_message.add( pl ) # добавляем новую кнопку в группу дешифрованного сообщения simbx += PL_W # прибавляем к simbx значение ширины кнопки алфавита, чтобы сдвинуть следующую кнопку в право
def one_round(difficulty): score = 0 nextb = Button(WIDTH - nextim.get_width(), HEIGHT - nextim.get_height(), screen, nextim) skipb = Button(WIDTH - nextim.get_width() - skip.get_width() - 20, HEIGHT - nextim.get_height(), screen, skip) if difficulty == 1: words = words1 else: words = words2 counter, text = 60, '60'.rjust(3) while counter > 0: for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() text = str(round(counter)).rjust(3) if counter > 0 else 'boom!' counter -= 0.1 screen.blit(background, (0, 0)) nextb.drawbutton() skipb.drawbutton() for i in range(6): screen.blit(font.render(str(words[i]), True, WHITE), (500, i * 50 + 20)) screen.blit(font.render("Score:" + str(score), True, WHITE), (30, HEIGHT / 2)) screen.blit(font.render(text, True, (0, 0, 0)), (30, 50)) if nextb.ispressed(): score += 10 words = Generate_Words(difficulty) if skipb.ispressed(): score -= 5 words = Generate_Words(difficulty) pygame.display.flip() time.sleep(0.1) return score
def run_game(): # Initialize game and create a screen object. pygame.init() game_set = Settings() #Making an instance of settings class screen = pygame.display.set_mode((game_set.screen_width, game_set.screen_height)) # Here screen has been created pygame.display.set_caption("Alien Ship Fight Game") ship_set = Ship(game_set, screen) #Making an instance of Ship class #Creating an instance to store the game_statistics game_stats = GameStatistics(game_set) # # Create an instance to store game statistics and create a scoreboard. sb = ScoreBoard(game_set,screen,game_stats) #Make a group to store bullet bullets = Group() play_button = Button(game_set,screen, "Play") ''' Creating Rows of Aliens To create a row, first create an empty group called aliens in alien_invasion.py to hold all of our aliens, and then call a function in game_functions.py to create a fleet. ''' aliens = Group() # Create the fleet of aliens. gf.create_fleet(game_set,screen,ship_set,aliens) # Set the background color #bg_color = (246, 221, 204) # Start the main loop for the game. while True: # Watch for keyboard and mouse events. gf.check_events(game_set,screen, ship_set, bullets, play_button, game_stats, aliens, sb) if game_stats.game_active: ship_set.update() gf.update_bullets(bullets, aliens, game_set,screen,ship_set, game_stats, sb ) #In the main while loop we will update the position of each alien as well gf.update_aliens(game_set,aliens , ship_set, game_stats, bullets, screen, sb) gf.update_screen(game_set, screen, ship_set, aliens, bullets, game_stats, play_button, sb)
def run_game(): # Initialize game and create a screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alien Invasion") # Set the background background = Background('Models/Space/Space1.png', [0, 0]) # Make a ship ship = Ship(screen, ai_settings) # Make the play button play_button = Button(ai_settings, screen, "Play") # Create an instance to store game statistics. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats, background) # Make a bullet group bullets = Group() # Make an alien group aliens = Group() # make a Explosion group explosions = Group() # create an alien fleet gf.create_fleet(ai_settings, screen, aliens, ship) # Start the main loop for the game while True: gf.check_events(ship, screen, bullets, stats, play_button, aliens, ai_settings) gf.update_screen(background, screen, ship, bullets, aliens, explosions, stats, play_button, sb) if stats.game_Active: ship.update() gf.update_bullets(bullets, aliens, explosions, screen, ship, ai_settings, stats, sb) gf.update_aliens(aliens, ai_settings, ship, stats, screen, bullets)
def __init__(self, keyValues, x=0, y=0, l=0, b=0, cols=3, bgColor=color(0, 0, 0, 0), keyColor=color(240)): RectangleComponent.__init__(self, x, y, l, b, col=bgColor) self.keyColor = keyColor self.keyColumns = cols self.keyWidth = (l / cols) rows = (len(keyValues) // cols) + (1 if len(keyValues) % cols != 0 else 0) self.keyHeight = (b / rows) self.keyGrid = [] for i, k in enumerate(keyValues): if (i % cols == 0): self.keyGrid.append([]) lx = self.x + (self.keyWidth * len(self.keyGrid[-1])) ly = self.y + (self.keyHeight * (len(self.keyGrid) - 1)) self.keyGrid[-1].append( Button(x=lx + 10, y=ly + 10, l=self.keyWidth - 20, b=self.keyHeight - 20, onClick=lambda: None, txt=str(k), col=color(255, 20, 20) if k == "C" else self.keyColor))
def run(): airplanes = [] destroyed_airplanes = [] airplane = Airplane(position_vector=(70, 170), speed_vector=(50, 0), num_img=0) # Cоздаем объект airplane.set_keys(pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s, pygame.K_SPACE) second_airplane = Airplane(position_vector=(1000, 170), speed_vector=(-50, 0), num_img=1) # Cоздаем объект second_airplane.set_keys(pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN, pygame.K_KP0) airplanes.append(airplane) airplanes.append(second_airplane) clock = pygame.time.Clock() # Создаем таймер для контроля фпс button_pause = Button(pos=(535, 5), path='images/buttons', image_names=('pause_off.png', 'pause_hover.png', 'pause_click.png'), function=pause, text='', w=30, h=35) interface = load_image('interface2.png', alpha_cannel=1) while len(airplanes) > 1: # главный цикл программы for e in pygame.event.get(): # цикл обработки очереди событий окна button_pause.event(e) for airplane in airplanes: airplane.event(e) if e.type == pygame.QUIT: sys.exit() # Закрытие окна программы dt = clock.tick(FPS) # Устанавливаем FPS if GAME_STATUS: for airplane in airplanes: airplane.update(dt) screen.blit(BACKGROUND, (0, 0)) if len(airplanes) > 1: airplanes[0].collide_bullet_with_airplane(airplanes[1]) airplanes[1].collide_bullet_with_airplane(airplanes[0]) for airplane in airplanes: airplane.render(screen) for airplane in airplanes: if airplane.status_airplane == False: destroyed_airplanes.append(airplane) airplanes.remove(airplane) for airplane in destroyed_airplanes: airplane.render(screen) screen.blit(interface, (0, 0)) button_pause.update(dt) button_pause.render(screen) for airplane in airplanes: airplane.render_hp(screen) pygame.display.flip() # отображаем на мониторе все, что нарисовали на экране start_game()
def pause(screen, rand_ball=False): """ This function will pause the game and give some options: 1. continue 2. restart 3. main menu :param screen: the screen the options will be drawn on. :type screen: pygame.display :param rand_ball: the custom setting for the random ball size, default is False :type rand_ball: boolean :return: None """ # Create the 3 buttons, one on top of the other continue_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 150, 350, 100, "Continue") restart_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 50, 350, 100, "Restart") main_menu_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 + 50, 350, 100, "Main Menu") be_careful_text = """Don't click on w/s/up/down keys when clicking on the continue/restart, will cause bags!""" paused = True # Stop mark clock = pygame.time.Clock() # Initialize a clock while paused: # stores the (x,y) coordinates into the variable as a tuple mouse = pygame.mouse.get_pos() for event in pygame.event.get(): # Handle the exit from game command if event.type == pygame.QUIT: pygame.quit() sys.exit() # If the "P" button was clicked: if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: paused = False # Check if the mouse is over A button if continue_button.is_over(mouse) or restart_button.is_over( mouse) or main_menu_button.is_over(mouse): # If so - change the mouse cursor pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND) # Check if the mouse left button is pressed and is on the continue button if pygame.mouse.get_pressed()[0] and continue_button.is_over( mouse): # If so - bring back the mouse cursor and continue the game pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) paused = False # Check if the mouse left button is pressed and is on the restart button if pygame.mouse.get_pressed()[0] and restart_button.is_over(mouse): # If so - create a new Game object and start it game = Game(screen, rand_ball) game.start() # Check if the mouse left button is pressed and is on the main_menu button if pygame.mouse.get_pressed()[0] and main_menu_button.is_over( mouse): # If so - create a new MainMenu object and start it main_menu_object = MainMenu() main_menu_object.start() # Else - bring the mouse cursor to normal else: pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) # Fill the bg color screen.fill(SCREEN_COLOR) # Draw the buttons using their draw function continue_button.draw(screen, (0, 0, 0)) restart_button.draw(screen, (0, 0, 0)) main_menu_button.draw(screen, (0, 0, 0)) message_to_screen(screen, be_careful_text, 25, "red", (350, 100), True) # Updating the window pygame.display.flip() # Number of frames per sec clock.tick(60)
class MainMenu: """ Main menu class with 6 attributes: 1. screen - the screen of the main menu. 2. start_game_button - a button to start a game. 3. rand_button - a button for the custom option random ball size. 4. how_to_play_button - a button for the how to play screen. The class represent a main menu. """ # A constructor def __init__(self): """ Create a new MainMenu object. :return: None """ # Setting up the main window self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Create the start button and the settings button self.start_game_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 70, 350, 100, "Start A Game") self.rand_button = SpecialButton(SCREEN_COLOR, 650, 366, 350, 100, "Disabled") self.how_to_play_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 170, 350, 100, "How to play") def start(self): """ This function will open the main menu. :return: None """ # General setup pygame.init() # Initialize the icon picture pygame.display.set_icon(PONG_ICON) pygame.display.set_caption("Pong") # Chose the name on the window clock = pygame.time.Clock() # Initialize a clock while True: # stores the (x,y) coordinates into the variable as a tuple mouse = pygame.mouse.get_pos() # Handling input for event in pygame.event.get(): # Handle the exit from game command if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if the mouse is over A button if self.start_game_button.is_over( mouse) or self.rand_button.is_over( mouse) or self.how_to_play_button.is_over(mouse): # If so - change the mouse cursor pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND) # Check if the mouse left button is pressed and is on the start button if pygame.mouse.get_pressed( )[0] and self.start_game_button.is_over(mouse): # If so - bring back the mouse cursor and start a game pygame.mouse.set_system_cursor( pygame.SYSTEM_CURSOR_ARROW) # If the random option selected - make a game with random option if self.rand_button.text_color == "green": game = Game(self.screen, rand_ball=True) # If not - make a game without the random option else: game = Game(self.screen) game.start() # Check if the mouse left button is pressed and is on the rand button if pygame.mouse.get_pressed( )[0] and self.rand_button.is_over(mouse): # If so - change the text and color self.rand_button.change_mode() # Check if the mouse left button is pressed and is on the how to play button if pygame.mouse.get_pressed( )[0] and self.how_to_play_button.is_over(mouse): # If so - open how to play screen how_to_play(self.screen) # Else - bring back the mouse cursor to normal else: pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) # Fill the bg color self.screen.fill(SCREEN_COLOR) # Draw the buttons self.start_game_button.draw(self.screen, (0, 0, 0)) self.how_to_play_button.draw(self.screen, (0, 0, 0)) self.rand_button.draw(self.screen) # Message to screen with what is the setting to chose. message_to_screen(self.screen, "Random ball size: ", 50, "black", (320, 385)) # Updating the window pygame.display.flip() # Number of frames per sec clock.tick(60)
def menu(): display = pygame.display.set_mode((WIDTH, HEIGHT)) display.fill(GREY) display.blit(face, (180, 150)) title_text = "Minesweeper" title = Text(display, int(WIDTH / 2), int((HEIGHT / 2)) - 100, title_text, TITLE, (0, 0, 0)) quit_button = Button(display, int(WIDTH / 2) - 50, 300, 100, 50, "QUIT", TITLE, RED, BLACK) easy = Button(display, 60, 200, 75, 50, "Easy", TEXT, GREEN, BLACK) medium = Button(display, 160, 200, 75, 50, "Medium", TEXT, ORANGE, BLACK) hard = Button(display, 260, 200, 75, 50, "Hard", TEXT, RED, BLACK) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONDOWN: if easy.clicked(): channel1.play(click) play(0) elif medium.clicked(): channel1.play(click) play(1) elif hard.clicked(): channel1.play(click) play(2) elif quit_button.clicked(): channel1.play(click) pygame.quit() quit() pygame.display.flip()
def end_game(screen, winner_player, rand_ball=False): """ This function will end the game, show the winner and give 2 options: 1. another game 2. main menu :param screen: the screen the options and the winner_player will be drawn on. :type screen: pygame.display :param winner_player: the player that won the game :type winner_player: Player :param rand_ball: the custom setting for the random ball size, default is False :type rand_ball: boolean :return: None """ text = winner_player.side + " player is the winner!!" # The text that will be displayed # Create a buttons another_game_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 - 50, 350, 100, "Another game") main_menu_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 + 50, 350, 100, "Main Menu") clock = pygame.time.Clock() # Initialize a clock while True: # stores the (x,y) coordinates into the variable as a tuple mouse = pygame.mouse.get_pos() for event in pygame.event.get(): # Handle the exit from game command if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if the mouse is over A button if another_game_button.is_over(mouse) or main_menu_button.is_over( mouse): # If so - change the mouse cursor pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND) # Check if the mouse left button is pressed and is on the another_game button if pygame.mouse.get_pressed( )[0] and another_game_button.is_over(mouse): # If so - bring back the mouse cursor and start a new game pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) game = Game(screen, rand_ball) game.start() # Check if the mouse left button is pressed and is on the main_menu button if pygame.mouse.get_pressed()[0] and main_menu_button.is_over( mouse): # If so - bring back the mouse cursor and open the main menu main_menu_object = MainMenu() main_menu_object.start() # Else - bring the mouse cursor to normal else: pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) # Fill the bg color screen.fill(SCREEN_COLOR) # Draw the buttons another_game_button.draw(screen, (0, 0, 0)) main_menu_button.draw(screen, (0, 0, 0)) message_to_screen(screen, text, 60, "black", (SCREEN_WIDTH / 2 - 340, SCREEN_HEIGHT / 2 - 180)) # Updating the window pygame.display.update() # Number of frames per sec clock.tick(60)
def how_to_play(screen): """ This function will show how to play the game and give the option to get to the main menu. :param screen: the screen the options will be drawn on. :type screen: pygame.display :return: None """ # Create the 1 button main_menu_button = Button("white", SCREEN_WIDTH / 2 - 170, SCREEN_HEIGHT / 2 + 50, 350, 100, "Main Menu") # Create text how_to_play_text = """The goal of the game is to make sure the ball \nwon't leave your side of the field, \nand leave the other player side of the field. The winner is the first person to get to 13 points!! Left player keys: W for up. S for down. Right player keys: UP-arrow for up. DOWN-arrow for down. P key for pause. R for restart.""" # Position of the text x_pos = SCREEN_WIDTH / 2 - 300 y_pos = SCREEN_HEIGHT / 2 - 200 clock = pygame.time.Clock() # Initialize a clock while True: # stores the (x,y) coordinates into the variable as a tuple mouse = pygame.mouse.get_pos() for event in pygame.event.get(): # Handle the exit from game command if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if the mouse is over the button if main_menu_button.is_over(mouse): # If so - change the mouse cursor pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND) # Check if the mouse left button is pressed and is on the main_menu button if pygame.mouse.get_pressed()[0] and main_menu_button.is_over( mouse): # If so - create a new MainMenu object and start it main_menu_object = MainMenu() main_menu_object.start() # Else - bring the mouse cursor to normal else: pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) # Fill the bg color screen.fill(SCREEN_COLOR) # Draw the button using it draw function main_menu_button.draw(screen, (0, 0, 0)) # Messages the screen how to play message_to_screen(screen, how_to_play_text, 30, "black", (x_pos, y_pos), True) # Updating the window pygame.display.flip() # Number of frames per sec clock.tick(60)
def play(difficulty): clock = 0 generate_grid(SIZES[difficulty]) display.fill(GREY) empties.draw(display) menu_button = Button(display, 0, 0, 100, 0, "Menu", TEXT, BLACK, GREY2) time_text = Text(display, 101, 0, "Your Time: " + str(clock), TEXT, RED2) org_time = time.time() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONDOWN: if menu_button.clicked(): channel1.play(click) lose() pos = pygame.mouse.get_pos() for tile in tiles: if tile.rect.collidepoint(pos): channel1.play(click) tile.clicked() won = True for tile in tiles: if tile.state != 3 and tile.action == False: won = False if won == True: score = 0 for _ in tiles: score += 1 score = (score * 2) - clock win(score) tiles.update() tiles.draw(display) # blit here display.blit(bar, (0, 0)) menu_button = Button(display, 0, 0, 100, 25, "Menu", TEXT, BLACK, GREY2) time_text = Text(display, 112, 12, str(clock), TEXT, RED2) if len(lost) != 0: for t in tiles: if t.state == 3 and t.image != flag: t.image = mine tiles.update() tiles.draw(display) pygame.display.flip() channel2.play(defeat) time.sleep(2) lose() if (time.time() - org_time) > 1: clock += 1 org_time = time.time() pygame.display.update()
# ADD BUTTONS for button in buttons: button.draw(surface) # DRAW LINES AND NODES grid.draw(surface) # Pygame Objects pathfinding_algorithm = None grid = Grid(screen.get_width(), screen.get_height()) start_button = Button((255, 0, 0), (800, 0), 200, 50, 'Start.Point') end_button = Button((0, 255, 0), (800, 100), 200, 50, 'End.Point') edit_button = Button((150, 0, 155), (800, 200), 200, 50, 'Edit.Walls') calculate_button = Button((255, 100, 255), (800, 300), 200, 50, 'Calculate.Path') clear_button = Button((100, 150, 255), (800, 400), 200, 50, 'Clear.Grid') astar_button = Algorithm_Button((23, 245, 100), (800, 500), 200, 50, AStar, 'A*') jps_button = Algorithm_Button((23, 245, 100), (800, 600), 200, 50, JPS, 'A*.JPS') djikstra_button = Algorithm_Button((23, 245, 100), (800, 700), 200, 50, Djikstra, 'Djikstra') # Mainloop
def playGame(self, win): #main function that runs the game #creates buttons for roll dice and quit rollButton = Button(win, Point(720.0, 45), 80, 30, "Roll Dice") quitButton = Button(win, Point(720.0, 510), 80, 30, "QUIT") rollButton.activate() quitButton.activate() pt = win.getMouse()#Gets the users click on which button turn = 0 #variable used to create turns for each player counter = 0 #variable used to keep count of the times the user gets a double die while not quitButton.clicked(pt): #while the player doesn't click Quit the game continues if turn == 0: #starts player red's turn if rollButton.clicked(pt): #checks if the player clicks roll dice, if true then their turn proceeds self.board.playerTurn("Red", win) #calls the function that draws in the menu who's player's turn it is dice1, dice2 = self.rollDice(win) #calls the function to roll the dice and returns the values for each one if self.players[0].returnChips() > 0:#calls the function returnChips() to determine available chips in the player's home, if true then proceeds checkMove, dice = self.startHome(dice1, dice2, "red", win) #calls function startHome to check if the player rolled a 5 on either dice and returns the value of the other if checkMove:#true if the player rolled a 5 on either die self.players[0].MovePiece(self.players[0].player, dice, dice1, dice2, "red", #calls function that moves the player's piece according to the dice value returned after rolling 5 self.players[0].returnSteps(), win) self.eatPlayer("red", win) #calls function that checks if the player ate another player elif self.players[0].returnChips() == 0: #calls function that checks the players available chips, if true then proceeds dice = dice1 + dice2 #sums both die values self.players[0].MovePiece(self.players[0].player, dice, dice1, dice2, "red", # calls function that moves the player's piece according to the sum of both die self.players[0].returnSteps(), win) self.eatPlayer("red", win) #calls function that checks if the player ate another player if self.doubleTurn(dice1, dice2): #calls funciton to check both die values, if true then proceeds to create another turn counter += 1 #adds one to counter to keep track of doubles turn = 0 #sets turn = 0 so that its player Red's turn again #prints a text in the menu letting the player know its their turn again turnAgain = Text(Point(720.0, 300), "Your turn again") turnAgain.setStyle("bold") turnAgain.setSize(16) turnAgain.draw(win) win.getMouse() turnAgain.undraw() if counter == 2: #once counter hits 2, the player's turn is skipped turn += 1 #adds one to turn to continue to next player counter = 0 #resets counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") #prints in the menu that it's the next player's turn skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() else: #if no double was rolled then proceeds turn += 1 #adds one to turn to continue to next player counter = 0 #resets counter = 0 skip = Text(Point(720.0, 300), "Next player's turn")#prints in the menu that it's the next player's turn skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() if self.players[0].playerWon(self.players[0].piecesInHome(), win): #calls function that checks if the player won win.getMouse() win.close() #closes the window if player won pt = win.getMouse() #resets the click for the next player elif turn == 1: #blue player's turn, everything works as mentioned above if rollButton.clicked(pt): self.board.playerTurn("Blue", win) dice1, dice2 = self.rollDice(win) if self.players[1].returnChips() > 0: checkMove, dice = self.startHome(dice1, dice2, "blue", win) if checkMove: self.players[1].MovePiece(self.players[1].player, dice, dice1, dice2, "blue", self.players[1].returnSteps(), win) self.eatPlayer("blue", win) elif self.players[1].returnChips() == 0: self.players[1].MovePiece(self.players[1].player, dice, dice1, dice2, "blue", self.players[1].returnSteps(), win) self.eatPlayer("blue", win) if self.doubleTurn(dice1, dice2): counter += 1 turn = 1 turnAgain = Text(Point(720.0, 300), "Your turn again") turnAgain.setStyle("bold") turnAgain.setSize(16) turnAgain.draw(win) win.getMouse() turnAgain.undraw() if counter == 2: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() else: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() if self.players[1].playerWon(self.players[1].piecesInHome(), win): win.getMouse() win.close() pt = win.getMouse() elif turn == 2: #green player's turn, everything works as mentioned above if rollButton.clicked(pt): self.board.playerTurn("Green", win) dice1, dice2 = self.rollDice(win) if self.players[2].returnChips() > 0: checkMove, dice = self.startHome(dice1, dice2, "green", win) if checkMove: self.players[2].MovePiece(self.players[2].player, dice, dice1, dice2, "green", self.players[2].returnSteps(), win) self.eatPlayer("green", win) elif self.players[2].returnChips() == 0: dice = dice1 + dice2 self.players[2].MovePiece(self.players[2].player, dice, dice1, dice2, "green", self.players[2].returnSteps(), win) self.eatPlayer("green", win) if self.doubleTurn(dice1, dice2): counter += 1 turn = 2 turnAgain = Text(Point(720.0, 300), "Your turn again") turnAgain.setStyle("bold") turnAgain.setSize(16) turnAgain.draw(win) win.getMouse() turnAgain.undraw() if counter == 2: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() else: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() if self.players[2].playerWon(self.players[2].piecesInHome(), win): win.getMouse() win.close() pt = win.getMouse() elif turn == 3: #yellow player's turn, everything works as mentioned above if rollButton.clicked(pt): self.board.playerTurn("Yellow", win) dice1, dice2 = self.rollDice(win) if self.players[3].returnChips() > 0: checkMove, dice = self.startHome(dice1, dice2, "yellow", win) if checkMove: self.players[3].MovePiece(self.players[3].player, dice, dice1, dice2, "yellow", self.players[3].returnSteps(), win) self.eatPlayer("yellow", win) elif self.players[3].returnChips() == 0: self.players[3].MovePiece(self.players[3].player, dice, dice1, dice2, "yellow", self.players[3].returnSteps(), win) self.eatPlayer("yellow", win) if self.doubleTurn(dice1, dice2): counter += 1 turn = 3 turnAgain = Text(Point(720.0, 300), "Your turn again") turnAgain.setStyle("bold") turnAgain.setSize(16) turnAgain.draw(win) win.getMouse() turnAgain.undraw() if counter == 2: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() else: turn += 1 counter = 0 skip = Text(Point(720.0, 300), "Next player's turn") skip.setStyle("bold") skip.setSize(16) skip.draw(win) win.getMouse() skip.undraw() if self.players[3].playerWon(self.players[3].piecesInHome(), win): win.getMouse() win.close() pt = win.getMouse() elif turn == 4: #keeps the loop going starting back at the first player's turn turn = 0 pt = win.getMouse() #resets click
class Game(): """A class that holds the entire game""" # pythons way of stating that something is being done to a specific object is called "self" def __init__(self): pygame.init() self.phase = START self.current_index = 0 self.timer = 0 self.time_limit = 40 self.color_index = 0 self.total_colors = 4 self.total_score = 0 self.color_list = [] self.get_color_list(self.total_colors) self.difficulty = None self.play_time_limit = 4 * FPS self.play_timer = self.play_time_limit self.red_box = ColorBox(RED) self.yellow_box = ColorBox(YELLOW) self.blue_box = ColorBox(BLUE) self.green_box = ColorBox(GREEN) self.easy_level = Button(EASY_BUTTON) self.easy_level.set_pos(350, 250) self.hard_level = Button(HARD_BUTTON) self.hard_level.set_pos(350, 325) self.back_button = Button(BACK_BUTTON) self.back_button.set_pos(10, 10) self.quit_button = Button(QUIT_BUTTON) self.quit_button.set_pos(10, 10) self.replay_button = Button(REPLAY_BUTTON) self.replay_button.set_pos(340, 350) self.rules_button = Button(RULES_BUTTON) self.rules_button.set_pos(340, 400) self.failed_buttons = pygame.sprite.Group() self.failed_buttons.add(self.replay_button) self.start_buttons = pygame.sprite.Group() self.start_buttons.add(self.easy_level) self.start_buttons.add(self.hard_level) self.start_buttons.add(self.rules_button) self.rules_buttons = pygame.sprite.Group() self.rules_buttons.add(self.back_button) self.game_buttons = pygame.sprite.Group() self.game_buttons.add(self.quit_button) self.font_name = pygame.font.match_font('arial') self.total_score_font = pygame.font.Font(self.font_name, 72) self.other_font = pygame.font.Font(self.font_name, 30) self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) self.running = True self.displaying_color = True self.backdrop1 = Backdrop("start_game") self.backdrop2 = Backdrop("rules") self.backdrop3 = Backdrop("game_page") self.backdrop4 = Backdrop("failed_page") self.failed_backdrop = pygame.sprite.Group() self.failed_backdrop.add(self.backdrop4) self.game_backdrop = pygame.sprite.Group() self.game_backdrop.add(self.backdrop3) self.rules_backdrop = pygame.sprite.Group() self.rules_backdrop.add(self.backdrop2) self.start_backdrop = pygame.sprite.Group() self.start_backdrop.add(self.backdrop1) self.boxes = pygame.sprite.Group() self.boxes.add(self.green_box) self.boxes.add(self.yellow_box) self.boxes.add(self.blue_box) self.boxes.add(self.red_box) def reset_display(self): self.timer = 0 self.displaying_color = True self.current_index = 0 self.color_index = 0 self.phase = DISPLAY def reset_game(self): self.phase = START self.current_index = 0 self.timer = 0 self.time_limit = 40 self.color_index = 0 self.total_colors = 4 self.total_score = 0 self.get_color_list(self.total_colors) self.displaying_color = True def get_color_list(self, squares_per_level): """returns random list of colors""" color_options = [RED, YELLOW, BLUE, GREEN] self.color_list.clear() while len(self.color_list) < squares_per_level: color = random.choice(color_options) self.color_list.append(color) def update_color_list(self): color_options = [RED, YELLOW, BLUE, GREEN] self.color_list.append(random.choice(color_options)) def update_timer(self): if self.play_timer > 0: self.play_timer -= 1 else: self.phase = FAILED def display_color_list(self): if self.displaying_color == True: self.timer += 1 if self.timer == self.time_limit: self.timer = 0 color = self.color_list[self.color_index] self.color_index += 1 if color == RED: self.red_box.activate() elif color == GREEN: self.green_box.activate() elif color == YELLOW: self.yellow_box.activate() elif color == BLUE: self.blue_box.activate() if self.color_index == len(self.color_list): self.displaying_color = False self.phase = PLAY def update(self): """Updates the game""" self.clock.tick(FPS) self.screen.fill((255, 222, 222)) self.handle_input() if self.phase == START: self.start_backdrop.draw(self.screen) self.start_buttons.update() self.start_buttons.draw(self.screen) elif self.phase == RULES: self.rules_backdrop.update() self.rules_backdrop.draw(self.screen) self.rules_buttons.update() self.rules_buttons.draw(self.screen) elif self.phase == FAILED: self.failed_backdrop.update() self.failed_backdrop.draw(self.screen) self.failed_buttons.update() self.failed_buttons.draw(self.screen) text_surface = self.total_score_font.render( str(self.total_score), True, (0, 0, 0)) text_rect = text_surface.get_rect() text_rect.midtop = (350, 200) self.screen.blit(text_surface, text_rect) elif self.phase == DISPLAY: self.display_color_list() self.boxes.update() self.boxes.draw(self.screen) self.game_buttons.update() self.game_buttons.draw(self.screen) text_surface = self.other_font.render("Watch the computer", True, (0, 0, 0)) text_rect = text_surface.get_rect() text_rect.midtop = (400, 550) self.screen.blit(text_surface, text_rect) elif self.phase == PLAY: self.boxes.update() self.boxes.draw(self.screen) self.game_buttons.update() self.game_buttons.draw(self.screen) text_surface = self.other_font.render("Your turn", True, (0, 0, 0)) text_rect = text_surface.get_rect() text_rect.midtop = (400, 550) self.screen.blit(text_surface, text_rect) self.update_timer() text_surface = self.total_score_font.render( "Time Left: " + str(self.play_timer // FPS), True, (0, 0, 0)) text_rect = text_surface.get_rect() text_rect.midtop = (400, 100) self.screen.blit(text_surface, text_rect) pygame.display.flip() def handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if self.phase == START: for sprite in self.start_buttons: if sprite.rect.collidepoint(pos): if sprite.button_type == HARD_BUTTON: self.phase = DISPLAY self.difficulty = HARD elif sprite.button_type == EASY_BUTTON: self.phase = DISPLAY self.difficulty = EASY elif sprite.button_type == RULES_BUTTON: self.phase = RULES elif self.phase == PLAY: for sprite in self.boxes: if sprite.rect.collidepoint(pos): sprite.activate() if sprite.color == self.color_list[ self.current_index]: self.current_index += 1 self.play_timer = self.play_time_limit if self.current_index == len(self.color_list): self.total_colors += 1 self.total_score += 1 if self.difficulty == HARD: self.get_color_list(self.total_colors) elif self.difficulty == EASY: self.update_color_list() self.reset_display() else: self.phase = FAILED for sprite in self.game_buttons: if sprite.rect.collidepoint(pos): if sprite.button_type == QUIT_BUTTON: self.phase = START self.reset_game() elif self.phase == RULES: for sprite in self.rules_buttons: if sprite.rect.collidepoint(pos): if sprite.button_type == BACK_BUTTON: self.phase = START elif self.phase == FAILED: for sprite in self.failed_buttons: if sprite.rect.collidepoint(pos): if sprite.button_type == REPLAY_BUTTON: self.phase = START elif self.phase == DISPLAY: for sprite in self.game_buttons: if sprite.rect.collidepoint(pos): if sprite.button_type == QUIT_BUTTON: self.phase = START self.reset_game()
def __init__(self): pygame.init() self.phase = START self.current_index = 0 self.timer = 0 self.time_limit = 40 self.color_index = 0 self.total_colors = 4 self.total_score = 0 self.color_list = [] self.get_color_list(self.total_colors) self.difficulty = None self.play_time_limit = 4 * FPS self.play_timer = self.play_time_limit self.red_box = ColorBox(RED) self.yellow_box = ColorBox(YELLOW) self.blue_box = ColorBox(BLUE) self.green_box = ColorBox(GREEN) self.easy_level = Button(EASY_BUTTON) self.easy_level.set_pos(350, 250) self.hard_level = Button(HARD_BUTTON) self.hard_level.set_pos(350, 325) self.back_button = Button(BACK_BUTTON) self.back_button.set_pos(10, 10) self.quit_button = Button(QUIT_BUTTON) self.quit_button.set_pos(10, 10) self.replay_button = Button(REPLAY_BUTTON) self.replay_button.set_pos(340, 350) self.rules_button = Button(RULES_BUTTON) self.rules_button.set_pos(340, 400) self.failed_buttons = pygame.sprite.Group() self.failed_buttons.add(self.replay_button) self.start_buttons = pygame.sprite.Group() self.start_buttons.add(self.easy_level) self.start_buttons.add(self.hard_level) self.start_buttons.add(self.rules_button) self.rules_buttons = pygame.sprite.Group() self.rules_buttons.add(self.back_button) self.game_buttons = pygame.sprite.Group() self.game_buttons.add(self.quit_button) self.font_name = pygame.font.match_font('arial') self.total_score_font = pygame.font.Font(self.font_name, 72) self.other_font = pygame.font.Font(self.font_name, 30) self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) self.running = True self.displaying_color = True self.backdrop1 = Backdrop("start_game") self.backdrop2 = Backdrop("rules") self.backdrop3 = Backdrop("game_page") self.backdrop4 = Backdrop("failed_page") self.failed_backdrop = pygame.sprite.Group() self.failed_backdrop.add(self.backdrop4) self.game_backdrop = pygame.sprite.Group() self.game_backdrop.add(self.backdrop3) self.rules_backdrop = pygame.sprite.Group() self.rules_backdrop.add(self.backdrop2) self.start_backdrop = pygame.sprite.Group() self.start_backdrop.add(self.backdrop1) self.boxes = pygame.sprite.Group() self.boxes.add(self.green_box) self.boxes.add(self.yellow_box) self.boxes.add(self.blue_box) self.boxes.add(self.red_box)
) # инициализация шрифтов обязательна, иначе модуль font не будет работать ff = font.Font('fonts/Segoe Print Regular.ttf', 23) Alfavit = Group() # группа алфавита message_group = Group() # группа кнопок сообщения message_list = [ ] # данный список нужен для передачи сообщения в дешифрующую функцию encode_message_group = Group() # группа кнопок зашифрованного сообщения button_group = Group() # группа кнопок управления decode_message = Group() # группа кнопок дешифрованного сообщения # добавляем кнопки с помощью модуля Button pl = Button(x=300, y=30, width=175, height=35, text='Зашифровать', text_size=32, color=Color("#bf3030")) button_group.add(pl) pl = Button(300, 70, 175, 35, 'Дешифровать', 32, Color("#bf3030")) button_group.add(pl) pl = Button(300, 110, 175, 35, 'Стереть', 32, Color("#bf3030")) button_group.add(pl) pl = Button(300, 150, 175, 35, 'Показать коды', 32, Color("#bf3030"),
def options(self): pygame.event.clear() texts = ["Audio", "Sounds", "Music", "Back"] length = len(texts) textsPos = [(320, 100), (100, 200), (100, 300), (500, 450)] elements = [] for i in range(length): elements.append(Button(texts[i], "Dearest.ttf", white)) elements[i].rect.topleft = textsPos[i] bar1, bar1Rect = loadImage("barSound.jpg") bar2, bar2Rect = loadImage("barSound.jpg") bar1Rect.topleft = (300, 220) bar2Rect.topleft = (300, 320) bars = [bar1Rect, bar2Rect] # X coordinates, relative to the bar's, of beginning and ending # of each volume cursor. MIN_VOLUME = 15 MAX_VOLUME = 240 # X absolute coordinates of the volume cursor. MIN = bars[0].x + MIN_VOLUME MAX = bars[0].x + MAX_VOLUME cursor1, cursor1Rect = loadImage("cursorSound.png") cursor2, cursor2Rect = loadImage("cursorSound.png") cursor1Rect.topleft = \ (bar1Rect.x + 225 * self.sound.soundVolume, bar1Rect.y - 23) cursor2Rect.topleft = \ (bar2Rect.x + 225 * self.sound.musicVolume, bar2Rect.y - 23) cursors = [cursor1Rect, cursor2Rect] while 1: self.screen.blit(self.bkgrnd, self.bkgrndRect) self.screen.blit(bar1, bar1Rect) self.screen.blit(bar2, bar2Rect) self.screen.blit(cursor1, cursors[0]) self.screen.blit(cursor2, cursors[1]) for i in range(length): self.screen.blit(elements[i].surface, elements[i].rect) for event in pygame.event.get(): if event.type == QUIT: self.quitGame() elif event.type == MOUSEBUTTONDOWN: mousex, mousey = pygame.mouse.get_pos() for i in range(len(cursors)): if cursors[i].collidepoint((mousex, mousey)): while pygame.event.poll().type != MOUSEBUTTONUP: mousex, mousey = pygame.mouse.get_pos() if MIN <= mousex <= MAX: cursors[i].centerx = mousex elif mousex > bars[i].x + MAX_VOLUME: cursors[i].centerx = bars[i].x + MAX_VOLUME else: cursors[i].centerx = bars[i].x + MIN_VOLUME volume = cursors[i].centerx - MIN if volume != 0: volume = (volume / 2.25) / 100.0 assert (0.0 <= volume <= 1.0) if i == 0: self.sound.soundVolume = volume self.sound.playPutCard() elif i == 1: self.sound.musicVolume = volume self.sound.update() self.screen.blit(self.bkgrnd, self.bkgrndRect) self.screen.blit(bar1, bar1Rect) self.screen.blit(bar2, bar2Rect) self.screen.blit(cursor1, cursors[0]) self.screen.blit(cursor2, cursors[1]) for j in range(4): self.screen.blit(elements[j].surface,\ elements[j].rect) pygame.display.flip() if elements[3].rect.collidepoint((mousex, mousey)): self.main() pygame.display.update()
window = set_mode(SIZE) screen = Surface(SIZE) font.init() # инициализация шрифтов обязательна, иначе модуль font не будет работать ff = font.Font('fonts/Segoe Print Regular.ttf', 23) Alfavit = Group() # группа алфавита message_group = Group() # группа кнопок сообщения message_list = [] # данный список нужен для передачи сообщения в дешифрующую функцию encode_message_group = Group() # группа кнопок зашифрованного сообщения button_group = Group() # группа кнопок управления decode_message = Group() # группа кнопок дешифрованного сообщения # добавляем кнопки с помощью модуля Button pl = Button(x=300, y=30, width=175, height=35, text='Зашифровать', text_size=32, color=Color("#bf3030")) button_group.add(pl) pl = Button(300, 70, 175, 35, 'Дешифровать', 32, Color("#bf3030")) button_group.add(pl) pl = Button(300, 110, 175, 35, 'Стереть', 32, Color("#bf3030")) button_group.add(pl) pl = Button(300, 150, 175, 35, 'Показать коды', 32, Color("#bf3030"), alt_text='Показать текст') button_group.add(pl) x, y = 35, 30 col, row = 1, 1 # в цикле ниже создаем алфавитную таблицу for i in ALFAVIT: # перебираем символы алфавита pl = Button(x=x, y=y, width=PL_W, height=PL_H, text=i, color=(Color('#300571'))) # создаем новую кнопку pl.col = col # задаем кнопке новое свойство col - это номер столбца в котором будет расположена кнопка pl.row = row # задаем кнопке новое свойство row - это номер строки в которой будет расположена кнопка
def main(): #Initialize Pygame pygame.init() #Create the display and caption the window SCREEN = pygame.display.set_mode((800,600)) pygame.display.set_caption("Rocket to the Moon") #Create the clock object and fps clock = pygame.time.Clock() fps = 60 #Initialize phase phase = 0 #Create an addText function def addText(text, pos, size, color): FONT = pygame.font.SysFont('calibri', size) TEXT = FONT.render(text, 5, color) SCREEN.blit(TEXT, pos) #Create the sprite lists allSprites = pygame.sprite.Group() rocket_list = pygame.sprite.Group() # This is a sloppy sprite list made for the intro for the rocket. asteroids = pygame.sprite.Group() #Create an instance of the background space = Space(SCREEN) #Create the rocket rocket = Rocket() allSprites.add(rocket) rocket_list.add(rocket) #Create the lives images life = pygame.image.load("./assets/rocket.png") life = pygame.transform.scale(life, (20, 30)) def showLives(): if rocket.lives == 3: SCREEN.blit(life, (700, 550)) SCREEN.blit(life, (740, 550)) SCREEN.blit(life, (780, 550)) elif rocket.lives == 2: SCREEN.blit(life, (740, 550)) SCREEN.blit(life, (780, 550)) elif rocket.lives == 1: SCREEN.blit(life, (780, 550)) #Create the asteroids for i in range(8): asteroid = Asteroid() allSprites.add(asteroid) asteroids.add(asteroid) asteroid.shuffle() #Create the intro buttons playButton = Button(SCREEN, 'rect', (165, 485), (150, 75), GREEN) quitButton = Button(SCREEN, 'rect', (485, 485), (150, 75), RED) def buttons(): playButton.draw() quitButton.draw() playButton.addText('Play', 'calibri', 40, (0,0,0)) quitButton.addText('Quit', 'calibri', 40, (0,0,0)) #When the mouse touches the play button if playButton.touching(pygame.mouse.get_pos()): playButton.detail = (0,150,0) else: playButton.detail = GREEN playButton.bevel((0,150,0), 5, ['left', 'bottom']) #When the mouse touches the quit button if quitButton.touching(pygame.mouse.get_pos()): quitButton.detail = (150, 0, 0) else: quitButton.detail = RED quitButton.bevel((150,0,0), 5, ['left', 'bottom']) #Create the intro def intro(): addText("Rocket", (270, 100), 100, RED) addText("to the", (230, 200), 60, BLUE) addText("Moon", (350, 175), 120, GREEN) buttons() #Create the startGame def startGame(): rocket.rect.x = 350 rocket.rect.y = 600 def rocketIntro(): rocket_list.draw(SCREEN) if rocket.rect.y != 500: rocket.rect.y -= 2 def play(): rocket.move() for asteroid in asteroids: asteroid.scroll() allSprites.draw(SCREEN) showLives() #Main pygame loop while True: space.draw() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: if phase == 0 and quitButton.touching(pygame.mouse.get_pos()): pygame.quit() sys.exit() if phase == 0 and playButton.touching(pygame.mouse.get_pos()): phase = 1 startGame() if phase == 0: intro() elif phase == 1: rocketIntro() if rocket.rect.y == 500: phase = 2 elif phase == 2: play() collideList = pygame.sprite.spritecollide(rocket, asteroids, False) if collideList: rocket.explode() pygame.display.update() clock.tick(fps)
def choose_mode(): global running num1b = Button(WIDTH / 2 - num1.get_width() - 30, 100, screen, num1, num1pressed) num2b = Button(WIDTH / 2 + 30, 100, screen, num2, num2pressed) star = Slider(WIDTH / 2 - stars[0].get_width() / 2, 300, screen, *stars) startb = Button(WIDTH - start.get_width(), HEIGHT - start.get_height(), screen, start) numberofteams = 0 difficulty = 0 while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() screen.blit(background, (0, 0)) screen.blit(text1, (WIDTH / 2 - text1.get_width() / 2, 0)) screen.blit(text2, (WIDTH / 2 - text2.get_width() / 2, 250)) num1b.drawbutton() num2b.drawbutton() startb.drawbutton() star.drawbutton() screen.blit(font.render(str(numberofteams), True, WHITE), (0, HEIGHT / 2 + 50)) screen.blit(font.render(str(difficulty), True, WHITE), (0, HEIGHT / 2 + 100)) pygame.display.flip() ispressed = star.ispressed() if not ispressed == 0: difficulty = ispressed if num1b.ispressed(): num2b.currentim = num2b.image numberofteams = 1 if num2b.ispressed(): num1b.currentim = num1b.image numberofteams = 2 if startb.ispressed() and difficulty > 0 and numberofteams > 0: Game(difficulty, numberofteams)