Метапромптінг з ChatGPT: пишемо Sudoku за годину
Всі знають, що ChatGPT вміє писати будь-якою мовою включаючи мови програмування. Але чи замінить він коли-небудь програмістів? Почнемо з малої форми. Я спробую написати щось за допомогою ШІ протягом однієї години.
Мені захотілось написати імплементацію головоломки sudoku, щось типу того, що можна робити на Sudoku by CB. А саме — фронтендну імплементацію судоку, де можна отримати нову головоломку, заповнювати її за допомогою спливаючого віконечка, мати валідацію та підказки.
Я хотів би отримати готовий код, який взагалі не потрібно ніяк доробляти. Для цього я використовую метапромптінг: я не тільки не хочу писати сам код, я ще й не хочу писати сам необхідний для цього детальний промпт. Замість цього, я пишу промпт, який напише промпт, який напише код.
I want to write a sudoku-solving SPA app. It should have following structure: index.html with all the interface, styles.css for styling, generate_sudoku.js for generation of sudoku puzzles, app.js for solving sudoku puzzles and other functionality. It goes like this: user is presented with sudoku. Every table cell in sudoku that doesn’t have number initially, is clickable. On click, a popup appears with standards numpad to enter a number. Only available numbers are active (numbers in same line, column and square are excluded). If sudoku becomes invalid, number is red. Ask me additional questions and write a prompt for LLM that would produce needed code
У відповідь chatGPT спитав мене наступне:
Here are a few clarifying questions that will help ensure the app meets your expectations:
- Difficulty Levels: Would you like different difficulty levels for Sudoku generation (easy, medium, hard)?
- Validation: Should the app validate the Sudoku puzzle automatically as users input numbers, or should it be triggered by a button (e.g., “Check Solution”)?
- Popup Design: How would you like the popup for entering numbers to look—should it be a simple overlay with number buttons, or would you prefer a custom design (e.g., mobile-friendly numpad layout)?
- Undo/Reset: Would you like an undo or reset button to allow users to revert changes?
- Hints: Should there be a “Hint” feature that suggests a correct number for a selected cell?
Once you confirm or provide additional input, I’ll draft the prompt for generating the code.
Відповідаю коротко:
1. Yes, make “start new game” button that would call a popup with three difficulty options for initiating new sudoku.
2. Automatically, plus numbers should be inactive for specific cell’s numpad
3. Simple overlay
4. no need
5. no
І ось промпт для кода першої версії
Generate the code for a Sudoku-solving single-page app (SPA) with the following structure:
- index.html — A minimalistic interface that displays the Sudoku grid, a ’Start New Game’ button that triggers a popup for selecting difficulty (easy, medium, hard), and popups for selecting numbers for Sudoku cells.
- styles.css — Styling for the Sudoku grid (9×9 table), highlighting the currently active cell, marking invalid numbers in red, and styling popups (e.g., difficulty selection and numpad overlay).
- generate_sudoku.js — Logic for generating valid Sudoku puzzles for easy, medium, and hard difficulties. This script should fill the grid with a puzzle, leaving some cells empty for the user to solve.
- app.js — Core Sudoku solving functionality. This script should:
- Allow the user to click on empty cells and open a simple overlay with a numpad
(1-9). - Disable numpad options that conflict with the row, column, or 3×3 square.
- Automatically validate the puzzle as the user enters numbers, turning invalid entries red.
Additional Details:
- The Sudoku table should have clickable cells. When a user clicks on an empty cell, an overlay popup should appear with numbers
(1-9) as buttons.- Only numbers that are not in the same row, column, or 3×3 box should be active. Invalid options should be disabled.
- The app should automatically validate numbers as they are entered. If a number makes the Sudoku invalid, it should be highlighted in red.
- Include a ’Start New Game’ button that triggers a difficulty selection popup (Easy, Medium, Hard).
- CSS should handle grid layout and simple popup/overlay styling.
Please ensure the code is well-commented and ready to be integrated.
Я несу його в окрему табу, запускаю новий чат, виконую, отримаю код всіх файлів, зберігаю їх, що вийшло можно подивитись тут. В принципі, виглядає майже нормально, генерує судоки, правда, суровим рендомом, як можна побачити в коді
function generateSudoku(difficulty) { const grid = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ]; // Adjust the number of clues based on difficulty let emptyCells; if (difficulty === ’easy’) emptyCells = 40; if (difficulty === ’medium’) emptyCells = 50; if (difficulty === ’hard’) emptyCells = 60; // Randomly remove numbers from the grid based on difficulty for (let i = 0; i < emptyCells; i++) { let row = Math.floor(Math.random() * 9); let col = Math.floor(Math.random() * 9); grid[row][col] = 0; } return grid; }
Що ж, переходжу в перший тред к своєму метапромпту, і інструктую chatGPT по змінах:
rewrite, considering following:
— valid sudoku must be generated, algorithm based on random numbers won’t do
— levels are too hard, there should be other numbers in complexity (50% unknown numbers for easy, 70% for hard)
— sudoku design should include inner 3×3 squares outline
В новому промпті з’являються відповідні зміни:
Generate the code for a Sudoku-solving single-page app (SPA) with the following structure:
- index.html — A minimalistic interface displaying:
- A 9×9 Sudoku grid.
- A ’Start New Game’ button that triggers a popup with three difficulty levels: Easy (50% unknown cells), Medium (60% unknown cells), Hard (70% unknown cells).
- Popup overlays for selecting numbers for each empty cell, and basic layout including the grid’s 3×3 inner square outlines.
- styles.css — Styling for:
- The Sudoku grid, ensuring that 3×3 sub-grids are clearly outlined.
- Highlighting the currently selected cell.
- Invalid numbers should be styled in red when the puzzle becomes invalid.
- Popup/overlay designs for selecting difficulty and for entering numbers (a simple numpad-style interface).
- generate_sudoku.js — This script must use a backtracking algorithm to generate valid, complete Sudoku boards, and then strategically remove numbers according to the difficulty level:
- For Easy, 50% of the numbers should be removed from the grid.
- For Medium, 60% of the numbers should be removed.
- For Hard, 70% of the numbers should be removed.
- Ensure that the resulting puzzles have a unique solution by validating the removals.
- app.js — Handles the Sudoku gameplay and solving functionality:
- Allow users to click on empty cells, which triggers a simple popup with number buttons
(1-9). - Disable any numbers in the numpad that conflict with existing numbers in the same row, column, or 3×3 square.
- Automatically validate the puzzle as numbers are entered. If an entry makes the Sudoku invalid, the number should be highlighted in red.
- Ensure valid inputs remain visible and update the puzzle dynamically.
Additional Details:
- The Sudoku grid should clearly show the 3×3 sub-grid outlines, to help players easily recognize the layout.
- The ’Start New Game’ button should trigger a popup allowing users to choose the difficulty (Easy, Medium, Hard). The selected difficulty will control how many cells are left blank for the player to fill.
- Ensure the backtracking algorithm used for Sudoku generation produces valid puzzles with a unique solution.
- The user should be able to interact with empty cells by clicking, which brings up a simple overlay popup displaying numbers
1-9. Only valid numbers should be clickable in the popup.- Automatically validate the puzzle as users fill in numbers, highlighting incorrect numbers in red.
Please ensure that the code is modular and well-commented for ease of integration and further customization
Результат другої ітерації можна побачити тут.
Ось що попросив наступним кроком:
rewrite prompt considering following:
— instead of disabling numbers on a numpad, let’s allow entering any number. If sudoku becomes invalid
— mark this number red.
— make cells bigger
— if three or less numbers are still possible for an empy cell, show theese numbers in the cell with grey font
Це принесло третю версію де замість дізейбла цифр в нампаді вводу я вирішив підказувати в клітинках де залишилось три чи меньше варіанта.
Далі я додав, поступово:
rewrite considering:— special mode where possible numbers are shown in empty cells should be connected to a button “hint” button
— if entered number makes sudoku invalid, write this number in red.
rewrite considering:
— add button to turn hinting on and off
rewrite considering:— cells that were empty at the beginning of the game must be editable with the same popup with numpad
— ensure that initially available numbers and user-entered numbers are looking different
— click on a cell that was initially empty should always bring numpad popup
rewrite considering following:
— there are three states for each cell: initially filled with number while creating sudoku, filled by user and valid (didn’t invalidate sudoku when entered), and filled by used and invalid. First should have slightly grey background, second white bg and black color, third
— white bg and red color.
— there should be a numpad available for any cell that was not initially filled — sudoku should be square, take as much space as possible, and be centred on the screen
За годину вдалось прокрутити сім ітерацій і отримати таку версію. В ній все виглядає класно по лейауту, можна вводити і редагувати цифри, видаляти, валідація робить червоним, все, що я від нього хотів. Що ж за промт вийшов в фіналі? Ось він:
Generate the code for a Sudoku-solving single-page app (SPA) with the following structure and functionality:
- index.html — A minimalistic interface displaying:
- A 9×9 Sudoku grid that dynamically resizes, taking up 90% of the available viewport while remaining square and centered on the screen.
- A ’Start New Game’ button that triggers a popup with three difficulty levels: Easy (50% unknown cells), Medium (60% unknown cells), Hard (70% unknown cells).
- A ’Hint’ button to toggle hint mode on and off, showing possible numbers in grey font inside empty cells where three or fewer valid numbers remain.
- A numpad overlay popup available for any cell that was not initially filled with a number.
- styles.css — Styling for:
- A dynamically sized Sudoku grid where the cell size is calculated initially so that the entire grid takes up 90% of the available viewport width or height (whichever is smaller), and it remains centered on the screen.
- Three distinct visual states for the cells:
- Initially filled cells (numbers filled when the Sudoku is generated):
- Slightly grey background with bold, dark text to differentiate from user input.
- User-filled cells (valid):
- White background with black text.
- User-filled cells (invalid):
- White background with red text when a number creates an invalid state (automatically validated).
- Clear outlines for the 3×3 sub-grid sections.
- Styling for the numpad, popups, and the ’Hint’ mode.
- generate_sudoku.js — A script that:
- Uses a backtracking algorithm to generate valid, complete Sudoku boards.
- Removes a specific percentage of numbers based on the difficulty level:
- Easy: 50% of the numbers removed.
- Medium: 60% of the numbers removed.
- Hard: 70% of the numbers removed.
- Ensures that the puzzle remains solvable and has a unique solution even after removing numbers.
- app.js — Handles the Sudoku gameplay and solving functionality:
- For any cell that was not initially filled, clicking it should always trigger a numpad popup to allow users to select a number
(1-9). - Three distinct states for each cell:
- Initially filled cells are non-editable and have a slightly grey background with bold, dark numbers.
- User-filled cells (valid) will have a white background with black text.
- User-filled cells (invalid), where the number creates an invalid state (conflicts in row, column, or 3×3 sub-grid), will have a white background with red text.
- Automatically validate the grid as numbers are entered. If a number creates an invalid state, it should immediately turn red.
- A ’Hint’ button that toggles on/off:
- When ’Hint’ mode is on, display possible numbers in grey font inside empty cells where three or fewer valid numbers remain.
- When ’Hint’ mode is off, hide these hints.
- Dynamically update the grid based on user input, ensuring that valid numbers are retained and the visual state of each cell is updated.
Additional Details:
- The Sudoku grid should be designed to take up 90% of the viewport (width or height, whichever is smaller) and be square. The cell size should be calculated initially to ensure that the grid fits into this space and stays centered.
- The ’Start New Game’ button should trigger a difficulty selection popup (Easy, Medium, Hard), controlling how many cells are left blank.
- For any cell that was not filled initially, the user can click on it to bring up a numpad for number entry. If the user enters a number that makes the Sudoku invalid, the number should turn red.
- Differentiate between initial, pre-filled cells (grey background, bold numbers) and user-filled cells (white background for both valid and invalid entries, with red text for invalid numbers).
- Ensure the Sudoku is generated using a backtracking algorithm to ensure a unique, valid solution, with a difficulty-specific number of cells left blank.
Please ensure the code is modular, well-commented, and easily customizable.
Спробуйте його на вашому LLM of choice. Працює? Звичайно, це дуже маленький проект, але і часу я витратив ровно одну годину. І схоже, що в таких масштабах ШІ може виявитися дуже конкурентним.
Підписуйтеся на Telegram-канал «DOU #tech», щоб не пропустити нові технічні статті
25 коментарів
Додати коментар Підписатись на коментаріВідписатись від коментарів