Как заставить кнопку открывать новый экран с текстовым полем с помощью pygamePython

Программы на Python
Ответить
Anonymous
 Как заставить кнопку открывать новый экран с текстовым полем с помощью pygame

Сообщение Anonymous »

У меня есть 3 кнопки, которые открывают разные экраны, отображающие разные вещи. Я хочу сделать так, чтобы при нажатии кнопки воспроизведения открывался экран с текстом «Введите свое имя», а затем текстовым полем под ним, которое позволяет вам введите имя и присвойте переменной, которая будет записана в текстовый файл. Я пытался это сделать, но в итоге это сломало всю мою программу и все мои кнопки, так что это здорово :)
Я решил попробовать использовать для этого функции, поскольку я мало ими пользовался все это есть в моей программе, и я думал, что это облегчит задачу и т. д., но похоже, что это не так.
Функция "enter_name" должна содержать все необходимое для создания текстового поля и прочего, кроме записи его в текстовый файл. но, похоже, это не работает, ни одна из кнопок больше не работает, и нажатие кнопки таблицы лидеров приводит к этой ошибке
Traceback (most recent call last):
File "c:\Users\leeun\OneDrive\Desktop\Python\NEA\Iteration1\mainmenu.py", line 137, in
leaderboard()
File "c:\Users\leeun\OneDrive\Desktop\Python\NEA\Iteration1\mainmenu.py", line 64, in leaderboard
if menu_state == "leaderboard":
^^^^^^^^^^
UnboundLocalError: cannot access local variable 'menu_state' where it is not associated with a value

import pygame
import button
import sys
from players import Player
from pytmx.util_pygame import load_pygame

pygame.init()

#**********************************VARIABLES**********************************
# screen size variables
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 800
clock = pygame.time.Clock()

# defining screen size/name
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Start Menu")

# for player
player = Player(250, 250, 3, (0, 0, 255), 20, screen)

# text font
font = pygame.font.SysFont("arialblack", 40)
font2 = pygame.font.SysFont("arialblack", 10)
font_header = pygame.font.SysFont("arialblack", 60)

# text colour
TEXT_COL = (255, 255, 255)
TEXT_COL2 = (0, 0, 0)

# loading / setting buttons
play_btn = pygame.image.load("C:/Users/leeun/OneDrive/Desktop/Python/NEA/Iteration1/images/button_play.png").convert_alpha()
quit_btn = pygame.image.load("C:/Users/leeun/OneDrive/Desktop/Python/NEA/Iteration1/images/button_quit.png").convert_alpha()
leaderboard_btn = pygame.image.load("C:/Users/leeun/OneDrive/Desktop/Python/NEA/Iteration1/images/button_leaderboard.png").convert_alpha()
back_btn = pygame.image.load("C:/Users/leeun/OneDrive/Desktop/Python/NEA/Iteration1/images/button_back.png").convert_alpha()

leaderboard_btn = button.Button(360, 390, leaderboard_btn, 1)
quit_btn = button.Button(400, 500, quit_btn, 1)
play_btn = button.Button(400, 275, play_btn, 1)
back_btn = button.Button(400, 525, back_btn, 1)

# function for displaying text
def draw_text(text, font, text_col, x, y):
img = font.render(text, True, text_col)
screen.blit(img, (x, y))

# runs the game
run = True
game_menu = True

# game states
game_paused = False
menu_state = "main"

#***************************************************FUNCTIONS**************************************************
def leaderboard():
# display the leaderboard
draw_text("Leaderboard display", font, TEXT_COL, 160, 250)
# return back to main menu
if back_btn.draw(screen):
menu_state = "main"

# check if leaderboard is open
if menu_state == "leaderboard":
leaderboard()

def enter_name():
user_text = ''
input_rect = pygame.Rect(200, 200, 140, 32)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('chartreuse4')
color = color_passive

active = False

while True:
for event in pygame.event.get():

if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_BACKSPACE:

user_text = user_text[:-1]

else:
user_text += event.unicode

if active:
color = color_active
else:
color = color_passive

pygame.draw.rect(screen, color, input_rect)

text_surface = font.render(user_text, True, (255, 255, 255))

screen.blit(text_surface, (input_rect.x+5, input_rect.y+5))

input_rect.w = max(100, text_surface.get_width()+10)

pygame.display.flip()

#**********************************MAIN LOOP**********************************
while run:

# fills the screen in with blue
screen.fill((79, 101, 176))

# main screen
if game_menu == True:

# check game state
if menu_state == "main":

# display the game name
draw_text("Worlds Easiest Game", font_header, TEXT_COL, 150, 90)

# draw main menu buttons
if play_btn.draw(screen):
menu_state = "enter_name"
if leaderboard_btn.draw(screen):
menu_state = "leaderboard"
if quit_btn.draw(screen):
run = False

if menu_state == "leaderboard":
leaderboard()

if menu_state == "enter_name":
enter_name()

# the main game screen, this will include the player, level objects
else:
# sets the game title to Main Game
pygame.display.set_caption("Main Game")

# makes the screen white
screen.fill((255, 255, 255))

# esc to pause top left
draw_text("Press ESC to pause", font2, TEXT_COL2, 25, 25)

# renders the player
player.render()

# movement
key_pressed = pygame.key.get_pressed()

if key_pressed[pygame.K_w]:
player.up()
if key_pressed[pygame.K_a]:
player.left()
if key_pressed[pygame.K_s]:
player.down()
if key_pressed[pygame.K_d]:
player.right()

# border
if player.x < player.size:
player.x = player.size
if player.x > 1000 - player.size-20:
player.x = 1000 - player.size-20
if player.y < player.size:
player.y = player.size
if player.y > 800 - player.size-20:
player.y = 800 - player.size-20

# main loop
for event in pygame.event.get():

# checks if ESC has been pressed to go to main menu
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
game_menu = True

# quits the game
if event.type == pygame.QUIT:
run = False

clock.tick(60)

pygame.display.flip()

pygame.quit()


Подробнее здесь: https://stackoverflow.com/questions/792 ... ing-pygame
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»