Как мне проверить мой введенный пароль из текстового поля в Pygame? - PullRequest
0 голосов
/ 04 октября 2018

так что я пытаюсь сделать тест с множественным выбором, так что это код, который я сделал до сих пор, но я не имею ни малейшего понятия о том, как я мог бы подтвердить или пароль для возвращающегося пользователя или для нового пользователя в тот момент, когда он работаеткак это должно.У меня есть 2 функции, если пользователь уже использовал программу, и 2, если пользователь новый и ему необходимо создать новую учетную запись с именем пользователя и паролем

import pygame
import sys

teal= (0,150,150)

#display window
pygame.init()
size=[800,600]
screen= pygame.display.set_mode(size)
screen.fill(teal)
font=pygame.font.SysFont("comicsandms", 72)

pygame.display.update()


#textbox code
def textbox():
    input_box = pygame.Rect(300, 300, 500, 50)
    color_inactive = pygame.Color('lightskyblue3')
    color_active = pygame.Color('dodgerblue2')
    color = color_inactive
    active = False
    text = ''
    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                # If the user clicked on the textbox
                if input_box.collidepoint(event.pos):

                    active = not active
                else:
                    active = False
                # change the colour of the textbox once clicked
                color = color_active if active else color_inactive
            if event.type == pygame.KEYDOWN:
                if active:
                    #prints the text from the textbox in the python shell
                    if event.key == pygame.K_RETURN:
                        print(text)
                        text = ''
                        done= True
                    elif event.key == pygame.K_BACKSPACE:
                        text = text[:-1]
                    else:
                        text += event.unicode


        # Render the current text.
        text_surface = font.render(text, True, color)
        # Resize the box if the text is too long.
        width = max(200, text_surface.get_width()+10)
        input_box.w = width

        # Blit the text.
        screen.blit(text_surface, (input_box.x+5, input_box.y+5))
        # Blit the input_box rect.
        pygame.draw.rect(screen, color, input_box, 2)

        pygame.display.flip()


#username and password functions
def username():
    usernametext= font.render("username :", True, (100, 100, 175))
    screen.blit(usernametext, (400 - usernametext.get_width() // 2, 240 - usernametext.get_height() // 2))
    textbox()
    #text

def password():
    passwordtext= font.render("password :", True, (100, 100, 175))
    screen.blit(passwordtext, (400 - passwordtext.get_width() // 2, 240 - passwordtext.get_height() // 2))
    textbox()


#new user username and password functions
def newuser():
    usernametext=font.render("please create a username", True, (100,100,175))
    screen.blit(usernametext, (400 - usernametext.get_width() // 2, 240 - usernametext.get_height() // 2))
    textbox()

def newpassword():
    passwordtext= font.render("please create a password", True, (100, 100, 175))
    screen.blit(passwordtext, (400 - passwordtext.get_width() // 2, 240 - passwordtext.get_height() // 2))
    textbox()




def mainscreen():

    #start up
    font=pygame.font.SysFont("comicsandms", 72)
    titletext= font.render("welcome to a-level chem quiz !!", True,(125,0,125))
    screen.blit(titletext,(400 - titletext.get_width() // 2, 240 - titletext.get_height() // 2))
    logintext= font.render("have you got an account?", True ,(0,0,0))
    screen.blit(logintext,(400 - logintext.get_width() // 2, 300 - logintext.get_height() // 2))




    #button for having account
    yesbutton= pygame.Rect(200,350,100,100)
    pygame.draw.rect(screen,[0,200,50], yesbutton)
    yesbuttontext=font.render("yes", True, (0,0,0))
    screen.blit(yesbuttontext, (250 - yesbuttontext.get_width() // 2, 400 - yesbuttontext.get_height() //2))

    #button for not having account
    nobutton= pygame.Rect(450, 350, 100,100)
    pygame.draw.rect(screen,[200,0,50], nobutton)
    nobuttontext=font.render("no", True, (0,0,0))
    screen.blit(nobuttontext, (513 - yesbuttontext.get_width() // 2, 400 - nobuttontext.get_height() //2))

    pygame.display.update()

    done=False
    while done == False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done= True

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos= pygame.mouse.get_pos()


                #if they already have an account
                if yesbutton.collidepoint(mouse_pos):  
                    screen.fill((30,30,30))
                    username()
                    screen.fill((30,30,30))
                    password()
                    done = True

                #if they are a new user and need to create a username and password
                elif nobutton.collidepoint(mouse_pos):
                    screen.fill((30,30,30))
                    newuser()
                    screen.fill((30,30,30))
                    newpassword()
                    done= True


                    pygame.display.update()


if __name__ == "__main__": 
    mainscreen()

. Любая помощь будет принята, спасибо.:) извините, что это действительно большой кусок кода

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

Я не совсем уверен, как вы хотите хранить информацию о пользователях, так как вы в настоящее время храните их только в переменных, которые работают только во время текущего экземпляра программы и исчезают после закрытия программы, именно по этой причине я 'Будут включены следующие функции для хранения пользовательских данных, их добавления и проверки.

import io
import ConfigParser


def create_User(username, password):
    config = ConfigParser.RawConfigParser()
    config.add_section('UserInformation')
    config.set('UserInformation', username, password)
    with open('userinfo.ini', 'wb') as f:
        config.write(f)
    print('User: ' + username + 'added to file with password: ' + password)

def check_User(username, password):
    with open('userinfo.ini') as f:
        conf = f.read()
        config = ConfigParser.RawConfigParser(allow_no_value=True)
        config.readfp(io.BytesIO(conf))
        real_Password = config.get('UserInformation', username)

        if real_Password == password:
            return True
        else:
            return False


#create_User('sage', 'password')
if check_User('sage', 'password') != False:
    print ('User Correct!')
else:
    print('User False!')

Использует ini, который является простым в использовании Config, этот код работает и должен помочь вам.

Развлекайся

0 голосов
/ 04 октября 2018

@ groot 1-й из всех, заголовок не ясен.Более подходящим заголовком будет «Как проверить пароли в Python».Я думал, что вы говорите о текстовых полях Tkinter.Кроме того, шрифт «comicsansms», а не «comicsandms».После прочтения вашего кода и тела вопроса я понял.Вам нужно посмотреть на I \ O в Python.Это метод чтения записи в файлы.После того, как вы записали имя пользователя и пароль в файл: ваш сценарий может найти этот файл и убедиться, что пользователь и пароль существуют и совпадают.Я не использовал это долгое время, поэтому я точно не помню, как это работает, но если вы посмотрите «Python I / O», вы найдете его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...