justcode 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
justcode/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from . import cli
2
+ from . import gui
3
+
4
+ __version__ = "1.0.0"
5
+ __all__ = ["cli", "gui"]
justcode/__main__.py ADDED
@@ -0,0 +1,21 @@
1
+ import sys
2
+
3
+ def main():
4
+ if len(sys.argv) < 3:
5
+ print("Использование: justcode <cli|gui> <calc|password|tetris|snake>")
6
+ print("Пример: justcode gui tetris")
7
+ return
8
+ mode, name = sys.argv[1], sys.argv[2]
9
+
10
+ try:
11
+ import justcode
12
+ target = getattr(getattr(justcode, mode), name, None)
13
+ if target:
14
+ target()
15
+ else:
16
+ print(f"Не найдено: {mode}.{name}")
17
+ except AttributeError:
18
+ print(f"Ошибка: проверьте правильность команды (например: gui tetris)")
19
+
20
+ if __name__ == "__main__":
21
+ main()
@@ -0,0 +1,4 @@
1
+ from .calc import calc
2
+ from .password import password
3
+
4
+ __all__ = ["calc", "password"]
justcode/cli/calc.py ADDED
@@ -0,0 +1,41 @@
1
+ def calc():
2
+ """Консольный калькулятор."""
3
+ print("=" * 40)
4
+ print(" КОНСОЛЬНЫЙ КАЛЬКУЛЯТОР")
5
+ print("=" * 40)
6
+ print("Введите выражение (например: 2 + 2 * 3)")
7
+ print("Команды: 'exit' - выход, 'help' - справка")
8
+ print("-" * 40)
9
+
10
+ while True:
11
+ try:
12
+ expr = input(">>> ").strip()
13
+ except (EOFError, KeyboardInterrupt):
14
+ print("\nДо свидания!")
15
+ break
16
+
17
+ if expr.lower() in ("exit", "quit", "q"):
18
+ print("До свидания!")
19
+ break
20
+
21
+ if expr.lower() == "help":
22
+ print("Поддерживаются: + - * / ** % // () и математические функции")
23
+ print("Примеры: (2+3)*4 | 2**10 | 10/3")
24
+ continue
25
+
26
+ if not expr:
27
+ continue
28
+
29
+ # Разрешаем только безопасные символы
30
+ allowed = set("0123456789+-*/().% ")
31
+ if not all(ch in allowed for ch in expr):
32
+ print("Ошибка: недопустимые символы")
33
+ continue
34
+
35
+ try:
36
+ result = eval(expr, {"__builtins__": {}}, {})
37
+ print(f"= {result}")
38
+ except ZeroDivisionError:
39
+ print("Ошибка: деление на ноль")
40
+ except Exception as e:
41
+ print(f"Ошибка: {e}")
@@ -0,0 +1,41 @@
1
+ import random
2
+ import string
3
+
4
+
5
+ def password():
6
+ """Консольный генератор паролей."""
7
+ print("=" * 40)
8
+ print(" ГЕНЕРАТОР ПАРОЛЕЙ (CLI)")
9
+ print("=" * 40)
10
+
11
+ try:
12
+ length = int(input("Длина пароля (по умолчанию 12): ") or 12)
13
+ except ValueError:
14
+ length = 12
15
+
16
+ if length < 4:
17
+ length = 4
18
+
19
+ use_digits = input("Включить цифры? (y/n): ").lower() != "n"
20
+ use_upper = input("Включить заглавные буквы? (y/n): ").lower() != "n"
21
+ use_symbols = input("Включить спецсимволы? (y/n): ").lower() == "y"
22
+
23
+ chars = string.ascii_lowercase
24
+ if use_digits:
25
+ chars += string.digits
26
+ if use_upper:
27
+ chars += string.ascii_uppercase
28
+ if use_symbols:
29
+ chars += "!@#$%^&*()-_=+[]{};:,.<>?/"
30
+
31
+ try:
32
+ count = int(input("Сколько паролей сгенерировать? (по умолчанию 1): ") or 1)
33
+ except ValueError:
34
+ count = 1
35
+
36
+ print("\nСгенерированные пароли:")
37
+ print("-" * 40)
38
+ for i in range(1, count + 1):
39
+ pwd = "".join(random.choice(chars) for _ in range(length))
40
+ print(f"{i}. {pwd}")
41
+ print("-" * 40)
@@ -0,0 +1,6 @@
1
+ from .calc import calc
2
+ from .password import password
3
+ from .tetris import tetris
4
+ from .snake import snake
5
+
6
+ __all__ = ["calc", "password", "tetris", "snake"]
justcode/gui/calc.py ADDED
@@ -0,0 +1,57 @@
1
+ import tkinter as tk
2
+
3
+
4
+ def calc():
5
+ """GUI калькулятор на Tkinter."""
6
+ root = tk.Tk()
7
+ root.title("Калькулятор")
8
+ root.geometry("320x420")
9
+ root.resizable(False, False)
10
+
11
+ entry = tk.Entry(root, font=("Arial", 20), justify="right",
12
+ bd=10, insertwidth=2, bg="#f0f0f0")
13
+ entry.pack(fill="x", padx=5, pady=5)
14
+ entry.insert(0, "")
15
+
16
+ def press(key):
17
+ if key == "=":
18
+ try:
19
+ result = eval(entry.get(), {"__builtins__": {}}, {})
20
+ entry.delete(0, tk.END)
21
+ entry.insert(0, str(result))
22
+ except ZeroDivisionError:
23
+ entry.delete(0, tk.END)
24
+ entry.insert(0, "Деление на 0")
25
+ except Exception:
26
+ entry.delete(0, tk.END)
27
+ entry.insert(0, "Ошибка")
28
+ elif key == "C":
29
+ entry.delete(0, tk.END)
30
+ elif key == "⌫":
31
+ entry.delete(len(entry.get()) - 1, tk.END)
32
+ else:
33
+ entry.insert(tk.END, key)
34
+
35
+ buttons = [
36
+ ["C", "⌫", "%", "/"],
37
+ ["7", "8", "9", "*"],
38
+ ["4", "5", "6", "-"],
39
+ ["1", "2", "3", "+"],
40
+ ["0", ".", "=", ""],
41
+ ]
42
+
43
+ frame = tk.Frame(root)
44
+ frame.pack(expand=True, fill="both", padx=5, pady=5)
45
+
46
+ for r, row in enumerate(buttons):
47
+ frame.rowconfigure(r, weight=1)
48
+ for c, label in enumerate(row):
49
+ frame.columnconfigure(c, weight=1)
50
+ if not label:
51
+ continue
52
+ color = "#ffd97a" if label in ("=",) else "#e0e0e0"
53
+ tk.Button(frame, text=label, font=("Arial", 16),
54
+ bg=color, command=lambda l=label: press(l)
55
+ ).grid(row=r, column=c, sticky="nsew", padx=2, pady=2)
56
+
57
+ root.mainloop()
@@ -0,0 +1,64 @@
1
+ import random
2
+ import string
3
+ import tkinter as tk
4
+ from tkinter import ttk, messagebox
5
+
6
+
7
+ def password():
8
+ """GUI генератор паролей на Tkinter."""
9
+ root = tk.Tk()
10
+ root.title("Генератор паролей")
11
+ root.geometry("420x420")
12
+ root.resizable(False, False)
13
+
14
+ tk.Label(root, text="Генератор паролей", font=("Arial", 16, "bold")).pack(pady=10)
15
+
16
+ frame = tk.Frame(root)
17
+ frame.pack(pady=5, padx=15, fill="x")
18
+
19
+ tk.Label(frame, text="Длина:").grid(row=0, column=0, sticky="w")
20
+ length_var = tk.IntVar(value=12)
21
+ tk.Spinbox(frame, from_=4, to=64, textvariable=length_var, width=6
22
+ ).grid(row=0, column=1, sticky="w", padx=5)
23
+
24
+ digits_var = tk.BooleanVar(value=True)
25
+ upper_var = tk.BooleanVar(value=True)
26
+ symbols_var = tk.BooleanVar(value=False)
27
+
28
+ tk.Checkbutton(frame, text="Цифры", variable=digits_var).grid(row=1, column=0, sticky="w")
29
+ tk.Checkbutton(frame, text="Заглавные буквы", variable=upper_var).grid(row=1, column=1, sticky="w")
30
+ tk.Checkbutton(frame, text="Спецсимволы", variable=symbols_var).grid(row=2, column=0, sticky="w")
31
+
32
+ result_var = tk.StringVar()
33
+
34
+ def generate():
35
+ chars = string.ascii_lowercase
36
+ if digits_var.get():
37
+ chars += string.digits
38
+ if upper_var.get():
39
+ chars += string.ascii_uppercase
40
+ if symbols_var.get():
41
+ chars += "!@#$%^&*()-_=+[]{};:,.<>?/"
42
+ n = length_var.get()
43
+ if n < 4:
44
+ messagebox.showwarning("Ошибка", "Минимальная длина — 4")
45
+ return
46
+ pwd = "".join(random.choice(chars) for _ in range(n))
47
+ result_var.set(pwd)
48
+
49
+ def copy():
50
+ pwd = result_var.get()
51
+ if pwd:
52
+ root.clipboard_clear()
53
+ root.clipboard_append(pwd)
54
+ messagebox.showinfo("Скопировано", "Пароль скопирован в буфер обмена")
55
+
56
+ ttk.Button(root, text="Сгенерировать", command=generate).pack(pady=10)
57
+
58
+ entry = tk.Entry(root, textvariable=result_var, font=("Consolas", 13),
59
+ justify="center", width=35)
60
+ entry.pack(pady=5)
61
+
62
+ ttk.Button(root, text="Копировать", command=copy).pack(pady=5)
63
+
64
+ root.mainloop()
justcode/gui/snake.py ADDED
@@ -0,0 +1,125 @@
1
+ import random
2
+ import tkinter as tk
3
+
4
+ CELL = 25
5
+ COLS, ROWS = 20, 20
6
+
7
+
8
+ def snake():
9
+ """GUI Змейка."""
10
+ root = tk.Tk()
11
+ root.title("Змейка")
12
+ root.resizable(False, False)
13
+
14
+ canvas = tk.Canvas(root, width=COLS * CELL, height=ROWS * CELL, bg="#1e1e1e")
15
+ canvas.pack(padx=5, pady=5)
16
+
17
+ info = tk.StringVar(value="Счёт: 0")
18
+ tk.Label(root, textvariable=info, font=("Arial", 14, "bold")).pack()
19
+
20
+ state = {
21
+ "snake": [(10, 10), (9, 10), (8, 10)],
22
+ "dir": (1, 0),
23
+ "food": None,
24
+ "score": 0,
25
+ "game_over": False,
26
+ "speed": 150,
27
+ }
28
+
29
+ def spawn_food():
30
+ while True:
31
+ pos = (random.randrange(COLS), random.randrange(ROWS))
32
+ if pos not in state["snake"]:
33
+ state["food"] = pos
34
+ return
35
+
36
+ spawn_food()
37
+
38
+ def step():
39
+ if state["game_over"]:
40
+ return
41
+
42
+ dx, dy = state["dir"]
43
+ head = (state["snake"][0][0] + dx, state["snake"][0][1] + dy)
44
+
45
+ # Проверка на столкновение со стенами или с собой
46
+ if (head[0] < 0 or head[0] >= COLS or
47
+ head[1] < 0 or head[1] >= ROWS or head in state["snake"]):
48
+ state["game_over"] = True
49
+ return
50
+
51
+ state["snake"].insert(0, head)
52
+
53
+ if head == state["food"]:
54
+ state["score"] += 10
55
+ info.set(f"Счёт: {state['score']}")
56
+ spawn_food()
57
+ else:
58
+ state["snake"].pop()
59
+
60
+ def draw():
61
+ canvas.delete("all")
62
+ # Сетка
63
+ for i in range(0, COLS * CELL, CELL):
64
+ canvas.create_line(i, 0, i, ROWS * CELL, fill="#2a2a2a")
65
+ for j in range(0, ROWS * CELL, CELL):
66
+ canvas.create_line(0, j, COLS * CELL, j, fill="#2a2a2a")
67
+
68
+ # Еда
69
+ fx, fy = state["food"]
70
+ canvas.create_oval(fx * CELL + 3, fy * CELL + 3,
71
+ (fx + 1) * CELL - 3, (fy + 1) * CELL - 3,
72
+ fill="#ff5252", outline="")
73
+
74
+ # Змейка
75
+ for i, (x, y) in enumerate(state["snake"]):
76
+ color = "#8fff8f" if i == 0 else "#4caf50"
77
+ canvas.create_rectangle(x * CELL, y * CELL,
78
+ (x + 1) * CELL, (y + 1) * CELL,
79
+ fill=color, outline="#1e1e1e")
80
+
81
+ # Экран проигрыша
82
+ if state["game_over"]:
83
+ canvas.create_text(COLS * CELL // 2, ROWS * CELL // 2 - 15,
84
+ text="GAME OVER", fill="white",
85
+ font=("Arial", 24, "bold"))
86
+ canvas.create_text(COLS * CELL // 2, ROWS * CELL // 2 + 20,
87
+ text="Нажмите ПРОБЕЛ для рестарта", fill="#aaaaaa",
88
+ font=("Arial", 12))
89
+
90
+ def on_key(event):
91
+ key = event.keysym
92
+
93
+ # Если игра окончена - ждем пробел для рестарта
94
+ if state["game_over"]:
95
+ if key == "space":
96
+ state["snake"] = [(10, 10), (9, 10), (8, 10)]
97
+ state["dir"] = (1, 0)
98
+ state["score"] = 0
99
+ state["game_over"] = False
100
+ info.set("Счёт: 0")
101
+ spawn_food()
102
+ draw()
103
+ return
104
+
105
+ # Управление
106
+ current = state["dir"]
107
+ if key == "Left" and current != (1, 0):
108
+ state["dir"] = (-1, 0)
109
+ elif key == "Right" and current != (-1, 0):
110
+ state["dir"] = (1, 0)
111
+ elif key == "Up" and current != (0, 1):
112
+ state["dir"] = (0, -1)
113
+ elif key == "Down" and current != (0, -1):
114
+ state["dir"] = (0, 1)
115
+
116
+ root.bind("<Key>", on_key)
117
+
118
+ def loop():
119
+ step()
120
+ draw()
121
+ root.after(state["speed"], loop)
122
+
123
+ loop()
124
+ canvas.focus_set()
125
+ root.mainloop()
justcode/gui/tetris.py ADDED
@@ -0,0 +1,160 @@
1
+ import random
2
+ import tkinter as tk
3
+
4
+ COLS, ROWS = 10, 20
5
+ CELL = 28
6
+
7
+ SHAPES = [
8
+ [[1, 1, 1, 1]], # I
9
+ [[1, 1], [1, 1]], # O
10
+ [[0, 1, 0], [1, 1, 1]], # T
11
+ [[1, 0, 0], [1, 1, 1]], # L
12
+ [[0, 0, 1], [1, 1, 1]], # J
13
+ [[0, 1, 1], [1, 1, 0]], # S
14
+ [[1, 1, 0], [0, 1, 1]], # Z
15
+ ]
16
+ COLORS = ["cyan", "yellow", "magenta", "orange", "blue", "green", "red"]
17
+
18
+
19
+ def tetris():
20
+ """GUI Тетрис."""
21
+ root = tk.Tk()
22
+ root.title("Тетрис")
23
+ root.resizable(False, False)
24
+
25
+ canvas = tk.Canvas(root, width=COLS * CELL, height=ROWS * CELL, bg="black")
26
+ canvas.pack(side="left", padx=5, pady=5)
27
+
28
+ side = tk.Frame(root)
29
+ side.pack(side="right", fill="y", padx=5, pady=5)
30
+ score_var = tk.StringVar(value="Счёт: 0")
31
+ tk.Label(side, textvariable=score_var, font=("Arial", 14, "bold")).pack(pady=10)
32
+ tk.Label(side, text="Управление:", font=("Arial", 11, "bold")).pack()
33
+ tk.Label(side, text="← → — движение\n↑ — поворот\n↓ — ускорить\nПробел — падение\nP — пауза",
34
+ justify="left").pack(pady=5)
35
+
36
+ # Поле храним как список списков
37
+ board = [[None] * COLS for _ in range(ROWS)]
38
+
39
+ state = {"piece": None, "color": None, "px": 0, "py": 0,
40
+ "score": 0, "paused": False, "game_over": False}
41
+
42
+ def new_piece():
43
+ idx = random.randrange(len(SHAPES))
44
+ state["piece"] = [row[:] for row in SHAPES[idx]]
45
+ state["color"] = COLORS[idx]
46
+ state["px"] = COLS // 2 - len(state["piece"][0]) // 2
47
+ state["py"] = 0
48
+ if collide(state["px"], state["py"], state["piece"]):
49
+ state["game_over"] = True
50
+
51
+ def collide(px, py, piece):
52
+ for r, row in enumerate(piece):
53
+ for c, val in enumerate(row):
54
+ if not val:
55
+ continue
56
+ x, y = px + c, py + r
57
+ if x < 0 or x >= COLS or y >= ROWS:
58
+ return True
59
+ if y >= 0 and board[y][x]:
60
+ return True
61
+ return False
62
+
63
+ def merge():
64
+ for r, row in enumerate(state["piece"]):
65
+ for c, val in enumerate(row):
66
+ if val:
67
+ board[state["py"] + r][state["px"] + c] = state["color"]
68
+
69
+ def clear_lines():
70
+ # Создаем новый список, оставляя только неполные ряды
71
+ new_board = [row for row in board if any(v is None for v in row)]
72
+ cleared = ROWS - len(new_board)
73
+ for _ in range(cleared):
74
+ new_board.insert(0, [None] * COLS)
75
+
76
+ # Обновляем board на месте
77
+ for i in range(ROWS):
78
+ board[i] = new_board[i]
79
+
80
+ if cleared:
81
+ state["score"] += [0, 100, 300, 500, 800][cleared]
82
+ score_var.set(f"Счёт: {state['score']}")
83
+
84
+ def rotate():
85
+ piece = state["piece"]
86
+ rotated = [list(row) for row in zip(*piece[::-1])]
87
+ if not collide(state["px"], state["py"], rotated):
88
+ state["piece"] = rotated
89
+
90
+ def move(dx):
91
+ if not collide(state["px"] + dx, state["py"], state["piece"]):
92
+ state["px"] += dx
93
+
94
+ def drop():
95
+ if not collide(state["px"], state["py"] + 1, state["piece"]):
96
+ state["py"] += 1
97
+ else:
98
+ merge()
99
+ clear_lines()
100
+ new_piece()
101
+
102
+ def hard_drop():
103
+ while not collide(state["px"], state["py"] + 1, state["piece"]):
104
+ state["py"] += 1
105
+ drop()
106
+
107
+ def draw():
108
+ canvas.delete("all")
109
+ for r in range(ROWS):
110
+ for c in range(COLS):
111
+ if board[r][c]:
112
+ canvas.create_rectangle(c * CELL, r * CELL,
113
+ (c + 1) * CELL, (r + 1) * CELL,
114
+ fill=board[r][c], outline="#222")
115
+ if state["piece"]:
116
+ for r, row in enumerate(state["piece"]):
117
+ for c, val in enumerate(row):
118
+ if val:
119
+ x = (state["px"] + c) * CELL
120
+ y = (state["py"] + r) * CELL
121
+ canvas.create_rectangle(x, y, x + CELL, y + CELL,
122
+ fill=state["color"], outline="#222")
123
+ if state["paused"]:
124
+ canvas.create_text(COLS * CELL // 2, ROWS * CELL // 2,
125
+ text="ПАУЗА", fill="white", font=("Arial", 24, "bold"))
126
+ if state["game_over"]:
127
+ canvas.create_text(COLS * CELL // 2, ROWS * CELL // 2,
128
+ text="GAME OVER", fill="red", font=("Arial", 22, "bold"))
129
+
130
+ def on_key(event):
131
+ if state["game_over"]:
132
+ return
133
+ key = event.keysym
134
+ if key == "p":
135
+ state["paused"] = not state["paused"]
136
+ if state["paused"]:
137
+ return
138
+ if key == "Left":
139
+ move(-1)
140
+ elif key == "Right":
141
+ move(1)
142
+ elif key == "Down":
143
+ drop()
144
+ elif key == "Up":
145
+ rotate()
146
+ elif key == "space":
147
+ hard_drop()
148
+
149
+ root.bind("<Key>", on_key)
150
+
151
+ def tick():
152
+ if not state["paused"] and not state["game_over"]:
153
+ drop()
154
+ draw()
155
+ root.after(500, tick)
156
+
157
+ new_piece()
158
+ tick()
159
+ canvas.focus_set()
160
+ root.mainloop()
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: justcode
3
+ Version: 1.0.0
4
+ Summary: Библиотека мини-проектов: калькулятор, тетрис, змейка, генератор паролей
5
+ Author-email: Ваше Имя <you@example.com>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Operating System :: OS Independent
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+
11
+ # justcode
12
+
13
+ Библиотека готовых мини-проектов на Python: калькулятор, тетрис, змейка, генератор паролей.
14
+
15
+ ## Установка
16
+ ```bash
17
+ pip install justcode
18
+
@@ -0,0 +1,15 @@
1
+ justcode/__init__.py,sha256=5s4m3v9JTOblc7tNLRNpB3ThqSEXGgKCkcv4NltbD2c,87
2
+ justcode/__main__.py,sha256=HBvDAnXoxi9e0FT0aPrwCqT2LayAo_KkVCjnCtD5FdI,669
3
+ justcode/cli/__init__.py,sha256=LnxTW8AStZBAl_JAV4XMdMXn5_AYCZGnNP2sHCm0FXA,88
4
+ justcode/cli/calc.py,sha256=GQIsux0mcYwVhkfNX_ZvHJeYIGVGqNiRqJvcC6WsbAE,1500
5
+ justcode/cli/password.py,sha256=lpQuJh0l4GQwWsK2yQfMdrbIZ3f3cZgjwrfCfVbaywM,1316
6
+ justcode/gui/__init__.py,sha256=lXm7w606i7hRFgXZghAkZly8BxthXsApsn5icrGqTg8,161
7
+ justcode/gui/calc.py,sha256=dGq_tapoh_vvzfl2kuSEwMuUi6CYFa66zP6pudOubHE,1877
8
+ justcode/gui/password.py,sha256=E36X2bS0eRTRWiePtt4kPrJrx6bO4JcnQ0lire0_RqU,2394
9
+ justcode/gui/snake.py,sha256=1OffK8H4T6zWeSRVFno_-5mZFJ-lkJZLAbLcszR1iZQ,4094
10
+ justcode/gui/tetris.py,sha256=GKmqcdqwWtmflfT7dyw1abwGW5NbFhVbJkAtWyhwj0Y,5695
11
+ justcode-1.0.0.dist-info/METADATA,sha256=S--rY21bhpw31eKwc7_dyD6QrpeGv22yBP8mhz6LlBE,647
12
+ justcode-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ justcode-1.0.0.dist-info/entry_points.txt,sha256=qwRJ-BqFD-goviyKDvP1w-6KG8hMcH35n3dZuSpCSAM,52
14
+ justcode-1.0.0.dist-info/top_level.txt,sha256=hS0rdlcOd8IxGqI2Ow5UkU-ny3U2V33tLQpvUYARi5g,9
15
+ justcode-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ justcode = justcode.__main__:main
@@ -0,0 +1 @@
1
+ justcode