2012-07-22 20 views
11

Estoy tratando de permitir el cambio de tamaño para esta aplicación, puse la bandera REDIMENSIONABLE, pero cuando intento cambiar el tamaño, ¡se arruina! Prueba mi códigoPermitir el cambio de tamaño de la ventana pyGame

Es un programa de cuadrícula, cuando la ventana cambia de tamaño, quiero que la cuadrícula también cambie de tamaño/contracción.

import pygame,math 
from pygame.locals import * 
# Define some colors 
black = ( 0, 0, 0) 
white = (255, 255, 255) 
green = ( 0, 255, 0) 
red  = (255, 0, 0) 

# This sets the width and height of each grid location 
width=50 
height=20 
size=[500,500] 
# This sets the margin between each cell 
margin=1 


# Initialize pygame 
pygame.init() 

# Set the height and width of the screen 

screen=pygame.display.set_mode(size,RESIZABLE) 

# Set title of screen 
pygame.display.set_caption("My Game") 

#Loop until the user clicks the close button. 
done=False 

# Used to manage how fast the screen updates 
clock=pygame.time.Clock() 

# -------- Main Program Loop ----------- 
while done==False: 
    for event in pygame.event.get(): # User did something 
     if event.type == pygame.QUIT: # If user clicked close 
      done=True # Flag that we are done so we exit this loop 
     if event.type == pygame.MOUSEBUTTONDOWN: 
      height+=10 

    # Set the screen background 
    screen.fill(black) 

    # Draw the grid 
    for row in range(int(math.ceil(size[1]/height))+1): 
     for column in range(int(math.ceil(size[0]/width))+1): 
      color = white 
      pygame.draw.rect(screen,color,[(margin+width)*column+margin,(margin+height)*row+margin,width,height]) 

    # Limit to 20 frames per second 
    clock.tick(20) 

    # Go ahead and update the screen with what we've drawn. 
    pygame.display.flip() 
# Be IDLE friendly. If you forget this line, the program will 'hang' 
# on exit. 
pygame.quit() 

Por favor, dime lo que está mal, gracias.

Respuesta

0

una simple ventana Hello World que es de tamaño variable, además de que estaba jugando con las clases.
Desglosado en dos archivos, uno para definir las constantes de color.

import pygame, sys 
from pygame.locals import * 
from colors import * 


# Data Definition 
class helloWorld: 
    '''Create a resizable hello world window''' 
    def __init__(self): 
     pygame.init() 
     self.width = 300 
     self.height = 300 
     DISPLAYSURF = pygame.display.set_mode((self.width,self.height), RESIZABLE) 
     DISPLAYSURF.fill(WHITE) 

    def run(self): 
     while True: 
      for event in pygame.event.get(): 
       if event.type == QUIT: 
        pygame.quit() 
        sys.exit() 
       elif event.type == VIDEORESIZE: 
        self.CreateWindow(event.w,event.h) 
      pygame.display.update() 

    def CreateWindow(self,width,height): 
     '''Updates the window width and height ''' 
     pygame.display.set_caption("Press ESC to quit") 
     DISPLAYSURF = pygame.display.set_mode((width,height),RESIZABLE) 
     DISPLAYSURF.fill(WHITE) 


if __name__ == '__main__': 
    helloWorld().run() 

colors.py:

BLACK = (0, 0,0) 
WHITE = (255, 255, 255) 
RED = (255, 0, 0) 
YELLOW = (255, 255, 0) 
BLUE = (0,0,255) 

GREEN = (0,255,0) 
+7

Código, pero que realmente debe leer las directrices PEP 8 estilo. Está incumpliendo una gran cantidad de convenciones con nombres como 'CreateWindow' que no es una clase,' helloWorld'hat * is * y 'DISPLAYSURF' que no es una constante. Además, evite enviar spam 'from ... import *' en todas partes, especialmente porque no los está usando (de todos modos, está prefijando todas las llamadas a 'pygame') – MestreLion

5

La descripción de ninMonkey era correcta (https://stackoverflow.com/a/11604661/3787376).

No está actualizando su ancho, alto o tamaño cuando cambia la ventana .

Así que la respuesta es simplemente para recrear la ventana Pygame, la actualización de su tamaño
(esto cambia el tamaño de la ventana actual y elimina todo el contenido anterior en su superficie).

>>> import pygame 
>>> 
>>> pygame.display.set_mode.__doc__ 
'set_mode(resolution=(0,0), flags=0, depth=0) -> Surface\nInitialize a window or screen for display' 
>>> 

Esto tiene que ser hecho en pygame.VIDEORESIZE eventos que se envían cuando el usuario cambia las dimensiones de la ventana de tamaño variable. Además, puede ser necesario utilizar el siguiente método para mantener el contenido de la ventana actual.

un código de ejemplo:

import pygame, sys 
# from pygame.locals import * # This would make Pygame constants (in capitals) not need the prefix "pygame." 

pygame.init() 

# Create the window, saving it to a variable. 
surface = pygame.display.set_mode((350, 250), pygame.RESIZABLE) 
pygame.display.set_caption("Example resizable window") 

while True: 
    surface.fill((255,255,255)) 

    # Draw a red rectangle that resizes with the window as a test. 
    pygame.draw.rect(surface, (200,0,0), (surface.get_width()/3, 
              surface.get_height()/3, 
              surface.get_width()/3, 
              surface.get_height()/3)) 

    pygame.display.update() 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_ESCAPE: 
       pygame.quit() 
       sys.exit() 
     if event.type == pygame.VIDEORESIZE: 
      # The main code that resizes the window: 
      # (recreate the window with the new size) 
      surface = pygame.display.set_mode((event.w, event.h), 
               pygame.RESIZABLE) 

Un método para evitar el riesgo de perder el contenido anterior:
Aquí hay algunos pasos para dejar partes de su interfaz gráfica de usuario sin cambios:

  1. crea una segunda variable, configurada con el valor de la variable de superficie de la ventana anterior.
  2. crear la nueva ventana, almacenándola como la variable anterior.
  3. dibujar la segunda superficie sobre la primera (variable antigua) - utilizar la función blit.
  4. utilice esta variable y elimine la nueva variable (opcional, use del) si no desea perder memoria.

un código de ejemplo para la solución anterior (va en el evento if comunicado pygame.VIDEORESIZE, en el inicio): trabaja

  old_surface_saved = surface 
      surface = pygame.display.set_mode((event.w, event.h), 
               pygame.RESIZABLE) 
      # On the next line, if only part of the window needs to be copied, there's some other options. 
      surface.blit(old_surface_saved, (0,0)) 
      del old_surface_saved # This line may not be needed. 
Cuestiones relacionadas