Create menu and difficulty in pygame

0

I have everything ready, I just need to create the menu and I do not know where to put it, the complete code is this

import pygame, sys, os, random
from pygame.locals import *

pygame.init()
#Se crea la ventana y le damos un titulo
screen = pygame.display.set_mode((397,660))
pygame.display.set_caption('Mastermind!')
#Se asignan los colores a utilizar y los guardamos con sus nombres 
respectivos
GREY = (127,127,127)
BLACK = (0,0,0)
WHITE = (255,255,255)
font = pygame.font.SysFont('agencyfb', 24)
clock = pygame.time.Clock()

#Carga las imagenes del juego en general data
def Cargar_Imagen(name, colorkey=None): 
  #Carga y guarda las imagenes de la carpeta Diseño
  fullname = os.path.join('data', name)
  try:
    image = pygame.image.load(fullname)
    #Muestra un error si la imagen no es encontrada y dice el nombre de la imagen faltante
  except pygame.error, message:
    print 'No se puede cargar imagen:', name
    raise SystemExit, message
  if colorkey is not None:
    if colorkey is -1:
        colorkey = image.get_at((0,0))
    image.set_colorkey(colorkey, RLEACCEL)
  return image, image.get_rect()

class Boton_Colores(pygame.sprite.Sprite):
    def __init__(self,image):
      pygame.sprite.Sprite.__init__(self)
      self.image, self.rect = Cargar_Imagen(image)
    def setCords(self,x,y):
      self.rect.topleft = x,y
      screen.blit(self.image, (x,y))
    def pressed(self,mouse):
       if mouse[0] > self.rect.topleft[0]:
          if mouse[1] > self.rect.topleft[1]:
              if mouse[0] < self.rect.bottomright[0]:
                 if mouse[1] < self.rect.bottomright[1]:
                    return True
                 else: return False
              else: return False
          else: return False
       else: return False


class TABLERO:
#Inicia el tablero y los demas elementos
def __init__(self):
    #Crea el tablero
    self.Tablero = ["g  g  g  g  g", 
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",
                  "g  g  g  g  g",]
    #Tablero de las fichas blancas y negras
    self.Fichas_NB = ["g  g  g  g  g",  
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",
                    "g  g  g  g  g",]
    #Botones donde se muestra la opcion elegida                
    self.Eleccion = ["g", "g", "g", "g","g"]
    #Mueve todo el set donde estan los colores hacia la derecha o izquierda (X)
    self.Set_x = 298
    #Mueve todo el set donde estan los colores hacia arriba o abajo (Y)
    self.Set_y = 360
    #Posicion donde estan los colores que se eligiran
    self.Set_e = 625
    #Asigna imagenes a los botones dependiendo de su color
    self.Boton_AZ = Boton_Colores('bluepeg.png')
    self.Boton_R = Boton_Colores('redpeg.png')
    self.Boton_A = Boton_Colores('yellowpeg.png')
    self.Boton_N = Boton_Colores('orangepeg.png')
    self.Boton_M = Boton_Colores('purppeg.png')
    self.Boton_V = Boton_Colores('greenpeg.png')
    #Formato en que estan los numeros
    #tamaño de los numeros
    self.font = pygame.font.SysFont('algerian', 14)
    self.font2 = pygame.font.SysFont('algerian', 4)

#Funcion donde se generan las filas de casillas y numeros al lado de ellas    
def Casilla_Num(self):
    #Genera los numeros antes de las filas de los intentos
    self.Num_Filas = 1
    #Mueve las casillas de intento en el eje X
    self.bx = 30
    #Mueve las casillas de intento en el eje Y
    self.by = 100
    #El contado de filas recorre el tablero
    for filas in self.Tablero:
        #Genera las filas 
        self.g = str(self.Num_Filas)
        self.text = self.font.render(self.g, 1, (10, 10, 10))
        #Muestra los numeros en la posicion X e Y indicadas
        screen.blit(self.text, (self.bx - 23, self.by)) #el 23 es la posicion en x
        #Se le suma 1 a los numeros generados para ir de forma creciente
        self.Num_Filas += 1
        pygame.display.update()
        #se asignan los colores a las filas de los intentos
        for col in filas:
            if col == "g":
                screen.blit(gris_peg, (self.bx, self.by))
            elif col == "r":
                screen.blit(rojo_peg, (self.bx, self.by))
            elif col == "az":
                screen.blit(azul_peg, (self.bx, self.by))
            elif col == "v":
                screen.blit(verde_peg, (self.bx, self.by))
            elif col == "m":
                screen.blit(morado_peg, (self.bx, self.by))
            elif col == "a":
                screen.blit(amarillo_peg, (self.bx, self.by))
            elif col == "n":
                screen.blit(naranjo_peg, (self.bx, self.by))
            else:
                continue
            self.bx += 35
        #Se le suma 35 al eje Y  de las casillas para que pase a la siguiente   
        self.by += 35
        #Se mantiene en la misma posicion en el eje X
        self.bx = 30
        pygame.display.flip()




def Fichas(self):#Le da posicion en el eje X e Y a las fichas
    self.Fichas_x = 205
    self.Fichas_y = 110
    for filas in self.Fichas_NB:
        for col in filas:
            if col == "g":
                screen.blit(Ficha_Gris, (self.Fichas_x, self.Fichas_y))
            elif col == "n":
                screen.blit(Ficha_Negra, (self.Fichas_x, self.Fichas_y))
            elif col == "b":
                screen.blit(Ficha_Blanca, (self.Fichas_x, self.Fichas_y))
            else:
                continue
            self.Fichas_x += 18
        self.Fichas_y += 35
        self.Fichas_x = 205
        pygame.display.flip()


def Color_Botones(self):
    #Le da color a la sombra de la tabla que contiene los colores a seleccionar
    pygame.draw.rect(screen, BLACK, (self.Set_x + 3, self.Set_y + 3, 90,110))
    #Le da color a la tabla que contiene los colores a seleccionar
    pygame.draw.rect(screen, WHITE, (self.Set_x,self.Set_y,90,110))
    #Le suma valores a los eje X e Y del set ,dandole nuevas posiciones a los colores
    self.Boton_R.setCords(self.Set_x+10,self.Set_y+5)
    self.Boton_N.setCords(self.Set_x+50,self.Set_y+5)
    self.Boton_A.setCords(self.Set_x+10, self.Set_y +40)
    self.Boton_V.setCords(self.Set_x+50, self.Set_y+40)
    self.Boton_AZ.setCords(self.Set_x+10, self.Set_y+75)
    self.Boton_M.setCords(self.Set_x+50, self.Set_y+75)
    pygame.display.update()
#Funcion que crea la filas que contendra los colores seleccionados
def Fila_Selec(self):
    #Mueve la fila en el eje X
    self.bx = 30
    #Pone el color seleccionado en la fila de elecciones
    for filas in self.Eleccion:
        #Si aun no elige un color la fila se quedara con el color gris hasta que seleccione uno
        if filas == "g":
            screen.blit(gris_peg, (self.bx, self.Set_e))
        elif filas == "r":
            screen.blit(rojo_peg, (self.bx, self.Set_e))
        elif filas == "az":
            screen.blit(azul_peg, (self.bx, self.Set_e))
        elif filas == "v":
            screen.blit(verde_peg, (self.bx, self.Set_e))
        elif filas == "m":
            screen.blit(morado_peg, (self.bx, self.Set_e))
        elif filas == "a":
            screen.blit(amarillo_peg, (self.bx, self.Set_e))
        elif filas == "n":
            screen.blit(naranjo_peg, (self.bx, self.Set_e))
        else:
            continue
        self.bx += 35
        pygame.display.flip()       

def Verificador(self, Eleccion):
    self.strikes1 = []
    self.strikes2 = []
    self.blackpeg=0
    self.whitepeg=0
    self.bwcount = []
    for i in range(len(Eleccion)):
        if Eleccion[i] == solucion[i]:
            self.blackpeg += 1
            self.strikes1.append(i)
            self.strikes2.append(i)
            self.bwcount.append("n")
    for x in range(len(solucion)):
        for y in range(len(solucion)):
            if x not in self.strikes1 and y not in self.strikes2:
                if Eleccion[x] == solucion[y]:
                    self.whitepeg += 1
                    self.strikes1.append(x)
                    self.strikes2.append(i)
                    self.bwcount.append("b")
        self.Fichas_NB[Turno] = self.bwcount

def Gana(self):
    screen.blit(winbg, (0,0))
    pygame.display.flip()
    pygame.time.delay(5000)
    exit()

def Pierde(self):
    screen.blit(losebg, (0,0))
    self.bx = 115
    #Genera la solucion y la imprime una vez el usuario pierde
    for filas in solucion:
        if filas == "g":
            screen.blit(gris_peg, (self.bx, 400))
        elif filas == "r":
            screen.blit(rojo_peg, (self.bx, 400))
        elif filas == "az":
            screen.blit(azul_peg, (self.bx, 400))
        elif filas == "v":
            screen.blit(verde_peg, (self.bx, 400))
        elif filas == "m":
            screen.blit(morado_peg, (self.bx, 400))
        elif filas == "a":
            screen.blit(amarillo_peg, (self.bx, 400))
        elif filas == "n":
            screen.blit(naranjo_peg, (self.bx, 400))
        else:
            continue
        self.bx += 35
    pygame.display.update()
    pygame.time.delay(5000)
    exit()

def Dar_Respuesta():
#generates the solution which the player must guess
availcolors = ("r", "n", "a", "v", "az", "m")
answer = [random.choice(availcolors) for i in range(5)]
return answer

def Fondo_Texto():
#Carga y guarda la imagen de fondo
Fondo, Fondo_rect = Cargar_Imagen('FONDO.jpg')
screen.blit(Fondo,(0,0))
#Le da color,grosor y posicion a la linea superior
pygame.draw.line(screen, BLACK, (30, 55), (350, 55), 5)
#Le da color,grosor y posicion a la linea inferior
pygame.draw.line(screen, BLACK, (30, 620), (620, 620), 5)
#Genera al texto en la parte superior 
heading_text = font.render("Sus Elecciones",1,(0,0,0))
#Da la posicion donde se se encontrara el texto
heading_textpos = (65, 65)
#Muestra en pantalla el texto en la posicion y su color
screen.blit(heading_text, heading_textpos)
pygame.display.update()

gris_peg, gris_rect = Cargar_Imagen('mmempty.png')
rojo_peg, rojo_peg_rect = Cargar_Imagen('redpeg.png')
azul_peg, azul_peg_rect = Cargar_Imagen('bluepeg.png')
verde_peg, verde_peg_rect = Cargar_Imagen('greenpeg.png')
morado_peg, morado_peg_rect = Cargar_Imagen('purppeg.png')
amarillo_peg, amarillo_peg_rect = Cargar_Imagen('yellowpeg.png')
naranjo_peg, naranjo_peg_rect = Cargar_Imagen('orangepeg.png')
Ficha_Gris, Ficha_Gris_rect = Cargar_Imagen('bwempty1.png')
Ficha_Blanca, Ficha_Blanca_rect = Cargar_Imagen('bwwhite.png')
Ficha_Negra, Ficha_Negra_rect = Cargar_Imagen('bwblack.png')
winbg, winbg_rect = Cargar_Imagen('mmbgwin.jpg')
losebg, losebg_rect = Cargar_Imagen('mmbglose.jpg')


#Menu General

Fondo_Texto()

Tablero = TABLERO()

solucion = Dar_Respuesta()
print solucion
Turno = 0
Tablero.Casilla_Num()
Tablero.Color_Botones()
Tablero.Fichas()
Tablero.Fila_Selec()
deltat = clock.tick(10)
#Contador de los colores elegidos
Color_Num = 0
guessresult = []
pos = pygame.mouse.get_pos()
#Se le asignan los intentos y los turnos que ha realizado
while Turno <= 15:
  for event in pygame.event.get():
    if event.type == QUIT:
        exit()
    #SI los turnos son iguales a los intentos permitidos, el jugador pierde    
    elif Turno == 15:
        #Le muestra una imagen diciendo que perdio
        Tablero.Pierde()
    elif event.type == MOUSEBUTTONDOWN and Color_Num < 5:
        pos = pygame.mouse.get_pos()
        if Tablero.Boton_AZ.pressed(pos) == True:#bluebut
            Tablero.Eleccion[Color_Num] = "az"
            Tablero.Fila_Selec()
            Color_Num += 1
        elif Tablero.Boton_A.pressed(pos) == True:
            Tablero.Eleccion[Color_Num] = "a"
            Tablero.Fila_Selec()
            Color_Num += 1

        elif Tablero.Boton_N.pressed(pos) == True:
            Tablero.Eleccion[Color_Num] = "n"
            Tablero.Fila_Selec()
            Color_Num += 1

        elif Tablero.Boton_M.pressed(pos) == True:
            Tablero.Eleccion[Color_Num] = "m"
            Tablero.Fila_Selec()
            Color_Num += 1

        elif Tablero.Boton_V.pressed(pos) == True:
            Tablero.Eleccion[Color_Num] = "v"
            Tablero.Fila_Selec()
            Color_Num += 1

        elif Tablero.Boton_R.pressed(pos) == True:
            Tablero.Eleccion[Color_Num] = "r"
            Tablero.Fila_Selec()
            Color_Num += 1
        else:
            continue
    elif Color_Num == 5:
        Tablero.Tablero[Turno] = Tablero.Eleccion
        Tablero.Casilla_Num()
        Tablero.Verificador(Tablero.Eleccion)
        Tablero.Fichas()
        Tablero.Eleccion = ["g", "g", "g", "g","g"]
        Turno += 1
        Tablero.Fila_Selec()
        Tablero.Fichas()
        Color_Num = 0
        if Tablero.blackpeg == 5:
            Tablero.Gana()
            break   
    else:
        continue

My idea is something like that

if event.key==KEYDOWN:
   if event.key==K_SPACE:

elif event.key==KEYDOWN:
    if event.key==K_ENTER:

But I do not know much about which part of the code should I put it so that I do not get an error and could give me an idea to do the whole process of the game but this time with 4 squares instead of 5? So, if you press space, the game starts in difficult mode (5 boxes) or if you press enter, the game starts in easy mode (4 boxes), you also appreciate all the help and if you want to give me suggestions to put more comments I would appreciate it

    
asked by Wolf 09.10.2018 в 01:55
source

1 answer

0

To make a menu:

You must find a way to generate another screen on top of your current game. For this you can define a function or class that generates another game_loop or game cycle, that is, something like while Turno <= 15: .

I do it this way:

import pygame

def generar_otra_pantalla():
    otra_pantalla = True
    while otra_pantalla:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                #IMPORTANTE ESTA ACCION, DE MODO QUE SI PULSAN DE NUEVO LA TECLA SE OCULTE EL MENU
                    otra_pantalla = False
                # COLOCAMOS EL COLOR DEL MENU
        screen.fill(WHITE)
        # DIBUJAMOS COSAS
        dibujar("cuadrado")
        dibujar("menu de acciones")
        # ACTUALIZAMOS EL DISPLAY CON UPDATE SE USA AQUI PARA 
        # UNICAMENTE ACTUALIZAR LA PORCION DE PANTALLA QUE ESTAMOS USANDO, NO TODO.
        # PORQUE DE LO CONTRARIO BORRARIA LO QUE ESTABA DEBAJO, 
        # DIGAMOS ERA UN MENU DE PAUSA, SI USAMOS FLIP CUANDO QUITEMOS EL MENU NO QUEDARA NADA
        pygame.display.update()

        # Y LUEGO PONEMOS EL RELOJ RAPIDO PARA QUE SEA UN RENDERIZADO PERMANENTE
        reloj_juego.tick(5)

And that function I call from the main_loop or main loop:

pygame.init()

# SE IGNORA LA DEFINICION DE RELOJ Y DEMAS ELEMENTOS BASICOS
GAME_END = False

import otra_pantalla

#: Bucle Principal
while not GAME_END:
#: Manejador de eventos
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                otra_pantalla()

    # OJO EL UPDATE VA A CARGAR LOS DIBUJOS QUE HAGAMOS EN EL LIENZO 
    # LLAMEMOSLO ASI DE otra_pantalla 
    # AQUI EL FLIP VA A ACTUALIZAR LA PANTALLA CON LO QUE SE HA TRAZADO 
    # EN GENERAL, POR TANTO, CUANDO PULSAMOS LA TECLA ASIGNADA (q) SE
    # CARGA OTRA PANTALLA Y SOLO SE ACTUALIZA ELLA, LUEGO
    # AL PULSARLA OTRA VEZ QUEDA EL MENU ANTERIOR

    pygame.display.flip()
    reloj_juego.tick(60)
pygame.quit()

For difficulty

You can follow these tutorials:

1. Schedule Arcade Games with Pygame (it's complete, it has up to     sprite management)

link

It is in Spanish but there are hyperlinks that do not work, everything works perfectly on the site in English.

2. Thenewboston pygame tutorial:

This has two courses, the first one you do a shooting game, then a racing one, it explains menus, collisions, pauses, and others, very good.

link

    
answered by 09.10.2018 / 04:11
source