Шаблон блокировки экрана Android в Pygame

пароль_3.gif

Реализация шаблона блокировки Android в Pygame — интересная попытка высмеять отличный пользовательский интерфейс.

Шаги

Вот примерный план того, о чем нам нужно подумать:

  • Кнопки отображения
  • Записать выбор пользователя
  • Рисуйте шаблоны на основе выбора пользователя
  • Иметь длину шаблона
  • Проверка правильного пароля
  • Сбросить выбор

Я рекомендую вам попытаться реализовать это в pygame или p5py, а затем вернуться, чтобы прочитать статью.

Скелет

мы используем мужчина в этом руководстве, которое реализует p5js API в Pygame.

python -m pip install hooman

Вот базовый скелет, который отображает пустое окно

from hooman import Hooman

import pygame

pen = Hooman(500, 500)


while pen.is_running:
    pen.background(255)


    pen.flip_display()
    pen.event_loop()

Кнопки отображения

Давайте реализуем наши кнопки шаблона в виде простых кругов.

class LockButton:
    def __init__(self, x, y, pen, num=0):
        self.x = x
        self.y = y
        self.pen = pen
        self.num = num

    def coords(self):
        return (self.x, self.y)

    def draw(self):
        pen = self.pen
        pen.fill(0)
        pen.ellipse(self.x, self.y, 20, 20)

    def update(self):
        pass

    def run(self):
        self.update()
        self.draw()

Затем мы инициализируем их в списке


button_id = 1
for x in range(5):
    for y in range(5):

        buttons.append(LockButton(x * 50 + 10, y * 50 + 10, pen, num=button_id))
        button_id += 1

Затем нарисуйте их из списка


while pen.is_running:
    

    
    for b in buttons:
        b.run()

    

Pass3but.png

Записать выбор пользователя

Для записи выбора пользователя мы записываем координаты выбранных кнопок, чтобы не рисовать на ней лишний раз линию, и записываем id кнопки, чтобы можно было легко сравнить его с нашим шаблоном пароля

from hooman import Hooman
from hooman.formula import distance

import pygame

pen = Hooman(500, 500)

attempt_button_coords = [] 
attempt_button_ids = [] 
buttons = [] 



class LockButton:
    

    def update(self):
        pen = self.pen
        global attempt_button_coords, attempt_button_ids

        if pen.pygame.mouse.get_pressed()[0]: 
            mouse_coords = (pen.mouseX(), pen.mouseY())
            if distance(self.coords(), mouse_coords) <= 20:
                if self.coords() not in attempt_button_coords:
                    attempt_button_ids.append(self.num)
                    attempt_button_coords.append(self.coords())

    

Рисуйте шаблоны на основе выбора пользователя

while pen.is_running:
    
    
    pen.fill(0)
    for i, c in enumerate(attempt_button_coords):
        try:
            pen.stroke_size(5)
            pen.stroke(pen.color["green"])
            pen.line(
                c[0] + 10,
                c[1] + 10,
                attempt_button_coords[i + 1][0] + 10,
                attempt_button_coords[i + 1][1] + 10,
            )
        except Exception as e:
            pass

    
    try:
        pen.line(
            attempt_button_coords[-1][0] + 10,
            attempt_button_coords[-1][1] + 10,
            pen.mouseX(),
            pen.mouseY(),
        )
    except:
        pass

user_choice.gif

Но у нас есть проблема: шаблоны продолжаются бесконечно.

Иметь длину шаблона

  
    
    if len(attempt_button_coords) >= 7:

        attempt_button_coords = []
        attempt_button_ids = []

pattern_length.gif

Проверьте правильный пароль

display_win = False
pattern = [1, 2, 3, 4, 5, 6, 7] 

    
    
    if len(attempt_button_coords) >= 7:

        if attempt_button_ids == pattern: 
            display_win = True

        

    
    if display_win:
        pen.fill((200, 200, 50))
        pen.font_size(30)
        pen.text("Right password!", 300, 50)

right_password.gif

Добавляем кнопку сброса

Чтобы мы могли повторить попытку шаблона, мы добавляем кнопку сброса, которая очищает список шаблонов. Мы используем человеческую кнопку.


from hooman.ui import Button


def reset_clicked(this):
    global attempt_button_coords, attempt_button_ids, display_win
    attempt_button_coords = []
    attempt_button_ids = []
    display_win = False

reset_button_styles = {
    "hover_background_color": (200, 200, 200),
    "font_size": 10,
    "background_color": (210, 210, 210),
    "on_click": reset_clicked,
    "curve": 1,
}
reset_button = Button(250, 10, 150, 20, "Reset", reset_button_styles)



while pen.is_running:
    

    reset_button.update()

reset_button.gif

Полный код

from hooman import Hooman
from hooman.formula import distance
from hooman.ui import Button

import pygame

pen = Hooman(500, 500)

attempt_button_coords = [] 
attempt_button_ids = [] 
buttons = [] 
display_win = False
pattern = [1, 2, 3, 4, 5, 6, 7] 



def reset_clicked(this):
    global attempt_button_coords, attempt_button_ids, display_win
    attempt_button_coords = []
    attempt_button_ids = []
    display_win = False


reset_button_styles = {
    "hover_background_color": (200, 200, 200),
    "font_size": 10,
    "background_color": (210, 210, 210),
    "on_click": reset_clicked,
    "curve": 1,
}
reset_button = Button(250, 10, 150, 20, "Reset", reset_button_styles)


class LockButton:
    def __init__(self, x, y, pen, num=0):
        self.x = x
        self.y = y
        self.pen = pen
        self.num = num

    def coords(self):
        return (self.x, self.y)

    def draw(self):
        pen = self.pen

        pen.fill(0)
        pen.ellipse(self.x, self.y, 20, 20)

    def update(self):
        pen = self.pen
        global attempt_button_coords, attempt_button_ids

        if pen.pygame.mouse.get_pressed()[0]:

            mouse_coords = (pen.mouseX(), pen.mouseY())
            if distance(self.coords(), mouse_coords) <= 20:
                if self.coords() not in attempt_button_coords:
                    attempt_button_ids.append(self.num)
                    attempt_button_coords.append(self.coords())

    def run(self):
        self.update()
        self.draw()



button_id = 1
for x in range(5):
    for y in range(5):

        buttons.append(LockButton(x * 50 + 10, y * 50 + 10, pen, num=button_id))
        button_id += 1


while pen.is_running:
    pen.background(255)

    
    pen.fill(0)
    for i, c in enumerate(attempt_button_coords):
        try:
            pen.stroke_size(5)
            pen.stroke(pen.color["green"])
            pen.line(
                c[0] + 10,
                c[1] + 10,
                attempt_button_coords[i + 1][0] + 10,
                attempt_button_coords[i + 1][1] + 10,
            )
        except Exception as e:
            pass

    
    try:
        pen.line(
            attempt_button_coords[-1][0] + 10,
            attempt_button_coords[-1][1] + 10,
            pen.mouseX(),
            pen.mouseY(),
        )
    except:
        pass

    
    for b in buttons:
        b.run()


    
    if len(attempt_button_coords) >= 7:

        if attempt_button_ids == pattern:
            display_win = True

        attempt_button_coords = []
        attempt_button_ids = []

    
    if display_win:
        pen.fill((200, 200, 50))
        pen.font_size(30)
        pen.text("Right password!", 300, 50)

    reset_button.update()

    pen.flip_display()
    pen.event_loop()

Похожие записи

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *