简体   繁体   中英

How do I make it so it goes to a new scene on keypress? (Pygame)

I am very new and I cant seem to find any tutorials on how to do this. I would imagine it would be pretty simple. I am creating an Oregon Trail type game and I need it to go to the next picture when you press E, or quit the program when you press Q.

Here is my code:

# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 1000, 800
screen=pygame.display.set_mode((width, height))

# 3 - Load images
background = pygame.image.load("start.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(background, (0,0))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit() 
            exit(0)

I think you are looking for something like this:

# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 1000, 800
screen=pygame.display.set_mode((width, height))

# 3 - Load images
background = pygame.image.load("start.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(background, (0,0))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                background = pygame.image.load("stage2.png")
        # check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit() 
            exit(0)

Of course this will only work for 2 images of background "start.png" and stage2.png". But you can create a list and cicle through it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM