১. শুরু করার আগে
ধরুন আপনাকে জিজ্ঞাসা করা হলো বিশ্বের বৃহত্তম ক্রসওয়ার্ড পাজল তৈরি করা সম্ভব কিনা। আপনার স্কুলে শেখা কিছু এআই কৌশলের কথা মনে পড়ল এবং আপনি ভাবতে লাগলেন যে, কম্পিউটেশনালি ইনটেনসিভ সমস্যাগুলোর সমাধান তৈরির জন্য অ্যালগরিদমিক বিকল্পগুলো অন্বেষণ করতে আপনি ফ্লাটার ব্যবহার করতে পারবেন কিনা।
এই কোডল্যাবে আপনি ঠিক সেটাই করবেন। শেষে, আপনি ওয়ার্ড গ্রিড পাজল তৈরির অ্যালগরিদম নিয়ে কাজ করার জন্য একটি টুল তৈরি করবেন। একটি বৈধ ক্রসওয়ার্ড পাজলের অনেক ভিন্ন ভিন্ন সংজ্ঞা রয়েছে এবং এই কৌশলগুলো আপনাকে আপনার সংজ্ঞার সাথে মানানসই পাজল তৈরি করতে সাহায্য করে।

এই টুলটিকে ভিত্তি করে, আপনি একটি ক্রসওয়ার্ড পাজল তৈরি করতে পারেন যা ব্যবহারকারীর সমাধানের জন্য ক্রসওয়ার্ড জেনারেটর ব্যবহার করে পাজলটি তৈরি করে। এই পাজলটি অ্যান্ড্রয়েড, আইওএস, উইন্ডোজ, ম্যাকওএস এবং লিনাক্সে ব্যবহারযোগ্য। অ্যান্ড্রয়েডে এটি নিচে দেওয়া হলো:

পূর্বশর্ত
- আপনার প্রথম ফ্লাটার অ্যাপ কোডল্যাবের সমাপ্তি
আপনি যা শিখবেন
- ফ্লাটারের
computeফাংশন এবং রিভারপডেরselectrebuild ফিল্টারের ভ্যালু-ক্যাশিং ক্ষমতার সমন্বয়ে, কীভাবে ফ্লাটারের রেন্ডার লুপে বাধা না দিয়ে গণনাগতভাবে ব্যয়বহুল কাজ করা যায়। -
built_valueএবংbuilt_collectionমতো অপরিবর্তনীয় ডেটা স্ট্রাকচার ব্যবহার করে কীভাবে ডেপথ-ফার্স্ট সার্চ এবং ব্যাকট্র্যাকিং-এর মতো অনুসন্ধান-ভিত্তিক পুরোনো দিনের এআই (GOFAI) কৌশলগুলো বাস্তবায়ন করা যায়। -
two_dimensional_scrollablesপ্যাকেজের সুবিধাগুলো ব্যবহার করে কীভাবে দ্রুত এবং সহজবোধ্য উপায়ে গ্রিড ডেটা প্রদর্শন করা যায়।
আপনার যা প্রয়োজন
- ফ্লাটার এসডিকে ।
- ফ্লাটার এবং ডার্ট প্লাগইন সহ ভিজ্যুয়াল স্টুডিও কোড (ভিএস কোড)।
- আপনার নির্বাচিত ডেভেলপমেন্ট টার্গেটের জন্য কম্পাইলার সফটওয়্যার। এই কোডল্যাবটি সকল ডেস্কটপ প্ল্যাটফর্ম, অ্যান্ড্রয়েড এবং আইওএস-এর জন্য কাজ করে। উইন্ডোজ টার্গেট করার জন্য আপনার ভিএস কোড, ম্যাকওএস বা আইওএস টার্গেট করার জন্য এক্সকোড এবং অ্যান্ড্রয়েড টার্গেট করার জন্য অ্যান্ড্রয়েড স্টুডিও প্রয়োজন।
২. একটি প্রকল্প তৈরি করুন
আপনার প্রথম ফ্লাটার প্রজেক্ট তৈরি করুন
- ভিএস কোড চালু করুন।
- কমান্ড প্যালেট খুলুন (Windows/Linux-এ Ctrl+Shift+P, macOS-এ Cmd+Shift+P), "flutter new" টাইপ করুন এবং তারপর মেনু থেকে Flutter: New Project নির্বাচন করুন।

- ‘খালি অ্যাপ্লিকেশন’ (Empty application) নির্বাচন করুন এবং তারপরে আপনার প্রজেক্ট তৈরি করার জন্য একটি ডিরেক্টরি বেছে নিন। এটি এমন যেকোনো ডিরেক্টরি হতে পারে যার জন্য বিশেষ অনুমতির (elevated privileges) প্রয়োজন হয় না অথবা যার পাথে (path) কোনো স্পেস নেই। উদাহরণস্বরূপ, আপনার হোম ডিরেক্টরি বা
C:\src\।

- আপনার প্রজেক্টের নাম দিন
generate_crossword। এই কোডল্যাবের বাকি অংশটি ধরে নিচ্ছে যে আপনি আপনার অ্যাপের নামওgenerate_crosswordরেখেছেন।

ফ্লাটার এখন আপনার প্রজেক্ট ফোল্ডার তৈরি করবে এবং ভিএস কোড সেটি খুলবে। এখন আপনি অ্যাপটির একটি প্রাথমিক কাঠামো দিয়ে দুটি ফাইলের বিষয়বস্তু ওভাররাইট করবেন।
প্রাথমিক অ্যাপটি কপি এবং পেস্ট করুন
- VS Code-এর বাম প্যানে, Explorer-এ ক্লিক করুন এবং
pubspec.yamlফাইলটি খুলুন।

- ক্রসওয়ার্ড তৈরির জন্য প্রয়োজনীয় নিম্নলিখিত ডিপেন্ডেন্সিগুলো দিয়ে এই ফাইলের বিষয়বস্তু প্রতিস্থাপন করুন:
pubspec.yaml
name: generate_crossword
description: "A new Flutter project."
publish_to: 'none'
version: 0.1.0
environment:
sdk: ^3.9.0
dependencies:
flutter:
sdk: flutter
built_collection: ^5.1.1
built_value: ^8.10.1
characters: ^1.4.0
flutter_riverpod: ^2.6.1
intl: ^0.20.2
riverpod: ^2.6.1
riverpod_annotation: ^2.6.1
two_dimensional_scrollables: ^0.3.7
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
build_runner: ^2.5.4
built_value_generator: ^8.10.1
custom_lint: ^0.7.6
riverpod_generator: ^2.6.5
riverpod_lint: ^2.6.5
flutter:
uses-material-design: true
pubspec.yaml ফাইলটি আপনার অ্যাপের মৌলিক তথ্য, যেমন এর বর্তমান সংস্করণ এবং এর নির্ভরতাগুলো নির্দিষ্ট করে। আপনি এমন কিছু নির্ভরতার সমাহার দেখতে পান যা একটি সাধারণ খালি ফ্লাটার অ্যাপের অংশ নয়। পরবর্তী ধাপগুলোতে আপনি এই সমস্ত প্যাকেজ থেকে উপকৃত হবেন।
নির্ভরশীলতা বোঝা
কোডে প্রবেশ করার আগে, চলুন জেনে নেওয়া যাক কেন এই নির্দিষ্ট প্যাকেজগুলো বেছে নেওয়া হয়েছে:
- built_value : অপরিবর্তনীয় অবজেক্ট তৈরি করে যা দক্ষতার সাথে মেমরি শেয়ার করে, যা আমাদের ব্যাকট্র্যাকিং অ্যালগরিদমের জন্য অত্যন্ত গুরুত্বপূর্ণ।
- রিভারপড : রিবিল্ড কমানোর জন্য
select()এর মাধ্যমে সূক্ষ্ম স্টেট ম্যানেজমেন্ট প্রদান করে। - two_dimensional_scrollables : পারফরম্যান্সের কোনো ক্ষতি ছাড়াই বড় গ্রিড পরিচালনা করে
-
lib/ডিরেক্টরিতে থাকাmain.dartফাইলটি খুলুন।

- এই ফাইলের বিষয়বস্তু নিম্নলিখিত দ্বারা প্রতিস্থাপন করুন:
lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
title: 'Crossword Builder',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorSchemeSeed: Colors.blueGrey,
brightness: Brightness.light,
),
home: Scaffold(
body: Center(
child: Text('Hello, World!', style: TextStyle(fontSize: 24)),
),
),
),
),
);
}
- সবকিছু ঠিকঠাক কাজ করছে কিনা তা পরীক্ষা করতে এই কোডটি চালান। এটি একটি নতুন উইন্ডো প্রদর্শন করবে, যেখানে সর্বত্র প্রতিটি নতুন প্রকল্পের জন্য বাধ্যতামূলক সূচনা বাক্যটি থাকবে। এখানে একটি
ProviderScopeরয়েছে যা নির্দেশ করে যে এই অ্যাপটি স্টেট ম্যানেজমেন্টের জন্যriverpodব্যবহার করবে।

চেকপয়েন্ট: বেসিক অ্যাপ চলছে
এই পর্যায়ে, আপনি একটি "Hello, World!" উইন্ডো দেখতে পাবেন। যদি না দেখেন:
- ফ্লাটার সঠিকভাবে ইনস্টল করা হয়েছে কিনা তা পরীক্ষা করুন।
-
flutter runদিয়ে অ্যাপটি চলছে কিনা তা যাচাই করুন। - টার্মিনালে কোনো কম্পাইলেশন ত্রুটি নেই তা নিশ্চিত করুন।
৩. শব্দ যোগ করুন
ক্রসওয়ার্ড পাজলের জন্য বিল্ডিং ব্লক
ক্রসওয়ার্ড মূলত শব্দের একটি তালিকা। শব্দগুলো একটি ছকে সাজানো থাকে, কিছু পাশাপাশি, কিছু লম্বালম্বি, এমনভাবে যাতে শব্দগুলো একে অপরের সাথে যুক্ত হয়। একটি শব্দ সমাধান করলে সেই প্রথম শব্দটির সাথে ছেদকারী শব্দগুলো সম্পর্কে সূত্র পাওয়া যায়। সুতরাং, একটি ভালো প্রাথমিক ভিত্তি হলো শব্দের একটি তালিকা।
এই শব্দগুলোর জন্য পিটার নরভিগের ন্যাচারাল ল্যাঙ্গুয়েজ কর্পাস ডেটা পেজটি একটি ভালো উৎস। SOWPODS তালিকাটি একটি কার্যকরী সূচনা বিন্দু, যেখানে ২৬৭,৭৫০টি শব্দ রয়েছে।
এই ধাপে, আপনি শব্দের একটি তালিকা ডাউনলোড করে সেটিকে আপনার ফ্লাটার অ্যাপের একটি অ্যাসেট হিসেবে যুক্ত করবেন এবং অ্যাপটি চালু হওয়ার সময় তালিকাটি লোড করার জন্য একটি রিভারপড প্রোভাইডারের ব্যবস্থা করবেন।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
- আপনার নির্বাচিত শব্দ তালিকার জন্য নিম্নলিখিত অ্যাসেট ডিক্লারেশনটি যোগ করতে আপনার প্রোজেক্টের
pubspec.yamlফাইলটি পরিবর্তন করুন। এই তালিকাটি আপনার অ্যাপের কনফিগারেশনের শুধুমাত্র ফ্লাটার স্ট্যানজাটি দেখাচ্ছে, কারণ বাকি সবকিছু অপরিবর্তিত রয়েছে।
pubspec.yaml
flutter:
uses-material-design: true
assets: # Add this line
- assets/words.txt # And this one.
আপনার এডিটর সম্ভবত এই শেষ লাইনটি একটি সতর্কবার্তা দিয়ে হাইলাইট করবে, কারণ আপনি এখনও এই ফাইলটি তৈরি করেননি।
- আপনার ব্রাউজার এবং এডিটর ব্যবহার করে, আপনার প্রোজেক্টের টপ লেভেলে একটি
assetsডিরেক্টরি তৈরি করুন এবং এর ভেতরে পূর্বে লিঙ্ক করা শব্দতালিকাগুলোর মধ্যে একটি দিয়ে একটিwords.txtফাইল তৈরি করুন।
এই কোডটি পূর্বে উল্লিখিত SOWPODS তালিকাটিকে মাথায় রেখে ডিজাইন করা হয়েছে, কিন্তু এটি শুধুমাত্র AZ অক্ষর দিয়ে গঠিত যেকোনো শব্দ তালিকার সাথেই কাজ করবে। এই কোডবেসটিকে বিভিন্ন ক্যারেক্টার সেটের সাথে কাজ করার উপযোগী করে তোলার কাজটি পাঠকের জন্য একটি অনুশীলন হিসেবে রেখে দেওয়া হলো।
শব্দগুলো লোড করুন
অ্যাপ চালু হওয়ার সময় শব্দ তালিকা লোড করার জন্য কোড লিখতে, এই ধাপগুলো অনুসরণ করুন:
-
libডিরেক্টরিতেproviders.dartএকটি ফাইল তৈরি করুন। - ফাইলটিতে নিম্নলিখিতগুলি যোগ করুন:
lib/providers.dart
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:flutter/services.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'providers.g.dart';
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
// This codebase requires that all words consist of lowercase characters
// in the range 'a'-'z'. Words containing uppercase letters will be
// lowercased, and words containing runes outside this range will
// be removed.
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter()
.convert(words)
.toBuiltSet()
.rebuild(
(b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)),
);
}
এই কোডবেসের জন্য এটি আপনার প্রথম রিভারপড প্রোভাইডার।
এই প্রদানকারী যেভাবে কাজ করে:
- অ্যাসেট থেকে শব্দ তালিকাটি অ্যাসিঙ্ক্রোনাসভাবে লোড করে।
- ২ অক্ষরের চেয়ে দীর্ঘ শব্দগুলিতে শুধুমাত্র 'az' অক্ষর অন্তর্ভুক্ত করার জন্য ফিল্টার করে।
- দক্ষ র্যান্ডম অ্যাক্সেসের জন্য একটি অপরিবর্তনীয়
BuiltSetফেরত দেয়।
এই প্রজেক্টটি রিভারপড সহ একাধিক ডিপেন্ডেন্সির জন্য কোড জেনারেশন ব্যবহার করে।
- কোড তৈরি করা শুরু করতে, নিম্নলিখিত কমান্ডটি চালান:
$ dart run build_runner watch -d [INFO] Generating build script completed, took 174ms [INFO] Setting up file watchers completed, took 5ms [INFO] Waiting for all file watchers to be ready completed, took 202ms [INFO] Reading cached asset graph completed, took 65ms [INFO] Checking for updates since last build completed, took 680ms [INFO] Running build completed, took 2.3s [INFO] Caching finalized dependency graph completed, took 42ms [INFO] Succeeded after 2.3s with 122 outputs (243 actions)
এটি ব্যাকগ্রাউন্ডে চলতে থাকবে এবং আপনি প্রজেক্টে পরিবর্তন আনার সাথে সাথে তৈরি হওয়া ফাইলগুলো আপডেট করতে থাকবে। এই কমান্ডটি providers.g.dart এ কোড তৈরি করে ফেলার পর, আপনার এডিটর providers.dart এ যোগ করা কোডটি নিয়ে সন্তুষ্ট থাকবে।
রিভারপডে, আপনার পূর্বে সংজ্ঞায়িত করা wordList ফাংশনের মতো প্রোভাইডারগুলো সাধারণত লেজিলি ইনস্ট্যানশিয়েট করা হয়। তবে, এই অ্যাপটির প্রয়োজনে আপনার ওয়ার্ড লিস্টটি ইগারলি লোড করার দরকার। রিভারপডের ডকুমেন্টেশনে, যে প্রোভাইডারগুলো ইগারলি লোড করা প্রয়োজন, সেগুলোর জন্য নিম্নলিখিত পদ্ধতির পরামর্শ দেওয়া হয়েছে। আপনি এখন সেটিই ইমপ্লিমেন্ট করবেন।
-
lib/widgetsডিরেক্টরিতেcrossword_generator_app.dartনামে একটি ফাইল তৈরি করুন। - ফাইলটিতে নিম্নলিখিতগুলি যোগ করুন:
lib/widgets/crossword_generator_app.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
class CrosswordGeneratorApp extends StatelessWidget {
const CrosswordGeneratorApp({super.key});
@override
Widget build(BuildContext context) {
return _EagerInitialization(
child: Scaffold(
appBar: AppBar(
titleTextStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 16,
fontWeight: FontWeight.bold,
),
title: Text('Crossword Generator'),
),
body: SafeArea(
child: Consumer(
builder: (context, ref, _) {
final wordListAsync = ref.watch(wordListProvider);
return wordListAsync.when(
data: (wordList) => ListView.builder(
itemCount: wordList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(wordList.elementAt(index)));
},
),
error: (error, stackTrace) => Center(child: Text('$error')),
loading: () => Center(child: CircularProgressIndicator()),
);
},
),
),
),
);
}
}
class _EagerInitialization extends ConsumerWidget {
const _EagerInitialization({required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(wordListProvider);
return child;
}
}
এই ফাইলটি দুটি ভিন্ন দিক থেকে আকর্ষণীয়। প্রথমটি হলো _EagerInitialization উইজেট, যার একমাত্র কাজ হলো আপনার পূর্বে তৈরি করা wordList প্রোভাইডারকে শব্দতালিকাটি লোড করতে বাধ্য করা। এই উইজেটটি ref.watch() কল ব্যবহার করে প্রোভাইডারকে শোনার মাধ্যমে এই উদ্দেশ্যটি সম্পন্ন করে। আপনি প্রোভাইডারদের ইগার ইনিশিয়ালাইজেশন বিষয়ে রিভারপড ডকুমেন্টেশনে এই কৌশলটি সম্পর্কে আরও পড়তে পারেন।
এই ফাইলটিতে লক্ষ্য করার মতো দ্বিতীয় আকর্ষণীয় বিষয়টি হলো রিভারপড কীভাবে অ্যাসিঙ্ক্রোনাস কন্টেন্ট পরিচালনা করে। আপনার হয়তো মনে আছে, wordList প্রোভাইডারটিকে একটি অ্যাসিঙ্ক্রোনাস ফাংশন হিসেবে সংজ্ঞায়িত করা হয়েছে, কারণ ডিস্ক থেকে কন্টেন্ট লোড করা ধীরগতির। এই কোডে wordlist প্রোভাইডারটি পর্যবেক্ষণ করলে, আপনি একটি AsyncValue<BuiltSet<String>> পাবেন। ওই টাইপের AsyncValue অংশটি প্রোভাইডারদের অ্যাসিঙ্ক্রোনাস জগৎ এবং উইজেটের build মেথডের সিঙ্ক্রোনাস জগতের মধ্যে একটি অ্যাডাপ্টার হিসেবে কাজ করে।
AsyncValue এর when মেথডটি ফিউচার ভ্যালুটির তিনটি সম্ভাব্য অবস্থা পরিচালনা করে। ফিউচারটি সফলভাবে রিজলভ হয়ে থাকতে পারে, সেক্ষেত্রে data কলব্যাকটি কল করা হয়; এটি কোনো এরর অবস্থায় থাকতে পারে, সেক্ষেত্রে এরর error কল করা হয়; অথবা সবশেষে, এটি তখনও লোড হতে থাকতে পারে। তিনটি কলব্যাকের রিটার্ন টাইপ অবশ্যই সামঞ্জস্যপূর্ণ হতে হবে, কারণ when মেথডটি কল করা কলব্যাকের রিটার্নটিই ফেরত দেয়। এই ক্ষেত্রে, when মেথডের ফলাফলটি Scaffold উইজেটের body হিসেবে প্রদর্শিত হয়।
একটি প্রায় অসীম তালিকা অ্যাপ তৈরি করুন
আপনার অ্যাপে CrosswordGeneratorApp উইজেটটি যুক্ত করতে, এই ধাপগুলো অনুসরণ করুন:
- নিম্নলিখিত কোডটি যোগ করে
lib/main.dartফাইলটি আপডেট করুন:
lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'widgets/crossword_generator_app.dart'; // Add this import
void main() {
runApp(
ProviderScope(
child: MaterialApp(
title: 'Crossword Builder',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorSchemeSeed: Colors.blueGrey,
brightness: Brightness.light,
),
home: CrosswordGeneratorApp(), // Remove what was here and replace
),
),
);
}
- অ্যাপটি পুনরায় চালু করুন। আপনি একটি স্ক্রোলিং তালিকা দেখতে পাবেন যা অভিধানের সমস্ত ২৬৭,৭৫০টিরও বেশি শব্দ পর্যায়ক্রমে দেখাবে।

এরপর আপনি যা নির্মাণ করবেন
এখন আপনি অপরিবর্তনীয় অবজেক্ট ব্যবহার করে আপনার ক্রসওয়ার্ড পাজলের জন্য মূল ডেটা স্ট্রাকচারগুলো তৈরি করবেন। এই ভিত্তিটি কার্যকর অ্যালগরিদম এবং মসৃণ UI আপডেট সক্ষম করবে।
৪. শব্দগুলো একটি গ্রিডে প্রদর্শন করুন।
এই ধাপে, আপনি built_value এবং built_collection প্যাকেজ ব্যবহার করে একটি ক্রসওয়ার্ড পাজল তৈরির জন্য একটি ডেটা স্ট্রাকচার তৈরি করবেন। এই দুটি প্যাকেজ অপরিবর্তনীয় মান (immutable values) হিসেবে ডেটা স্ট্রাকচার তৈরি করতে সক্ষম করে, যা আইসোলেটগুলোর (Isolates) মধ্যে ডেটা আদান-প্রদানের জন্য এবং ডেপথ ফার্স্ট সার্চ (depth first search) ও ব্যাকট্র্যাকিং (backtracking) বাস্তবায়নকে অনেক সহজ করে তোলার জন্য উপকারী হবে।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
-
libডিরেক্টরিতে একটিmodel.dartফাইল তৈরি করুন এবং তারপর ফাইলটিতে নিম্নলিখিত বিষয়বস্তু যোগ করুন:
lib/model.dart
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:characters/characters.dart';
part 'model.g.dart';
/// A location in a crossword.
abstract class Location implements Built<Location, LocationBuilder> {
static Serializer<Location> get serializer => _$locationSerializer;
/// The horizontal part of the location. The location is 0 based.
int get x;
/// The vertical part of the location. The location is 0 based.
int get y;
/// Returns a new location that is one step to the left of this location.
Location get left => rebuild((b) => b.x = x - 1);
/// Returns a new location that is one step to the right of this location.
Location get right => rebuild((b) => b.x = x + 1);
/// Returns a new location that is one step up from this location.
Location get up => rebuild((b) => b.y = y - 1);
/// Returns a new location that is one step down from this location.
Location get down => rebuild((b) => b.y = y + 1);
/// Returns a new location that is [offset] steps to the left of this location.
Location leftOffset(int offset) => rebuild((b) => b.x = x - offset);
/// Returns a new location that is [offset] steps to the right of this location.
Location rightOffset(int offset) => rebuild((b) => b.x = x + offset);
/// Returns a new location that is [offset] steps up from this location.
Location upOffset(int offset) => rebuild((b) => b.y = y - offset);
/// Returns a new location that is [offset] steps down from this location.
Location downOffset(int offset) => rebuild((b) => b.y = y + offset);
/// Pretty print a location as a (x,y) coordinate.
String prettyPrint() => '($x,$y)';
/// Returns a new location built from [updates]. Both [x] and [y] are
/// required to be non-null.
factory Location([void Function(LocationBuilder)? updates]) = _$Location;
Location._();
/// Returns a location at the given coordinates.
factory Location.at(int x, int y) {
return Location((b) {
b
..x = x
..y = y;
});
}
}
/// The direction of a word in a crossword.
enum Direction {
across,
down;
@override
String toString() => name;
}
/// A word in a crossword. This is a word at a location in a crossword, in either
/// the across or down direction.
abstract class CrosswordWord
implements Built<CrosswordWord, CrosswordWordBuilder> {
static Serializer<CrosswordWord> get serializer => _$crosswordWordSerializer;
/// The word itself.
String get word;
/// The location of this word in the crossword.
Location get location;
/// The direction of this word in the crossword.
Direction get direction;
/// Compare two CrosswordWord by coordinates, x then y.
static int locationComparator(CrosswordWord a, CrosswordWord b) {
final compareRows = a.location.y.compareTo(b.location.y);
final compareColumns = a.location.x.compareTo(b.location.x);
return switch (compareColumns) {
0 => compareRows,
_ => compareColumns,
};
}
/// Constructor for [CrosswordWord].
factory CrosswordWord.word({
required String word,
required Location location,
required Direction direction,
}) {
return CrosswordWord(
(b) => b
..word = word
..direction = direction
..location.replace(location),
);
}
/// Constructor for [CrosswordWord].
/// Use [CrosswordWord.word] instead.
factory CrosswordWord([void Function(CrosswordWordBuilder)? updates]) =
_$CrosswordWord;
CrosswordWord._();
}
/// A character in a crossword. This is a single character at a location in a
/// crossword. It may be part of an across word, a down word, both, but not
/// neither. The neither constraint is enforced elsewhere.
abstract class CrosswordCharacter
implements Built<CrosswordCharacter, CrosswordCharacterBuilder> {
static Serializer<CrosswordCharacter> get serializer =>
_$crosswordCharacterSerializer;
/// The character at this location.
String get character;
/// The across word that this character is a part of.
CrosswordWord? get acrossWord;
/// The down word that this character is a part of.
CrosswordWord? get downWord;
/// Constructor for [CrosswordCharacter].
/// [acrossWord] and [downWord] are optional.
factory CrosswordCharacter.character({
required String character,
CrosswordWord? acrossWord,
CrosswordWord? downWord,
}) {
return CrosswordCharacter((b) {
b.character = character;
if (acrossWord != null) {
b.acrossWord.replace(acrossWord);
}
if (downWord != null) {
b.downWord.replace(downWord);
}
});
}
/// Constructor for [CrosswordCharacter].
/// Use [CrosswordCharacter.character] instead.
factory CrosswordCharacter([
void Function(CrosswordCharacterBuilder)? updates,
]) = _$CrosswordCharacter;
CrosswordCharacter._();
}
/// A crossword puzzle. This is a grid of characters with words placed in it.
/// The puzzle constraint is in the English crossword puzzle tradition.
abstract class Crossword implements Built<Crossword, CrosswordBuilder> {
/// Serializes and deserializes the [Crossword] class.
static Serializer<Crossword> get serializer => _$crosswordSerializer;
/// Width across the [Crossword] puzzle.
int get width;
/// Height down the [Crossword] puzzle.
int get height;
/// The words in the crossword.
BuiltList<CrosswordWord> get words;
/// The characters by location. Useful for displaying the crossword.
BuiltMap<Location, CrosswordCharacter> get characters;
/// Add a word to the crossword at the given location and direction.
Crossword addWord({
required Location location,
required String word,
required Direction direction,
}) {
return rebuild(
(b) => b
..words.add(
CrosswordWord.word(
word: word,
direction: direction,
location: location,
),
),
);
}
/// As a finalize step, fill in the characters map.
@BuiltValueHook(finalizeBuilder: true)
static void _fillCharacters(CrosswordBuilder b) {
b.characters.clear();
for (final word in b.words.build()) {
for (final (idx, character) in word.word.characters.indexed) {
switch (word.direction) {
case Direction.across:
b.characters.updateValue(
word.location.rightOffset(idx),
(b) => b.rebuild((bInner) => bInner.acrossWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
acrossWord: word,
character: character,
),
);
case Direction.down:
b.characters.updateValue(
word.location.downOffset(idx),
(b) => b.rebuild((bInner) => bInner.downWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
downWord: word,
character: character,
),
);
}
}
}
}
/// Pretty print a crossword. Generates the character grid, and lists
/// the down words and across words sorted by location.
String prettyPrintCrossword() {
final buffer = StringBuffer();
final grid = List.generate(
height,
(_) => List.generate(
width,
(_) => '░', // https://www.compart.com/en/unicode/U+2591
),
);
for (final MapEntry(key: Location(:x, :y), value: character)
in characters.entries) {
grid[y][x] = character.character;
}
for (final row in grid) {
buffer.writeln(row.join());
}
buffer.writeln();
buffer.writeln('Across:');
for (final word
in words.where((word) => word.direction == Direction.across).toList()
..sort(CrosswordWord.locationComparator)) {
buffer.writeln('${word.location.prettyPrint()}: ${word.word}');
}
buffer.writeln();
buffer.writeln('Down:');
for (final word
in words.where((word) => word.direction == Direction.down).toList()
..sort(CrosswordWord.locationComparator)) {
buffer.writeln('${word.location.prettyPrint()}: ${word.word}');
}
return buffer.toString();
}
/// Constructor for [Crossword].
factory Crossword.crossword({
required int width,
required int height,
Iterable<CrosswordWord>? words,
}) {
return Crossword((b) {
b
..width = width
..height = height;
if (words != null) {
b.words.addAll(words);
}
});
}
/// Constructor for [Crossword].
/// Use [Crossword.crossword] instead.
factory Crossword([void Function(CrosswordBuilder)? updates]) = _$Crossword;
Crossword._();
}
/// Construct the serialization/deserialization code for the data model.
@SerializersFor([Location, Crossword, CrosswordWord, CrosswordCharacter])
final Serializers serializers = _$serializers;
এই ফাইলটি সেই ডেটা স্ট্রাকচারের সূচনা বর্ণনা করে যা আপনি ক্রসওয়ার্ড তৈরির জন্য ব্যবহার করবেন। মূলতঃ, একটি ক্রসওয়ার্ড পাজল হলো একটি গ্রিডে পরস্পর সংযুক্ত অনুভূমিক এবং উল্লম্ব শব্দের একটি তালিকা। এই ডেটা স্ট্রাকচারটি ব্যবহার করার জন্য, আপনি Crossword.crossword নামক কনস্ট্রাক্টর দিয়ে উপযুক্ত আকারের একটি Crossword তৈরি করবেন, তারপর addWord মেথড ব্যবহার করে শব্দ যোগ করবেন। চূড়ান্ত মানটি তৈরির অংশ হিসেবে, _fillCharacters মেথডের মাধ্যমে CrosswordCharacter এর একটি গ্রিড তৈরি করা হয়।
এই ডেটা স্ট্রাকচারটি ব্যবহার করতে, নিম্নলিখিত ধাপগুলো অনুসরণ করুন:
-
libডিরেক্টরিতে একটিutilsফাইল তৈরি করুন এবং তারপর ফাইলটিতে নিম্নলিখিত বিষয়বস্তু যোগ করুন:
lib/utils.dart
import 'dart:math';
import 'package:built_collection/built_collection.dart';
/// A [Random] instance for generating random numbers.
final _random = Random();
/// An extension on [BuiltSet] that adds a method to get a random element.
extension RandomElements<E> on BuiltSet<E> {
E randomElement() {
return elementAt(_random.nextInt(length));
}
}
এটি BuiltSet এর একটি এক্সটেনশন যা সেটের যেকোনো একটি উপাদানকে অনায়াসে পুনরুদ্ধার করতে সাহায্য করে। এক্সটেনশন মেথডগুলো হলো অতিরিক্ত কার্যকারিতা দিয়ে ক্লাসকে প্রসারিত করার একটি ভালো উপায়। utils.dart ফাইলের বাইরে এক্সটেনশনটি উপলব্ধ করার জন্য এটির নামকরণ করা আবশ্যক।
- আপনার
lib/providers.dartফাইলে নিম্নলিখিত ইম্পোর্টগুলো যোগ করুন:
lib/providers.dart
import 'dart:convert';
import 'dart:math'; // Add this import
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart'; // Add this import
import 'package:flutter/services.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'model.dart' as model; // And this import
import 'utils.dart'; // And this one
part 'providers.g.dart';
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(WordListRef ref) async {
এই ইম্পোর্টগুলো পূর্বে সংজ্ঞায়িত মডেলটিকে আপনার তৈরি করতে যাওয়া প্রোভাইডারগুলোর কাছে উন্মুক্ত করে। Random এর জন্য dart:math ইম্পোর্ট, debugPrint এর জন্য flutter/foundation.dart , মডেলের জন্য model.dart এবং BuiltSet এক্সটেনশনের জন্য utils.dart অন্তর্ভুক্ত করা হয়েছে।
- একই ফাইলের শেষে নিম্নলিখিত প্রোভাইডারগুলো যোগ করুন:
lib/providers.dart
/// An enumeration for different sizes of [model.Crossword]s.
enum CrosswordSize {
small(width: 20, height: 11),
medium(width: 40, height: 22),
large(width: 80, height: 44),
xlarge(width: 160, height: 88),
xxlarge(width: 500, height: 500);
const CrosswordSize({required this.width, required this.height});
final int width;
final int height;
String get label => '$width x $height';
}
/// A provider that holds the current size of the crossword to generate.
@Riverpod(keepAlive: true)
class Size extends _$Size {
var _size = CrosswordSize.medium;
@override
CrosswordSize build() => _size;
void setSize(CrosswordSize size) {
_size = size;
ref.invalidateSelf();
}
}
final _random = Random();
@riverpod
Stream<model.Crossword> crossword(Ref ref) async* {
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
var crossword = model.Crossword.crossword(
width: size.width,
height: size.height,
);
yield* wordListAsync.when(
data: (wordList) async* {
while (crossword.characters.length < size.width * size.height * 0.8) {
final word = wordList.randomElement();
final direction = _random.nextBool()
? model.Direction.across
: model.Direction.down;
final location = model.Location.at(
_random.nextInt(size.width),
_random.nextInt(size.height),
);
crossword = crossword.addWord(
word: word,
direction: direction,
location: location,
);
yield crossword;
await Future.delayed(Duration(milliseconds: 100));
}
yield crossword;
},
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield crossword;
},
loading: () async* {
yield crossword;
},
);
}
এই পরিবর্তনগুলো আপনার অ্যাপে দুটি প্রোভাইডার যোগ করে। প্রথমটি হলো Size , যা মূলত একটি গ্লোবাল ভ্যারিয়েবল এবং এতে CrosswordSize এনুমারেশনের নির্বাচিত মানটি থাকে। এটি UI-কে নির্মাণাধীন ক্রসওয়ার্ডটি প্রদর্শন এবং তার আকার নির্ধারণ করার সুযোগ দেবে। দ্বিতীয় প্রোভাইডার, crossword , একটি আরও আকর্ষণীয় সংযোজন। এটি একটি ফাংশন যা ধারাবাহিকভাবে কয়েকটি Crossword রিটার্ন করে। ফাংশনটির উপর async* চিহ্ন দ্বারা নির্দেশিত, এটি ডার্টের জেনারেটর সাপোর্ট ব্যবহার করে তৈরি করা হয়েছে। এর মানে হলো, এটি রিটার্ন করে শেষ না হয়ে, ধারাবাহিকভাবে কয়েকটি Crossword প্রদান করে, যা অন্তর্বর্তী ফলাফল প্রদানকারী কোনো গণনা লেখার জন্য অনেক সহজ একটি উপায়।
crossword প্রোভাইডার ফাংশনের শুরুতে একজোড়া ref.watch কল থাকার কারণে, প্রতিবার ক্রসওয়ার্ডের নির্বাচিত আকার পরিবর্তিত হলে এবং শব্দ তালিকা লোড হওয়া শেষ হলে রিভারপড সিস্টেম দ্বারা Crossword প্রবাহটি পুনরায় চালু করা হবে।
এখন যেহেতু আপনার কাছে ক্রসওয়ার্ড তৈরি করার কোড আছে, যদিও তা এলোমেলো শব্দে পূর্ণ, টুলটির ব্যবহারকারীকে সেগুলো দেখাতে পারলে ভালো হতো।
-
lib/widgetsডিরেক্টরিতে নিম্নলিখিত বিষয়বস্তু সহ একটিcrossword_widget.dartফাইল তৈরি করুন:
lib/widgets/crossword_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart';
import '../model.dart';
import '../providers.dart';
class CrosswordWidget extends ConsumerWidget {
const CrosswordWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
return TableView.builder(
diagonalDragBehavior: DiagonalDragBehavior.free,
cellBuilder: _buildCell,
columnCount: size.width,
columnBuilder: (index) => _buildSpan(context, index),
rowCount: size.height,
rowBuilder: (index) => _buildSpan(context, index),
);
}
TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
final location = Location.at(vicinity.column, vicinity.row);
return TableViewCell(
child: Consumer(
builder: (context, ref, _) {
final character = ref.watch(
crosswordProvider.select(
(crosswordAsync) => crosswordAsync.when(
data: (crossword) => crossword.characters[location],
error: (error, stackTrace) => null,
loading: () => null,
),
),
);
if (character != null) {
return Container(
color: Theme.of(context).colorScheme.onPrimary,
child: Center(
child: Text(
character.character,
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.primary,
),
),
),
);
}
return ColoredBox(
color: Theme.of(context).colorScheme.primaryContainer,
);
},
),
);
}
TableSpan _buildSpan(BuildContext context, int index) {
return TableSpan(
extent: FixedTableSpanExtent(32),
foregroundDecoration: TableSpanDecoration(
border: TableSpanBorder(
leading: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
trailing: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
);
}
}
এই উইজেটটি, একটি ConsumerWidget হওয়ায়, Crossword অক্ষরগুলো প্রদর্শনের জন্য গ্রিডের আকার নির্ধারণ করতে সরাসরি Size প্রোভাইডারের উপর নির্ভর করতে পারে। এই গ্রিডটির প্রদর্শন two_dimensional_scrollables প্যাকেজের TableView উইজেটের মাধ্যমে সম্পন্ন করা হয়।
এটি লক্ষণীয় যে, _buildCell হেল্পার ফাংশন দ্বারা রেন্ডার করা প্রতিটি সেলের রিটার্ন করা Widget ট্রি-তে একটি Consumer উইজেট থাকে। এটি একটি রিফ্রেশ বাউন্ডারি হিসেবে কাজ করে। যখন ref.watch এর রিটার্ন করা মান পরিবর্তিত হয়, তখন Consumer উইজেটের ভেতরের সবকিছু পুনরায় তৈরি করা হয়। প্রতিবার Crossword পরিবর্তিত হলে পুরো ট্রি-টি পুনরায় তৈরি করার একটি প্রবণতা থাকতে পারে, তবে এর ফলে প্রচুর গণনার প্রয়োজন হয় যা এই সেটআপ ব্যবহার করে এড়ানো যায়।
আপনি যদি ref.watch এর প্যারামিটারটি দেখেন, তাহলে দেখবেন যে crosswordProvider.select ব্যবহার করে লেআউট পুনঃগণনা এড়ানোর আরেকটি স্তর রয়েছে। এর মানে হলো, ref.watch শুধুমাত্র তখনই TableViewCell এর বিষয়বস্তু পুনঃনির্মাণ শুরু করবে, যখন সেলটি যে অক্ষরটি রেন্ডার করার জন্য দায়ী, সেটি পরিবর্তিত হবে। পুনঃরেন্ডারিং-এর এই হ্রাস UI-কে রেসপন্সিভ রাখার একটি অপরিহার্য অংশ।
ব্যবহারকারীর কাছে CrosswordWidget এবং Size প্রোভাইডার উন্মুক্ত করতে, crossword_generator_app.dart ফাইলটি নিম্নরূপ পরিবর্তন করুন:
lib/widgets/crossword_generator_app.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
import 'crossword_widget.dart'; // Add this import
class CrosswordGeneratorApp extends StatelessWidget {
const CrosswordGeneratorApp({super.key});
@override
Widget build(BuildContext context) {
return _EagerInitialization(
child: Scaffold(
appBar: AppBar(
actions: [_CrosswordGeneratorMenu()], // Add this line
titleTextStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 16,
fontWeight: FontWeight.bold,
),
title: Text('Crossword Generator'),
),
body: SafeArea(child: CrosswordWidget()), // Replace what was here before
),
);
}
}
class _EagerInitialization extends ConsumerWidget {
const _EagerInitialization({required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(wordListProvider);
return child;
}
}
class _CrosswordGeneratorMenu extends ConsumerWidget { // Add from here
@override
Widget build(BuildContext context, WidgetRef ref) => MenuAnchor(
menuChildren: [
for (final entry in CrosswordSize.values)
MenuItemButton(
onPressed: () => ref.read(sizeProvider.notifier).setSize(entry),
leadingIcon: entry == ref.watch(sizeProvider)
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
child: Text(entry.label),
),
],
builder: (context, controller, child) => IconButton(
onPressed: () => controller.open(),
icon: Icon(Icons.settings),
),
); // To here.
}
এখানে কয়েকটি পরিবর্তন করা হয়েছে। প্রথমত, wordList ListView হিসেবে রেন্ডার করার জন্য ব্যবহৃত কোডটি lib/widgets/crossword_widget.dart ফাইলে সংজ্ঞায়িত CrosswordWidget এর একটি কল দ্বারা প্রতিস্থাপিত করা হয়েছে। আরেকটি বড় পরিবর্তন হলো অ্যাপটির আচরণ পরিবর্তনের জন্য একটি মেনুর সূচনা, যা ক্রসওয়ার্ডের আকার পরিবর্তনের মাধ্যমে শুরু হবে। পরবর্তী ধাপগুলোতে আরও MenuItemButton যোগ করা হবে। আপনার অ্যাপটি রান করলে আপনি এইরকম কিছু দেখতে পাবেন:

একটি গ্রিডে অক্ষরগুলো সাজানো আছে এবং একটি মেনু রয়েছে যা ব্যবহারকারীকে গ্রিডের আকার পরিবর্তন করার সুযোগ দেয়। কিন্তু শব্দগুলো ক্রসওয়ার্ড পাজলের মতো করে সাজানো নেই। ক্রসওয়ার্ডে কীভাবে শব্দ যোগ করা হবে, তার ওপর কোনো বিধিনিষেধ আরোপ না করার ফলেই এমনটা হয়েছে। সংক্ষেপে, এটি একটি জগাখিচুড়ি অবস্থা। যা আপনি পরবর্তী ধাপে নিয়ন্ত্রণে আনতে শুরু করবেন!
৫. সীমাবদ্ধতা প্রয়োগ করুন
আমরা কী পরিবর্তন করছি এবং কেন
বর্তমানে আপনার ক্রসওয়ার্ডে কোনো যাচাইকরণ ছাড়াই একটির উপর আরেকটি শব্দ বসার অনুমতি আছে। শব্দগুলো যাতে একটি আসল ক্রসওয়ার্ড পাজলের মতো সঠিকভাবে একে অপরের সাথে যুক্ত হয়, তা নিশ্চিত করতে আপনাকে সীমাবদ্ধতা যাচাইয়ের ব্যবস্থা যোগ করতে হবে।
ক্রসওয়ার্ডের সীমাবদ্ধতাগুলো কার্যকর করার জন্য মডেলে কোড যোগ করাই এই ধাপের লক্ষ্য। বিভিন্ন ধরনের ক্রসওয়ার্ড পাজল রয়েছে, এবং এই কোডল্যাবটি যে শৈলীটি প্রয়োগ করবে তা ইংরেজি ক্রসওয়ার্ড পাজলের ঐতিহ্য অনুসরণ করে। অন্যান্য শৈলীর ক্রসওয়ার্ড পাজল তৈরি করার জন্য এই কোডটি পরিবর্তন করার কাজটি, বরাবরের মতোই, পাঠকের জন্য একটি অনুশীলন হিসেবে রেখে দেওয়া হলো।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
-
model.dartফাইলটি খুলুন এবং শুধুCrosswordmodel-টি নিচের কোড দিয়ে প্রতিস্থাপন করুন:
lib/model.dart
/// A crossword puzzle. This is a grid of characters with words placed in it.
/// The puzzle constraint is in the English crossword puzzle tradition.
abstract class Crossword implements Built<Crossword, CrosswordBuilder> {
/// Serializes and deserializes the [Crossword] class.
static Serializer<Crossword> get serializer => _$crosswordSerializer;
/// Width across the [Crossword] puzzle.
int get width;
/// Height down the [Crossword] puzzle.
int get height;
/// The words in the crossword.
BuiltList<CrosswordWord> get words;
/// The characters by location. Useful for displaying the crossword,
/// or checking the proposed solution.
BuiltMap<Location, CrosswordCharacter> get characters;
/// Checks if this crossword is valid.
bool get valid {
// Check that there are no duplicate words.
final wordSet = words.map((word) => word.word).toBuiltSet();
if (wordSet.length != words.length) {
return false;
}
for (final MapEntry(key: location, value: character)
in characters.entries) {
// All characters must be a part of an across or down word.
if (character.acrossWord == null && character.downWord == null) {
return false;
}
// All characters must be within the crossword puzzle.
// No drawing outside the lines.
if (location.x < 0 ||
location.y < 0 ||
location.x >= width ||
location.y >= height) {
return false;
}
// Characters above and below this character must be related
// by a vertical word
if (characters[location.up] case final up?) {
if (character.downWord == null) {
return false;
}
if (up.downWord != character.downWord) {
return false;
}
}
if (characters[location.down] case final down?) {
if (character.downWord == null) {
return false;
}
if (down.downWord != character.downWord) {
return false;
}
}
// Characters to the left and right of this character must be
// related by a horizontal word
final left = characters[location.left];
if (left != null) {
if (character.acrossWord == null) {
return false;
}
if (left.acrossWord != character.acrossWord) {
return false;
}
}
final right = characters[location.right];
if (right != null) {
if (character.acrossWord == null) {
return false;
}
if (right.acrossWord != character.acrossWord) {
return false;
}
}
}
return true;
}
/// Add a word to the crossword at the given location and direction.
Crossword? addWord({
required Location location,
required String word,
required Direction direction,
}) {
// Require that the word is not already in the crossword.
if (words.map((crosswordWord) => crosswordWord.word).contains(word)) {
return null;
}
final wordCharacters = word.characters;
bool overlap = false;
// Check that the word fits in the crossword.
for (final (index, character) in wordCharacters.indexed) {
final characterLocation = switch (direction) {
Direction.across => location.rightOffset(index),
Direction.down => location.downOffset(index),
};
final target = characters[characterLocation];
if (target != null) {
overlap = true;
if (target.character != character) {
return null;
}
if (direction == Direction.across && target.acrossWord != null ||
direction == Direction.down && target.downWord != null) {
return null;
}
}
}
if (words.isNotEmpty && !overlap) {
return null;
}
final candidate = rebuild(
(b) => b
..words.add(
CrosswordWord.word(
word: word,
direction: direction,
location: location,
),
),
);
if (candidate.valid) {
return candidate;
} else {
return null;
}
}
/// As a finalize step, fill in the characters map.
@BuiltValueHook(finalizeBuilder: true)
static void _fillCharacters(CrosswordBuilder b) {
b.characters.clear();
for (final word in b.words.build()) {
for (final (idx, character) in word.word.characters.indexed) {
switch (word.direction) {
case Direction.across:
b.characters.updateValue(
word.location.rightOffset(idx),
(b) => b.rebuild((bInner) => bInner.acrossWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
acrossWord: word,
character: character,
),
);
case Direction.down:
b.characters.updateValue(
word.location.downOffset(idx),
(b) => b.rebuild((bInner) => bInner.downWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
downWord: word,
character: character,
),
);
}
}
}
}
/// Pretty print a crossword. Generates the character grid, and lists
/// the down words and across words sorted by location.
String prettyPrintCrossword() {
final buffer = StringBuffer();
final grid = List.generate(
height,
(_) => List.generate(
width,
(_) => '░', // https://www.compart.com/en/unicode/U+2591
),
);
for (final MapEntry(key: Location(:x, :y), value: character)
in characters.entries) {
grid[y][x] = character.character;
}
for (final row in grid) {
buffer.writeln(row.join());
}
buffer.writeln();
buffer.writeln('Across:');
for (final word
in words.where((word) => word.direction == Direction.across).toList()
..sort(CrosswordWord.locationComparator)) {
buffer.writeln('${word.location.prettyPrint()}: ${word.word}');
}
buffer.writeln();
buffer.writeln('Down:');
for (final word
in words.where((word) => word.direction == Direction.down).toList()
..sort(CrosswordWord.locationComparator)) {
buffer.writeln('${word.location.prettyPrint()}: ${word.word}');
}
return buffer.toString();
}
/// Constructor for [Crossword].
factory Crossword.crossword({
required int width,
required int height,
Iterable<CrosswordWord>? words,
}) {
return Crossword((b) {
b
..width = width
..height = height;
if (words != null) {
b.words.addAll(words);
}
});
}
/// Constructor for [Crossword].
/// Use [Crossword.crossword] instead.
factory Crossword([void Function(CrosswordBuilder)? updates]) = _$Crossword;
Crossword._();
}
মনে করিয়ে দিচ্ছি, model.dart এবং providers.dart ফাইলগুলিতে আপনি যে পরিবর্তনগুলি করছেন, তার জন্য build_runner চালু থাকা প্রয়োজন, যাতে সংশ্লিষ্ট model.g.dart এবং providers.g.dart ফাইলগুলি আপডেট হয়। যদি এই ফাইলগুলি স্বয়ংক্রিয়ভাবে আপডেট না হয়ে থাকে, dart run build_runner watch -d . কমান্ডটি দিয়ে build_runner আবার চালু করার এটাই উপযুক্ত সময়।
মডেল লেয়ারের এই নতুন সক্ষমতার সুবিধা নিতে হলে, আপনাকে প্রোভাইডার লেয়ারটিকেও সেই অনুযায়ী আপডেট করতে হবে।
- আপনার
providers.dartফাইলটি নিম্নরূপভাবে সম্পাদনা করুন:
lib/providers.dart
import 'dart:convert';
import 'dart:math';
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'model.dart' as model;
import 'utils.dart';
part 'providers.g.dart';
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(WordListRef ref) async {
// This codebase requires that all words consist of lowercase characters
// in the range 'a'-'z'. Words containing uppercase letters will be
// lowercased, and words containing runes outside this range will
// be removed.
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter().convert(words).toBuiltSet().rebuild((b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)));
}
/// An enumeration for different sizes of [model.Crossword]s.
enum CrosswordSize {
small(width: 20, height: 11),
medium(width: 40, height: 22),
large(width: 80, height: 44),
xlarge(width: 160, height: 88),
xxlarge(width: 500, height: 500);
const CrosswordSize({
required this.width,
required this.height,
});
final int width;
final int height;
String get label => '$width x $height';
}
/// A provider that holds the current size of the crossword to generate.
@Riverpod(keepAlive: true)
class Size extends _$Size {
var _size = CrosswordSize.medium;
@override
CrosswordSize build() => _size;
void setSize(CrosswordSize size) {
_size = size;
ref.invalidateSelf();
}
}
final _random = Random();
@riverpod
Stream<model.Crossword> crossword(CrosswordRef ref) async* {
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
var crossword =
model.Crossword.crossword(width: size.width, height: size.height);
yield* wordListAsync.when(
data: (wordList) async* {
while (crossword.characters.length < size.width * size.height * 0.8) {
final word = wordList.randomElement();
final direction =
_random.nextBool() ? model.Direction.across : model.Direction.down;
final location = model.Location.at(
_random.nextInt(size.width), _random.nextInt(size.height));
var candidate = crossword.addWord( // Edit from here
word: word, direction: direction, location: location);
await Future.delayed(Duration(milliseconds: 10));
if (candidate != null) {
debugPrint('Added word: $word');
crossword = candidate;
yield crossword;
} else {
debugPrint('Failed to add word: $word');
} // To here.
}
yield crossword;
},
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield crossword;
},
loading: () async* {
yield crossword;
},
);
}
- আপনার অ্যাপটি চালান। ইউজার ইন্টারফেসে তেমন কিছু দেখা যাচ্ছে না, কিন্তু লগগুলো দেখলে বোঝা যায় যে অনেক কিছুই ঘটছে।

এখানে কী ঘটছে তা নিয়ে ভাবলে দেখা যায়, আমরা যেন দৈবক্রমে একটি ক্রসওয়ার্ড আবির্ভূত হতে দেখছি। Crossword মডেলের addWord মেথডটি এমন যেকোনো প্রস্তাবিত শব্দকে বাতিল করে দিচ্ছে যা বর্তমান ক্রসওয়ার্ডের সাথে খাপ খায় না, তাই এখানে যে আদৌ কোনো শব্দ আবির্ভূত হচ্ছে, সেটাই এক বিরাট বিস্ময়।
কেন ব্যাকগ্রাউন্ড প্রসেসিং-এ স্থানান্তর করবেন?
ক্রসওয়ার্ড তৈরির সময় আপনি হয়তো লক্ষ্য করতে পারেন যে UI সাড়া দেওয়া বন্ধ করে দিচ্ছে। এমনটা হয় কারণ ক্রসওয়ার্ড তৈরিতে হাজার হাজার যাচাইকরণ পরীক্ষা জড়িত থাকে। এই গণনাগুলো ফ্লাটারের ৬০fps রেন্ডারিং লুপকে ব্লক করে দেয়, তাই আপনাকে ভারী গণনাগুলো ব্যাকগ্রাউন্ড আইসোলেটে সরিয়ে নিতে হবে। এর সুবিধা হলো, ব্যাকগ্রাউন্ডে পাজলটি তৈরি হওয়ার সময় UI মসৃণ থাকে।
কোথায় কোন শব্দ ব্যবহার করা হবে তা বেছে নেওয়ার ক্ষেত্রে আরও পদ্ধতিগত হওয়ার প্রস্তুতি হিসেবে, এই গণনাটিকে UI থ্রেড থেকে সরিয়ে একটি ব্যাকগ্রাউন্ড আইসোলেটে নিয়ে যাওয়া খুবই সহায়ক হবে। ফ্লাটারে একবারে বড় কোনো কাজ নিয়ে সেটিকে ব্যাকগ্রাউন্ড আইসোলেটে চালানোর জন্য একটি অত্যন্ত কার্যকর র্যাপার রয়েছে - সেটি হলো compute ফাংশন।
-
providers.dartফাইলে, ক্রসওয়ার্ড প্রোভাইডারটিকে নিম্নরূপে পরিবর্তন করুন:
lib/providers.dart
@riverpod
Stream<model.Crossword> crossword(Ref ref) async* {
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
var crossword = model.Crossword.crossword(
width: size.width,
height: size.height,
);
yield* wordListAsync.when(
data: (wordList) async* {
while (crossword.characters.length < size.width * size.height * 0.8) {
final word = wordList.randomElement();
final direction = _random.nextBool()
? model.Direction.across
: model.Direction.down;
final location = model.Location.at(
_random.nextInt(size.width),
_random.nextInt(size.height),
);
try { // Edit from here
var candidate = await compute((
(String, model.Direction, model.Location) wordToAdd,
) {
final (word, direction, location) = wordToAdd;
return crossword.addWord(
word: word,
direction: direction,
location: location,
);
}, (word, direction, location));
if (candidate != null) {
crossword = candidate;
yield crossword;
}
} catch (e) {
debugPrint('Error running isolate: $e');
} // To here.
}
yield crossword;
},
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield crossword;
},
loading: () async* {
yield crossword;
},
);
}
বিচ্ছিন্ন সীমাবদ্ধতা বোঝা
এই কোডটি কাজ করে, কিন্তু এতে একটি লুকানো সমস্যা আছে। আইসোলেটগুলোর মধ্যে কী ডেটা আদান-প্রদান করা যাবে সে সম্পর্কে কঠোর নিয়ম রয়েছে। সমস্যাটি হলো, ক্লোজারটি প্রোভাইডার রেফারেন্সকে "ক্যাপচার" করে, যা সিরিয়ালাইজ করে অন্য আইসোলেটে পাঠানো যায় না।
সিস্টেম যখন নন-সিরিয়ালাইজেবল ডেটা পাঠানোর চেষ্টা করে, তখন আপনি এটি দেখতে পাবেন:
flutter: Error running isolate: Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _Future@4048458 (see restrictions listed at `SendPort.send()` documentation for more information)
flutter: <- Instance of 'AutoDisposeStreamProviderElement<Crossword>' (from package:riverpod/src/stream_provider.dart)
flutter: <- Context num_variables: 2 <- Context num_variables: 1 parent:{ Context num_variables: 2 }
flutter: <- Context num_variables: 1 parent:{ Context num_variables: 1 parent:{ Context num_variables: 2 } }
flutter: <- Closure: () => Crossword? (from package:generate_crossword/providers.dart)
এটি সেই ক্লোজারের ফলাফল যা compute ব্যাকগ্রাউন্ড isolate-এর কাছে হস্তান্তর করার সময় একটি প্রোভাইডারকে ক্লোজ করে দেয়, যা SendPort.send() এর মাধ্যমে পাঠানো যায় না। এর একটি সমাধান হলো এটি নিশ্চিত করা যে, ক্লোজারটি ক্লোজ করার জন্য এমন কিছু যেন না থাকে যা প্রেরণযোগ্য নয়।
প্রথম ধাপ হলো প্রোভাইডারদেরকে আইসোলেট কোড থেকে আলাদা করা।
- আপনার
libডিরেক্টরিতে একটিisolates.dartফাইল তৈরি করুন এবং তারপর এতে নিম্নলিখিত বিষয়বস্তু যোগ করুন:
lib/isolates.dart
import 'dart:math';
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'model.dart';
import 'utils.dart';
final _random = Random();
Stream<Crossword> exploreCrosswordSolutions({
required Crossword crossword,
required BuiltSet<String> wordList,
}) async* {
while (crossword.characters.length <
crossword.width * crossword.height * 0.8) {
final word = wordList.randomElement();
final direction = _random.nextBool() ? Direction.across : Direction.down;
final location = Location.at(
_random.nextInt(crossword.width),
_random.nextInt(crossword.height),
);
try {
var candidate = await compute(((String, Direction, Location) wordToAdd) {
final (word, direction, location) = wordToAdd;
return crossword.addWord(
word: word,
direction: direction,
location: location,
);
}, (word, direction, location));
if (candidate != null) {
crossword = candidate;
yield crossword;
}
} catch (e) {
debugPrint('Error running isolate: $e');
}
}
}
এই কোডটি আপনার কাছে বেশ পরিচিত মনে হওয়া উচিত। এটি crossword প্রোভাইডারের মূল অংশ, কিন্তু এখন একটি স্বতন্ত্র জেনারেটর ফাংশন হিসেবে। এখন আপনি ব্যাকগ্রাউন্ড আইসোলেট ইনস্ট্যানশিয়েট করার জন্য এই নতুন ফাংশনটি ব্যবহার করতে আপনার providers.dart ফাইলটি আপডেট করতে পারেন।
lib/providers.dart
// Drop the dart:math import, the _random instance moved to isolates.dart
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'isolates.dart'; // Add this import
import 'model.dart' as model;
// Drop the utils.dart import
part 'providers.g.dart';
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
// This codebase requires that all words consist of lowercase characters
// in the range 'a'-'z'. Words containing uppercase letters will be
// lowercased, and words containing runes outside this range will
// be removed.
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter()
.convert(words)
.toBuiltSet()
.rebuild(
(b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)),
);
}
/// An enumeration for different sizes of [model.Crossword]s.
enum CrosswordSize {
small(width: 20, height: 11),
medium(width: 40, height: 22),
large(width: 80, height: 44),
xlarge(width: 160, height: 88),
xxlarge(width: 500, height: 500);
const CrosswordSize({required this.width, required this.height});
final int width;
final int height;
String get label => '$width x $height';
}
/// A provider that holds the current size of the crossword to generate.
@Riverpod(keepAlive: true)
class Size extends _$Size {
var _size = CrosswordSize.medium;
@override
CrosswordSize build() => _size;
void setSize(CrosswordSize size) {
_size = size;
ref.invalidateSelf();
}
}
// Drop the _random instance
@riverpod
Stream<model.Crossword> crossword(Ref ref) async* {
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
final emptyCrossword = model.Crossword.crossword( // Edit from here
width: size.width,
height: size.height,
);
yield* wordListAsync.when(
data: (wordList) => exploreCrosswordSolutions(
crossword: emptyCrossword,
wordList: wordList,
),
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield emptyCrossword;
},
loading: () async* {
yield emptyCrossword; // To here.
},
);
}
এর মাধ্যমে এখন আপনার কাছে এমন একটি টুল আছে যা বিভিন্ন আকারের ক্রসওয়ার্ড পাজল তৈরি করে, এবং পাজলটি সমাধান করার compute একটি ব্যাকগ্রাউন্ড আইসোলেটে সম্পন্ন হয়। এখন, ক্রসওয়ার্ড পাজলে কোন শব্দগুলো যোগ করার চেষ্টা করা হবে, সেই সিদ্ধান্ত নেওয়ার ক্ষেত্রে কোডটি যদি আরও বেশি কার্যকর হতে পারত।
৬. কাজের সারি পরিচালনা করুন
অনুসন্ধান কৌশল বোঝা
আপনার ক্রসওয়ার্ড তৈরিতে ব্যাকট্র্যাকিং ব্যবহার করা হয়, যা একটি নিয়মতান্ত্রিক পরীক্ষা-নিরীক্ষার পদ্ধতি। প্রথমে আপনার অ্যাপটি একটি নির্দিষ্ট স্থানে একটি শব্দ বসানোর চেষ্টা করে, তারপর দেখে যে শব্দটি বিদ্যমান শব্দগুলোর সাথে খাপ খায় কি না। যদি খাপ খায়, তবে শব্দটি রেখে দিয়ে পরের শব্দটি চেষ্টা করা হয়। আর যদি না মেলে, তবে শব্দটি সরিয়ে দিয়ে অন্য কোথাও চেষ্টা করা হয়।
ক্রসওয়ার্ডের ক্ষেত্রে ব্যাকট্র্যাকিং কার্যকর, কারণ প্রতিটি শব্দ বসানোর স্থান পরবর্তী শব্দগুলোর জন্য সীমাবদ্ধতা তৈরি করে, যেখানে ভুল বসানোর স্থানগুলো দ্রুত শনাক্ত করে বাদ দেওয়া হয়। অপরিবর্তনীয় ডেটা স্ট্রাকচার পরিবর্তনগুলোকে পূর্বাবস্থায় ফিরিয়ে আনাকে দক্ষ করে তোলে।
বর্তমান কোডটির একটি সমস্যা হলো, যে সমস্যাটির সমাধান করা হচ্ছে তা মূলত একটি অনুসন্ধান সমস্যা, এবং বর্তমান সমাধানটি অন্ধভাবে অনুসন্ধান করছে। কোডটি যদি গ্রিডের যেকোনো জায়গায় এলোমেলোভাবে শব্দ বসানোর চেষ্টা না করে, বরং বর্তমান শব্দগুলোর সাথে যুক্ত হবে এমন শব্দ খোঁজার উপর মনোযোগ দেয়, তাহলে সিস্টেমটি আরও দ্রুত সমাধান খুঁজে পাবে। এই সমস্যার একটি সমাধান হতে পারে, শব্দ খোঁজার জন্য বিভিন্ন অবস্থানের একটি ওয়ার্ক কিউ (work queue) চালু করা।
কোডটি সম্ভাব্য সমাধান তৈরি করে, সমাধানটি বৈধ কিনা তা পরীক্ষা করে এবং বৈধতার উপর নির্ভর করে সেটিকে অন্তর্ভুক্ত করে অথবা বাতিল করে দেয়। এটি ব্যাকট্র্যাকিং অ্যালগরিদম পরিবারের একটি উদাহরণমূলক বাস্তবায়ন। built_value এবং built_collection এর মাধ্যমে এই বাস্তবায়নটি অনেক সহজ হয়ে যায়, যা এমন নতুন অপরিবর্তনীয় মান তৈরি করতে সক্ষম করে যা তার পূর্ববর্তী অপরিবর্তনীয় মানের সাথে একই অবস্থা (state) ধারণ করে এবং সেই অনুযায়ী তা শেয়ার করে। এর ফলে ডিপ কপিং-এর জন্য প্রয়োজনীয় মেমরি খরচ ছাড়াই সম্ভাব্য সমাধানগুলোকে স্বল্প খরচে ব্যবহার করা সম্ভব হয়।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
-
model.dartফাইলটি খুলুন এবং এতে নিম্নলিখিতWorkQueueসংজ্ঞাটি যোগ করুন:
lib/model.dart
/// Constructor for [Crossword].
/// Use [Crossword.crossword] instead.
factory Crossword([void Function(CrosswordBuilder)? updates]) = _$Crossword;
Crossword._();
}
// Add from here
/// A work queue for a worker to process. The work queue contains a crossword
/// and a list of locations to try, along with candidate words to add to the
/// crossword.
abstract class WorkQueue implements Built<WorkQueue, WorkQueueBuilder> {
static Serializer<WorkQueue> get serializer => _$workQueueSerializer;
/// The crossword the worker is working on.
Crossword get crossword;
/// The outstanding queue of locations to try.
BuiltMap<Location, Direction> get locationsToTry;
/// Known bad locations.
BuiltSet<Location> get badLocations;
/// The list of unused candidate words that can be added to this crossword.
BuiltSet<String> get candidateWords;
/// Returns true if the work queue is complete.
bool get isCompleted => locationsToTry.isEmpty || candidateWords.isEmpty;
/// Create a work queue from a crossword.
static WorkQueue from({
required Crossword crossword,
required Iterable<String> candidateWords,
required Location startLocation,
}) => WorkQueue((b) {
if (crossword.words.isEmpty) {
// Strip candidate words too long to fit in the crossword
b.candidateWords.addAll(
candidateWords.where(
(word) => word.characters.length <= crossword.width,
),
);
b.crossword.replace(crossword);
b.locationsToTry.addAll({startLocation: Direction.across});
} else {
// Assuming words have already been stripped to length
b.candidateWords.addAll(
candidateWords.toBuiltSet().rebuild(
(b) => b.removeAll(crossword.words.map((word) => word.word)),
),
);
b.crossword.replace(crossword);
crossword.characters
.rebuild(
(b) => b.removeWhere((location, character) {
if (character.acrossWord != null && character.downWord != null) {
return true;
}
final left = crossword.characters[location.left];
if (left != null && left.downWord != null) return true;
final right = crossword.characters[location.right];
if (right != null && right.downWord != null) return true;
final up = crossword.characters[location.up];
if (up != null && up.acrossWord != null) return true;
final down = crossword.characters[location.down];
if (down != null && down.acrossWord != null) return true;
return false;
}),
)
.forEach((location, character) {
b.locationsToTry.addAll({
location: switch ((character.acrossWord, character.downWord)) {
(null, null) => throw StateError(
'Character is not part of a word',
),
(null, _) => Direction.across,
(_, null) => Direction.down,
(_, _) => throw StateError('Character is part of two words'),
},
});
});
}
});
WorkQueue remove(Location location) => rebuild(
(b) => b
..locationsToTry.remove(location)
..badLocations.add(location),
);
/// Update the work queue from a crossword derived from the current crossword
/// that this work queue is built from.
WorkQueue updateFrom(final Crossword crossword) =>
WorkQueue.from(
crossword: crossword,
candidateWords: candidateWords,
startLocation: locationsToTry.isNotEmpty
? locationsToTry.keys.first
: Location.at(0, 0),
).rebuild(
(b) => b
..badLocations.addAll(badLocations)
..locationsToTry.removeWhere(
(location, _) => badLocations.contains(location),
),
);
/// Factory constructor for [WorkQueue]
factory WorkQueue([void Function(WorkQueueBuilder)? updates]) = _$WorkQueue;
WorkQueue._();
} // To here.
/// Construct the serialization/deserialization code for the data model.
@SerializersFor([
Location,
Crossword,
CrosswordWord,
CrosswordCharacter,
WorkQueue, // Add this line
])
final Serializers serializers = _$serializers;
- এই নতুন কন্টেন্ট যোগ করার পরেও যদি ফাইলটিতে কয়েক সেকেন্ডের বেশি সময় ধরে লাল আঁকাবাঁকা দাগ থেকে যায়, তাহলে নিশ্চিত করুন যে আপনার
build_runnerএখনও চলছে। যদি না চলে,dart run build_runner watch -dকমান্ডটি চালান।
আপনার কোডে বিভিন্ন আকারের ক্রসওয়ার্ড তৈরি করতে কত সময় লাগে তা দেখানোর জন্য লগিং যুক্ত করতে চলেছেন। Durations-এর যদি সুন্দরভাবে ফরম্যাট করা কোনো ডিসপ্লে থাকত, তবে বেশ ভালো হতো। সৌভাগ্যবশত, এক্সটেনশন মেথডের সাহায্যে আমরা ঠিক আমাদের প্রয়োজনীয় মেথডটি যোগ করতে পারি।
-
utils.dartফাইলটি নিম্নরূপভাবে সম্পাদনা করুন:
lib/utils.dart
import 'dart:math';
import 'package:built_collection/built_collection.dart';
/// A [Random] instance for generating random numbers.
final _random = Random();
/// An extension on [BuiltSet] that adds a method to get a random element.
extension RandomElements<E> on BuiltSet<E> {
E randomElement() {
return elementAt(_random.nextInt(length));
}
}
// Add from here
/// An extension on [Duration] that adds a method to format the duration.
extension DurationFormat on Duration {
/// A human-readable string representation of the duration.
/// This format is tuned for durations in the seconds to days range.
String get formatted {
final hours = inHours.remainder(24).toString().padLeft(2, '0');
final minutes = inMinutes.remainder(60).toString().padLeft(2, '0');
final seconds = inSeconds.remainder(60).toString().padLeft(2, '0');
return switch ((inDays, inHours, inMinutes, inSeconds)) {
(0, 0, 0, _) => '${inSeconds}s',
(0, 0, _, _) => '$inMinutes:$seconds',
(0, _, _, _) => '$inHours:$minutes:$seconds',
_ => '$inDays days, $hours:$minutes:$seconds',
};
}
} // To here.
এই এক্সটেনশন মেথডটি সেকেন্ড থেকে দিন পর্যন্ত বিভিন্ন সময়কাল প্রদর্শনের উপযুক্ত উপায় নির্বাচন করতে সুইচ এক্সপ্রেশন এবং রেকর্ডের উপর প্যাটার্ন ম্যাচিং ব্যবহার করে। এই ধরনের কোড সম্পর্কে আরও তথ্যের জন্য, "Dive into Dart's patterns and records" কোডল্যাবটি দেখুন।
- এই নতুন কার্যকারিতাটি অন্তর্ভুক্ত করতে,
isolates.dartফাইলটি প্রতিস্থাপন করেexploreCrosswordSolutionsফাংশনটির সংজ্ঞা নিম্নরূপভাবে পরিবর্তন করুন:
lib/isolates.dart
import 'package:built_collection/built_collection.dart';
import 'package:characters/characters.dart';
import 'package:flutter/foundation.dart';
import 'model.dart';
import 'utils.dart';
Stream<Crossword> exploreCrosswordSolutions({
required Crossword crossword,
required BuiltSet<String> wordList,
}) async* {
final start = DateTime.now();
var workQueue = WorkQueue.from(
crossword: crossword,
candidateWords: wordList,
startLocation: Location.at(0, 0),
);
while (!workQueue.isCompleted) {
final location = workQueue.locationsToTry.keys.toBuiltSet().randomElement();
try {
final crossword = await compute(((WorkQueue, Location) workMessage) {
final (workQueue, location) = workMessage;
final direction = workQueue.locationsToTry[location]!;
final target = workQueue.crossword.characters[location];
if (target == null) {
return workQueue.crossword.addWord(
direction: direction,
location: location,
word: workQueue.candidateWords.randomElement(),
);
}
var words = workQueue.candidateWords.toBuiltList().rebuild(
(b) => b
..where((b) => b.characters.contains(target.character))
..shuffle(),
);
int tryCount = 0;
for (final word in words) {
tryCount++;
for (final (index, character) in word.characters.indexed) {
if (character != target.character) continue;
final candidate = workQueue.crossword.addWord(
location: switch (direction) {
Direction.across => location.leftOffset(index),
Direction.down => location.upOffset(index),
},
word: word,
direction: direction,
);
if (candidate != null) {
return candidate;
}
}
if (tryCount > 1000) {
break;
}
}
}, (workQueue, location));
if (crossword != null) {
workQueue = workQueue.updateFrom(crossword);
yield crossword;
} else {
workQueue = workQueue.remove(location);
}
} catch (e) {
debugPrint('Error running isolate: $e');
}
}
debugPrint(
'${crossword.width} x ${crossword.height} Crossword generated in '
'${DateTime.now().difference(start).formatted}',
);
}
এই কোডটি চালালে এমন একটি অ্যাপ তৈরি হবে যা দেখতে হুবহু একই রকম, কিন্তু পার্থক্যটা হলো একটি সম্পূর্ণ ক্রসওয়ার্ড পাজল খুঁজে পেতে যে সময় লাগে তাতে। এখানে ১ মিনিট ২৯ সেকেন্ডে তৈরি করা একটি ৮০ x ৪৪ ক্রসওয়ার্ড পাজল দেখানো হলো।
চেকপয়েন্ট: কার্যকর অ্যালগরিদম কাজ করছে
আপনার ক্রসওয়ার্ড তৈরি এখন উল্লেখযোগ্যভাবে দ্রুততর হবে, যার কারণ হলো:
- ছেদ বিন্দু লক্ষ্য করে বুদ্ধিদীপ্ত শব্দ স্থাপন
- প্লেসমেন্ট ব্যর্থ হলে কার্যকরভাবে পূর্বাবস্থায় ফেরা
- অপ্রয়োজনীয় অনুসন্ধান এড়ানোর জন্য ওয়ার্ক কিউ ব্যবস্থাপনা

স্বাভাবিকভাবেই প্রশ্ন ওঠে, আমরা কি আরও দ্রুত যেতে পারি? ও হ্যাঁ, অবশ্যই পারি।
৭. পৃষ্ঠের পরিসংখ্যান
পরিসংখ্যান কেন যোগ করা হয়?
কোনো কিছুকে দ্রুত করার ক্ষেত্রে, কী ঘটছে তা দেখতে পাওয়া সহায়ক হয়। পরিসংখ্যান আপনাকে অগ্রগতি নিরীক্ষণ করতে সাহায্য করে, যার মাধ্যমে অ্যালগরিদমটি রিয়েল-টাইমে কেমন কাজ করছে তা দেখা যায়। অ্যালগরিদমটি কোথায় তার সময় ব্যয় করছে তা বোঝার মাধ্যমে এটি আপনাকে প্রতিবন্ধকতাগুলো শনাক্ত করতে সক্ষম করে। এর ফলে, অপ্টিমাইজেশন পদ্ধতি সম্পর্কে তথ্যভিত্তিক সিদ্ধান্ত নিয়ে আপনি পারফরম্যান্স উন্নত করতে পারেন।
যে তথ্য আপনি প্রদর্শন করবেন, তা WorkQueue থেকে বের করে UI-তে দেখাতে হবে। একটি কার্যকরী প্রথম পদক্ষেপ হলো একটি নতুন মডেল ক্লাস সংজ্ঞায়িত করা, যেটিতে আপনি প্রদর্শন করতে চান এমন তথ্য থাকবে।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
-
DisplayInfoক্লাসটি যোগ করতেmodel.dartফাইলটি নিম্নরূপভাবে সম্পাদনা করুন:
lib/model.dart
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:characters/characters.dart';
import 'package:intl/intl.dart'; // Add this import
part 'model.g.dart';
/// A location in a crossword.
abstract class Location implements Built<Location, LocationBuilder> {
- ফাইলের শেষে
DisplayInfoক্লাসটি যোগ করতে নিম্নলিখিত পরিবর্তনগুলো করুন:
lib/model.dart
/// Factory constructor for [WorkQueue]
factory WorkQueue([void Function(WorkQueueBuilder)? updates]) = _$WorkQueue;
WorkQueue._();
}
// Add from here.
/// Display information for the current state of the crossword solve.
abstract class DisplayInfo implements Built<DisplayInfo, DisplayInfoBuilder> {
static Serializer<DisplayInfo> get serializer => _$displayInfoSerializer;
/// The number of words in the grid.
String get wordsInGridCount;
/// The number of candidate words.
String get candidateWordsCount;
/// The number of locations to explore.
String get locationsToExploreCount;
/// The number of known bad locations.
String get knownBadLocationsCount;
/// The percentage of the grid filled.
String get gridFilledPercentage;
/// Construct a [DisplayInfo] instance from a [WorkQueue].
factory DisplayInfo.from({required WorkQueue workQueue}) {
final gridFilled =
(workQueue.crossword.characters.length /
(workQueue.crossword.width * workQueue.crossword.height));
final fmt = NumberFormat.decimalPattern();
return DisplayInfo(
(b) => b
..wordsInGridCount = fmt.format(workQueue.crossword.words.length)
..candidateWordsCount = fmt.format(workQueue.candidateWords.length)
..locationsToExploreCount = fmt.format(workQueue.locationsToTry.length)
..knownBadLocationsCount = fmt.format(workQueue.badLocations.length)
..gridFilledPercentage = '${(gridFilled * 100).toStringAsFixed(2)}%',
);
}
/// An empty [DisplayInfo] instance.
static DisplayInfo get empty => DisplayInfo(
(b) => b
..wordsInGridCount = '0'
..candidateWordsCount = '0'
..locationsToExploreCount = '0'
..knownBadLocationsCount = '0'
..gridFilledPercentage = '0%',
);
factory DisplayInfo([void Function(DisplayInfoBuilder)? updates]) =
_$DisplayInfo;
DisplayInfo._();
} // To here.
/// Construct the serialization/deserialization code for the data model.
@SerializersFor([
Location,
Crossword,
CrosswordWord,
CrosswordCharacter,
WorkQueue,
DisplayInfo, // Add this line.
])
final Serializers serializers = _$serializers;
-
WorkQueueমডেলটি প্রকাশ করার জন্যisolates.dartফাইলটি নিম্নরূপভাবে পরিবর্তন করুন:
lib/isolates.dart
import 'package:built_collection/built_collection.dart';
import 'package:characters/characters.dart';
import 'package:flutter/foundation.dart';
import 'model.dart';
import 'utils.dart';
Stream<WorkQueue> exploreCrosswordSolutions({ // Modify this line
required Crossword crossword,
required BuiltSet<String> wordList,
}) async* {
final start = DateTime.now();
var workQueue = WorkQueue.from(
crossword: crossword,
candidateWords: wordList,
startLocation: Location.at(0, 0),
);
while (!workQueue.isCompleted) {
final location = workQueue.locationsToTry.keys.toBuiltSet().randomElement();
try {
final crossword = await compute(((WorkQueue, Location) workMessage) {
final (workQueue, location) = workMessage;
final direction = workQueue.locationsToTry[location]!;
final target = workQueue.crossword.characters[location];
if (target == null) {
return workQueue.crossword.addWord(
direction: direction,
location: location,
word: workQueue.candidateWords.randomElement(),
);
}
var words = workQueue.candidateWords.toBuiltList().rebuild(
(b) => b
..where((b) => b.characters.contains(target.character))
..shuffle(),
);
int tryCount = 0;
for (final word in words) {
tryCount++;
for (final (index, character) in word.characters.indexed) {
if (character != target.character) continue;
final candidate = workQueue.crossword.addWord(
location: switch (direction) {
Direction.across => location.leftOffset(index),
Direction.down => location.upOffset(index),
},
word: word,
direction: direction,
);
if (candidate != null) {
return candidate;
}
}
if (tryCount > 1000) {
break;
}
}
}, (workQueue, location));
if (crossword != null) {
workQueue = workQueue.updateFrom(crossword); // Drop the yield crossword;
} else {
workQueue = workQueue.remove(location);
}
yield workQueue; // Add this line.
} catch (e) {
debugPrint('Error running isolate: $e');
}
}
debugPrint(
'${crossword.width} x ${crossword.height} Crossword generated in '
'${DateTime.now().difference(start).formatted}',
);
}
এখন যেহেতু ব্যাকগ্রাউন্ড আইসোলেটটি ওয়ার্ক কিউকে উন্মুক্ত করে দিচ্ছে, প্রশ্ন হলো এই ডেটা উৎস থেকে কীভাবে এবং কোথা থেকে পরিসংখ্যান সংগ্রহ করা হবে।
- পুরানো ক্রসওয়ার্ড প্রোভাইডারটিকে একটি ওয়ার্ক কিউ প্রোভাইডার দিয়ে প্রতিস্থাপন করুন এবং তারপরে আরও প্রোভাইডার যুক্ত করুন যেগুলো ওয়ার্ক কিউ প্রোভাইডারের স্ট্রিম থেকে তথ্য আহরণ করে:
lib/providers.dart
import 'dart:convert';
import 'dart:math'; // Add this import
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'isolates.dart';
import 'model.dart' as model;
part 'providers.g.dart';
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
// This codebase requires that all words consist of lowercase characters
// in the range 'a'-'z'. Words containing uppercase letters will be
// lowercased, and words containing runes outside this range will
// be removed.
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter()
.convert(words)
.toBuiltSet()
.rebuild(
(b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)),
);
}
/// An enumeration for different sizes of [model.Crossword]s.
enum CrosswordSize {
small(width: 20, height: 11),
medium(width: 40, height: 22),
large(width: 80, height: 44),
xlarge(width: 160, height: 88),
xxlarge(width: 500, height: 500);
const CrosswordSize({required this.width, required this.height});
final int width;
final int height;
String get label => '$width x $height';
}
/// A provider that holds the current size of the crossword to generate.
@Riverpod(keepAlive: true)
class Size extends _$Size {
var _size = CrosswordSize.medium;
@override
CrosswordSize build() => _size;
void setSize(CrosswordSize size) {
_size = size;
ref.invalidateSelf();
}
}
@riverpod
Stream<model.WorkQueue> workQueue(Ref ref) async* { // Modify this provider
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
final emptyCrossword = model.Crossword.crossword(
width: size.width,
height: size.height,
);
final emptyWorkQueue = model.WorkQueue.from(
crossword: emptyCrossword,
candidateWords: BuiltSet<String>(),
startLocation: model.Location.at(0, 0),
);
ref.read(startTimeProvider.notifier).start();
ref.read(endTimeProvider.notifier).clear();
yield* wordListAsync.when(
data: (wordList) => exploreCrosswordSolutions(
crossword: emptyCrossword,
wordList: wordList,
),
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield emptyWorkQueue;
},
loading: () async* {
yield emptyWorkQueue;
},
);
ref.read(endTimeProvider.notifier).end();
} // To here.
@Riverpod(keepAlive: true) // Add from here to end of file
class StartTime extends _$StartTime {
@override
DateTime? build() => _start;
DateTime? _start;
void start() {
_start = DateTime.now();
ref.invalidateSelf();
}
}
@Riverpod(keepAlive: true)
class EndTime extends _$EndTime {
@override
DateTime? build() => _end;
DateTime? _end;
void clear() {
_end = null;
ref.invalidateSelf();
}
void end() {
_end = DateTime.now();
ref.invalidateSelf();
}
}
const _estimatedTotalCoverage = 0.54;
@riverpod
Duration expectedRemainingTime(Ref ref) {
final startTime = ref.watch(startTimeProvider);
final endTime = ref.watch(endTimeProvider);
final workQueueAsync = ref.watch(workQueueProvider);
return workQueueAsync.when(
data: (workQueue) {
if (startTime == null || endTime != null || workQueue.isCompleted) {
return Duration.zero;
}
try {
final soFar = DateTime.now().difference(startTime);
final completedPercentage = min(
0.99,
(workQueue.crossword.characters.length /
(workQueue.crossword.width * workQueue.crossword.height) /
_estimatedTotalCoverage),
);
final expectedTotal = soFar.inSeconds / completedPercentage;
final expectedRemaining = expectedTotal - soFar.inSeconds;
return Duration(seconds: expectedRemaining.toInt());
} catch (e) {
return Duration.zero;
}
},
error: (error, stackTrace) => Duration.zero,
loading: () => Duration.zero,
);
}
/// A provider that holds whether to display info.
@Riverpod(keepAlive: true)
class ShowDisplayInfo extends _$ShowDisplayInfo {
var _display = true;
@override
bool build() => _display;
void toggle() {
_display = !_display;
ref.invalidateSelf();
}
}
/// A provider that summarise the DisplayInfo from a [model.WorkQueue].
@riverpod
class DisplayInfo extends _$DisplayInfo {
@override
model.DisplayInfo build() => ref
.watch(workQueueProvider)
.when(
data: (workQueue) => model.DisplayInfo.from(workQueue: workQueue),
error: (error, stackTrace) => model.DisplayInfo.empty,
loading: () => model.DisplayInfo.empty,
);
}
নতুন প্রোভাইডারগুলো হলো গ্লোবাল স্টেট (যেমন, ইনফরমেশন ডিসপ্লেটি ক্রসওয়ার্ড গ্রিডের উপরে ওভারলে করা হবে কি না) এবং ডিরাইভড ডেটা (যেমন, ক্রসওয়ার্ড তৈরির চলমান সময়)-এর একটি মিশ্রণ। এই পুরো বিষয়টি আরও জটিল হয়ে ওঠে কারণ এই স্টেটের কয়েকটির লিসেনার ক্ষণস্থায়ী। ইনফো ডিসপ্লেটি লুকানো থাকলে ক্রসওয়ার্ড গণনার শুরু এবং শেষের সময় কেউ শোনে না, কিন্তু ইনফো ডিসপ্লেটি দেখানো হলে গণনাটি নির্ভুল হতে হলে সেগুলোকে মেমরিতে থাকতে হয়। এক্ষেত্রে Riverpod অ্যাট্রিবিউটের keepAlive প্যারামিটারটি খুবই কার্যকর।
তথ্য প্রদর্শনে একটি সামান্য সমস্যা আছে। আমরা অতিবাহিত রান টাইম দেখাতে চাই, কিন্তু অতিবাহিত সময়কে ক্রমাগত আপডেট করার জন্য এখানে কোনো ব্যবস্থা নেই। 'Building next generation UIs in Flutter' কোডল্যাবে ফিরে গেলে, ঠিক এই প্রয়োজনটির জন্য একটি কার্যকরী উইজেট পাওয়া যায়।
-
lib/widgetsডিরেক্টরিতেticker_builder.dartএকটি ফাইল তৈরি করুন এবং তারপর এতে নিম্নলিখিত বিষয়বস্তু যোগ করুন:
lib/widgets/ticker_builder.dart
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
/// A Builder widget that invokes its [builder] function on every animation frame.
class TickerBuilder extends StatefulWidget {
const TickerBuilder({super.key, required this.builder});
final Widget Function(BuildContext context) builder;
@override
State<TickerBuilder> createState() => _TickerBuilderState();
}
class _TickerBuilderState extends State<TickerBuilder>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
@override
void initState() {
super.initState();
_ticker = createTicker(_handleTick)..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
void _handleTick(Duration elapsed) {
setState(() {
// Force a rebuild without changing the widget tree.
});
}
@override
Widget build(BuildContext context) => widget.builder.call(context);
}
এই উইজেটটি একটি হাতুড়ির মতো। এটি প্রতিটি ফ্রেমে এর বিষয়বস্তু পুনর্নির্মাণ করে। সাধারণত এটিকে ভালো চোখে দেখা হয় না, কিন্তু ক্রসওয়ার্ড পাজল খোঁজার গণনাগত চাপের তুলনায়, প্রতি ফ্রেমে অতিবাহিত সময়কে পুনরায় চিত্রিত করার গণনাগত চাপ সম্ভবত নগণ্য হয়ে যাবে। এই নতুন প্রাপ্ত তথ্যের সুবিধা নিতে, এখন একটি নতুন উইজেট তৈরি করার সময় এসেছে।
- আপনার
lib/widgetsডিরেক্টরিতেcrossword_info_widget.dartনামে একটি ফাইল তৈরি করুন এবং তারপর এতে নিম্নলিখিত বিষয়বস্তু যোগ করুন:
lib/widgets/crossword_info_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
import '../utils.dart';
import 'ticker_builder.dart';
class CrosswordInfoWidget extends ConsumerWidget {
const CrosswordInfoWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
final displayInfo = ref.watch(displayInfoProvider);
final startTime = ref.watch(startTimeProvider);
final endTime = ref.watch(endTimeProvider);
final remaining = ref.watch(expectedRemainingTimeProvider);
return Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(right: 32.0, bottom: 32.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: ColoredBox(
color: Theme.of(context).colorScheme.onPrimary.withAlpha(230),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: DefaultTextStyle(
style: TextStyle(
fontSize: 16,
color: Theme.of(context).colorScheme.primary,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_CrosswordInfoRichText(
label: 'Grid Size',
value: '${size.width} x ${size.height}',
),
_CrosswordInfoRichText(
label: 'Words in grid',
value: displayInfo.wordsInGridCount,
),
_CrosswordInfoRichText(
label: 'Candidate words',
value: displayInfo.candidateWordsCount,
),
_CrosswordInfoRichText(
label: 'Locations to explore',
value: displayInfo.locationsToExploreCount,
),
_CrosswordInfoRichText(
label: 'Known bad locations',
value: displayInfo.knownBadLocationsCount,
),
_CrosswordInfoRichText(
label: 'Grid filled',
value: displayInfo.gridFilledPercentage,
),
switch ((startTime, endTime)) {
(null, _) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: 'Not started yet',
),
(DateTime start, null) => TickerBuilder(
builder: (context) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: DateTime.now().difference(start).formatted,
),
),
(DateTime start, DateTime end) => _CrosswordInfoRichText(
label: 'Completed in',
value: end.difference(start).formatted,
),
},
if (startTime != null && endTime == null)
_CrosswordInfoRichText(
label: 'Est. remaining',
value: remaining.formatted,
),
],
),
),
),
),
),
),
);
}
}
class _CrosswordInfoRichText extends StatelessWidget {
final String label;
final String value;
const _CrosswordInfoRichText({required this.label, required this.value});
@override
Widget build(BuildContext context) => RichText(
text: TextSpan(
children: [
TextSpan(text: '$label ', style: DefaultTextStyle.of(context).style),
TextSpan(
text: value,
style: DefaultTextStyle.of(
context,
).style.copyWith(fontWeight: FontWeight.bold),
),
],
),
);
}
এই উইজেটটি রিভারপডের প্রোভাইডারদের ক্ষমতার একটি প্রধান উদাহরণ। পাঁচটি প্রোভাইডারের যেকোনো একটি আপডেট হলে এই উইজেটটি পুনর্নির্মাণের জন্য চিহ্নিত করা হবে। এই ধাপের শেষ প্রয়োজনীয় পরিবর্তনটি হলো এই নতুন উইজেটটিকে UI-এর সাথে একীভূত করা।
- আপনার
crossword_generator_app.dartফাইলটি নিম্নরূপভাবে সম্পাদনা করুন:
lib/widgets/crossword_generator_app.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
import 'crossword_info_widget.dart'; // Add this import
import 'crossword_widget.dart';
class CrosswordGeneratorApp extends StatelessWidget {
const CrosswordGeneratorApp({super.key});
@override
Widget build(BuildContext context) {
return _EagerInitialization(
child: Scaffold(
appBar: AppBar(
actions: [_CrosswordGeneratorMenu()],
titleTextStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 16,
fontWeight: FontWeight.bold,
),
title: Text('Crossword Generator'),
),
body: SafeArea(
child: Consumer( // Modify from here
builder: (context, ref, child) {
return Stack(
children: [
Positioned.fill(child: CrosswordWidget()),
if (ref.watch(showDisplayInfoProvider)) CrosswordInfoWidget(),
],
);
},
), // To here.
),
),
);
}
}
class _EagerInitialization extends ConsumerWidget {
const _EagerInitialization({required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(wordListProvider);
return child;
}
}
class _CrosswordGeneratorMenu extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) => MenuAnchor(
menuChildren: [
for (final entry in CrosswordSize.values)
MenuItemButton(
onPressed: () => ref.read(sizeProvider.notifier).setSize(entry),
leadingIcon: entry == ref.watch(sizeProvider)
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
child: Text(entry.label),
),
MenuItemButton( // Add from here
leadingIcon: ref.watch(showDisplayInfoProvider)
? Icon(Icons.check_box_outlined)
: Icon(Icons.check_box_outline_blank_outlined),
onPressed: () => ref.read(showDisplayInfoProvider.notifier).toggle(),
child: Text('Display Info'),
), // To here.
],
builder: (context, controller, child) => IconButton(
onPressed: () => controller.open(),
icon: Icon(Icons.settings),
),
);
}
এখানের দুটি পরিবর্তন প্রোভাইডারদের একীভূত করার ভিন্ন ভিন্ন পদ্ধতি প্রদর্শন করে। CrosswordGeneratorApp এর build মেথডে, আপনি একটি নতুন Consumer বিল্ডার যুক্ত করেছেন, যা তথ্য প্রদর্শন দেখানো বা লুকানোর সময় বাধ্যতামূলকভাবে পুনর্নির্মিত হওয়া অংশটিকে ধারণ করে। অন্যদিকে, পুরো ড্রপ-ডাউন মেনুটি একটিই ConsumerWidget , যা ক্রসওয়ার্ডের আকার পরিবর্তন হোক বা তথ্য প্রদর্শন দেখানো বা লুকানো হোক, পুনর্নির্মিত হবে। কোন পদ্ধতিটি গ্রহণ করা হবে, তা সর্বদা সরলতা বনাম পুনর্নির্মিত উইজেট ট্রি-এর লেআউট পুনরায় গণনা করার খরচের একটি ইঞ্জিনিয়ারিং আপস।
এখন অ্যাপটি চালালে ক্রসওয়ার্ড তৈরির প্রক্রিয়াটি কীভাবে এগোচ্ছে সে সম্পর্কে ব্যবহারকারী আরও স্পষ্ট ধারণা পান। তবে, ক্রসওয়ার্ড তৈরির প্রায় শেষের দিকে আমরা দেখতে পাই যে এমন একটি পর্যায় রয়েছে যেখানে সংখ্যাগুলো পরিবর্তিত হচ্ছে, কিন্তু অক্ষরের বিন্যাসে খুব সামান্যই পরিবর্তন হচ্ছে।

কী ঘটছে এবং কেন ঘটছে, সে সম্পর্কে আরও ধারণা পেলে সহায়ক হবে।
৮. থ্রেড দিয়ে সমান্তরাল করুন
কেন কর্মক্ষমতা হ্রাস পায়
ক্রসওয়ার্ডটি শেষের দিকে এলে অ্যালগরিদমটির গতি কমে যায়, কারণ শব্দ বসানোর বৈধ বিকল্প কমে আসতে থাকে। অ্যালগরিদমটি এমন অনেক সংমিশ্রণ চেষ্টা করে যা কাজ করবে না। সিঙ্গেল-থ্রেডেড প্রসেসিং দক্ষতার সাথে একাধিক বিকল্প খতিয়ে দেখতে পারে না।
অ্যালগরিদমটি কল্পনা করা
শেষের দিকে কেন কাজ ধীর হয়ে যায় তা বোঝার জন্য, অ্যালগরিদমটি কী করছে তা দেখতে পারাটা সহায়ক। এর একটি মূল অংশ হলো WorkQueue তে থাকা অসমাপ্ত locationsToTry । TableView আমাদের এটি খতিয়ে দেখার একটি কার্যকর উপায় দেয়। সেলটি locationsToTry মধ্যে আছে কি না, তার উপর ভিত্তি করে আমরা এর রঙ পরিবর্তন করতে পারি।
শুরু করতে, এই ধাপগুলো অনুসরণ করুন:
-
crossword_widget.dartফাইলটি নিম্নরূপভাবে পরিবর্তন করুন:
lib/widgets/crossword_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart';
import '../model.dart';
import '../providers.dart';
class CrosswordWidget extends ConsumerWidget {
const CrosswordWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
return TableView.builder(
diagonalDragBehavior: DiagonalDragBehavior.free,
cellBuilder: _buildCell,
columnCount: size.width,
columnBuilder: (index) => _buildSpan(context, index),
rowCount: size.height,
rowBuilder: (index) => _buildSpan(context, index),
);
}
TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
final location = Location.at(vicinity.column, vicinity.row);
return TableViewCell(
child: Consumer(
builder: (context, ref, _) {
final character = ref.watch(
workQueueProvider.select(
(workQueueAsync) => workQueueAsync.when(
data: (workQueue) => workQueue.crossword.characters[location],
error: (error, stackTrace) => null,
loading: () => null,
),
),
);
final explorationCell = ref.watch( // Add from here
workQueueProvider.select(
(workQueueAsync) => workQueueAsync.when(
data: (workQueue) =>
workQueue.locationsToTry.keys.contains(location),
error: (error, stackTrace) => false,
loading: () => false,
),
),
); // To here.
if (character != null) { // Modify from here
return AnimatedContainer(
duration: Durations.extralong1,
curve: Curves.easeInOut,
color: explorationCell
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onPrimary,
child: Center(
child: AnimatedDefaultTextStyle(
duration: Durations.extralong1,
curve: Curves.easeInOut,
style: TextStyle(
fontSize: 24,
color: explorationCell
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.primary,
),
child: Text(character.character),
), // To here.
),
);
}
return ColoredBox(
color: Theme.of(context).colorScheme.primaryContainer,
);
},
),
);
}
TableSpan _buildSpan(BuildContext context, int index) {
return TableSpan(
extent: FixedTableSpanExtent(32),
foregroundDecoration: TableSpanDecoration(
border: TableSpanBorder(
leading: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
trailing: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
);
}
}
যখন আপনি এই কোডটি চালাবেন, তখন আপনি সেইসব অমীমাংসিত স্থানগুলির একটি ভিজ্যুয়ালাইজেশন দেখতে পাবেন যেগুলি অ্যালগরিদমটি এখনও অনুসন্ধান করেনি।

ক্রসওয়ার্ডটি শেষের দিকে এগোতে থাকার সময় মজার ব্যাপার হলো, এমন অনেক বিষয় বাকি থাকে যা খতিয়ে দেখার প্রয়োজন হয়, কিন্তু তা থেকে কোনো কাজের তথ্য পাওয়া যাবে না। এক্ষেত্রে কয়েকটি উপায় আছে; একটি হলো, ক্রসওয়ার্ডের একটি নির্দিষ্ট শতাংশ ঘর পূরণ হয়ে গেলে খতিয়ে দেখা বন্ধ করে দেওয়া এবং দ্বিতীয়টি হলো, একই সাথে একাধিক গুরুত্বপূর্ণ বিষয় খতিয়ে দেখা। দ্বিতীয় উপায়টি বেশি মজার মনে হচ্ছে, তাই এখন সেটাই করার সময়।
-
isolates.dartফাইলটি সম্পাদনা করুন। এটি কোডটির প্রায় সম্পূর্ণ পুনর্লিখন, যার উদ্দেশ্য হলো একটি ব্যাকগ্রাউন্ড আইসোলেটে গণনাকৃত বিষয়গুলোকে N সংখ্যক ব্যাকগ্রাউন্ড আইসোলেটের একটি পুলে বিভক্ত করা।
lib/isolates.dart
import 'package:built_collection/built_collection.dart';
import 'package:characters/characters.dart';
import 'package:flutter/foundation.dart';
import 'model.dart';
import 'utils.dart';
Stream<WorkQueue> exploreCrosswordSolutions({
required Crossword crossword,
required BuiltSet<String> wordList,
required int maxWorkerCount,
}) async* {
final start = DateTime.now();
var workQueue = WorkQueue.from(
crossword: crossword,
candidateWords: wordList,
startLocation: Location.at(0, 0),
);
while (!workQueue.isCompleted) {
try {
workQueue = await compute(_generate, (workQueue, maxWorkerCount));
yield workQueue;
} catch (e) {
debugPrint('Error running isolate: $e');
}
}
debugPrint(
'Generated ${workQueue.crossword.width} x '
'${workQueue.crossword.height} crossword in '
'${DateTime.now().difference(start).formatted} '
'with $maxWorkerCount workers.',
);
}
Future<WorkQueue> _generate((WorkQueue, int) workMessage) async {
var (workQueue, maxWorkerCount) = workMessage;
final candidateGeneratorFutures = <Future<(Location, Direction, String?)>>[];
final locations = workQueue.locationsToTry.keys.toBuiltList().rebuild(
(b) => b
..shuffle()
..take(maxWorkerCount),
);
for (final location in locations) {
final direction = workQueue.locationsToTry[location]!;
candidateGeneratorFutures.add(
compute(_generateCandidate, (
workQueue.crossword,
workQueue.candidateWords,
location,
direction,
)),
);
}
try {
final results = await candidateGeneratorFutures.wait;
var crossword = workQueue.crossword;
for (final (location, direction, word) in results) {
if (word != null) {
final candidate = crossword.addWord(
location: location,
word: word,
direction: direction,
);
if (candidate != null) {
crossword = candidate;
}
} else {
workQueue = workQueue.remove(location);
}
}
workQueue = workQueue.updateFrom(crossword);
} catch (e) {
debugPrint('$e');
}
return workQueue;
}
(Location, Direction, String?) _generateCandidate(
(Crossword, BuiltSet<String>, Location, Direction) searchDetailMessage,
) {
final (crossword, candidateWords, location, direction) = searchDetailMessage;
final target = crossword.characters[location];
if (target == null) {
return (location, direction, candidateWords.randomElement());
}
// Filter down the candidate word list to those that contain the letter
// at the current location
final words = candidateWords.toBuiltList().rebuild(
(b) => b
..where((b) => b.characters.contains(target.character))
..shuffle(),
);
int tryCount = 0;
final start = DateTime.now();
for (final word in words) {
tryCount++;
for (final (index, character) in word.characters.indexed) {
if (character != target.character) continue;
final candidate = crossword.addWord(
location: switch (direction) {
Direction.across => location.leftOffset(index),
Direction.down => location.upOffset(index),
},
word: word,
direction: direction,
);
if (candidate != null) {
return switch (direction) {
Direction.across => (location.leftOffset(index), direction, word),
Direction.down => (location.upOffset(index), direction, word),
};
}
final deltaTime = DateTime.now().difference(start);
if (tryCount >= 1000 || deltaTime > Duration(seconds: 10)) {
return (location, direction, null);
}
}
}
return (location, direction, null);
}
মাল্টি-আইসোলেট আর্কিটেকচার বোঝা
এই কোডের বেশিরভাগই আপনার কাছে পরিচিত মনে হওয়ার কথা, কারণ মূল বিজনেস লজিক অপরিবর্তিত রয়েছে। যা পরিবর্তিত হয়েছে তা হলো, এখন compute কলের দুটি স্তর রয়েছে। প্রথম স্তরটি অনুসন্ধানের জন্য স্বতন্ত্র অবস্থানগুলোকে N সংখ্যক ওয়ার্কার আইসোলেটের মধ্যে ভাগ করে দেওয়ার এবং সব N সংখ্যক ওয়ার্কার আইসোলেটের কাজ শেষ হলে ফলাফলগুলোকে পুনরায় একত্রিত করার দায়িত্বে থাকে। দ্বিতীয় স্তরটি সেই N সংখ্যক ওয়ার্কার আইসোলেট নিয়ে গঠিত। সেরা পারফরম্যান্স পাওয়ার জন্য N-এর মান নির্ধারণ করা আপনার কম্পিউটার এবং ব্যবহৃত ডেটা উভয়ের উপরই নির্ভরশীল। গ্রিড যত বড় হবে, তত বেশি ওয়ার্কার একে অপরের কাজে বাধা না দিয়ে একসাথে কাজ করতে পারবে।
একটি আকর্ষণীয় বিষয় হলো, এই কোডটি এখন ক্লোজারগুলোর এমন কিছু ক্যাপচার করার সমস্যাটি কীভাবে সমাধান করে যা তাদের করা উচিত নয়। এখন এখানে কোনো ক্লোজার নেই। _generate এবং _generateWorker ফাংশনগুলোকে টপ-লেভেল ফাংশন হিসেবে সংজ্ঞায়িত করা হয়েছে, যেগুলোর ক্যাপচার করার জন্য কোনো পারিপার্শ্বিক পরিবেশ নেই। এই দুটি ফাংশনের আর্গুমেন্ট এবং আউটপুট উভয়ই ডার্ট রেকর্ডের আকারে থাকে। এটি compute কলের 'একটি ভ্যালু ইন, একটি ভ্যালু আউট' নীতিকে এড়িয়ে চলার একটি উপায়।
এখন যেহেতু আপনার কাছে একটি গ্রিডে পরস্পর সংযুক্ত হয়ে ক্রসওয়ার্ড পাজল তৈরি করার জন্য ব্যাকগ্রাউন্ড কর্মীদের একটি পুল তৈরি করার ক্ষমতা আছে, তাই এই সক্ষমতাটি ক্রসওয়ার্ড জেনারেটর টুলের বাকি অংশের কাছে উন্মুক্ত করার সময় এসেছে।
- নিম্নলিখিতভাবে workQueue প্রোভাইডারটি সম্পাদনা করে
providers.dartফাইলটি এডিট করুন:
lib/providers.dart
@riverpod
Stream<model.WorkQueue> workQueue(Ref ref) async* {
final workers = ref.watch(workerCountProvider); // Add this line
final size = ref.watch(sizeProvider);
final wordListAsync = ref.watch(wordListProvider);
final emptyCrossword = model.Crossword.crossword(
width: size.width,
height: size.height,
);
final emptyWorkQueue = model.WorkQueue.from(
crossword: emptyCrossword,
candidateWords: BuiltSet<String>(),
startLocation: model.Location.at(0, 0),
);
ref.read(startTimeProvider.notifier).start();
ref.read(endTimeProvider.notifier).clear();
yield* wordListAsync.when(
data: (wordList) => exploreCrosswordSolutions(
crossword: emptyCrossword,
wordList: wordList,
maxWorkerCount: workers.count, // Add this line
),
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield emptyWorkQueue;
},
loading: () async* {
yield emptyWorkQueue;
},
);
ref.read(endTimeProvider.notifier).end();
}
- ফাইলের শেষে
WorkerCountপ্রোভাইডারটি নিম্নোক্তভাবে যুক্ত করুন:
lib/providers.dart
/// A provider that summarise the DisplayInfo from a [model.WorkQueue].
@riverpod
class DisplayInfo extends _$DisplayInfo {
@override
model.DisplayInfo build() => ref
.watch(workQueueProvider)
.when(
data: (workQueue) => model.DisplayInfo.from(workQueue: workQueue),
error: (error, stackTrace) => model.DisplayInfo.empty,
loading: () => model.DisplayInfo.empty,
);
}
enum BackgroundWorkers { // Add from here
one(1),
two(2),
four(4),
eight(8),
sixteen(16),
thirtyTwo(32),
sixtyFour(64),
oneTwentyEight(128);
const BackgroundWorkers(this.count);
final int count;
String get label => count.toString();
}
/// A provider that holds the current number of background workers to use.
@Riverpod(keepAlive: true)
class WorkerCount extends _$WorkerCount {
var _count = BackgroundWorkers.four;
@override
BackgroundWorkers build() => _count;
void setCount(BackgroundWorkers count) {
_count = count;
ref.invalidateSelf();
}
} // To here.
With these two changes, the provider layer now exposes a way to set the maximum worker count for the background isolate pool in a way that the isolate functions are correctly configured.
- Update the
crossword_info_widget.dartfile by modifying theCrosswordInfoWidgetas follows:
lib/widgets/crossword_info_widget.dart
class CrosswordInfoWidget extends ConsumerWidget {
const CrosswordInfoWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
final displayInfo = ref.watch(displayInfoProvider);
final workerCount = ref.watch(workerCountProvider).label; // Add this line
final startTime = ref.watch(startTimeProvider);
final endTime = ref.watch(endTimeProvider);
final remaining = ref.watch(expectedRemainingTimeProvider);
return Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(right: 32.0, bottom: 32.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: ColoredBox(
color: Theme.of(context).colorScheme.onPrimary.withAlpha(230),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: DefaultTextStyle(
style: TextStyle(
fontSize: 16,
color: Theme.of(context).colorScheme.primary,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_CrosswordInfoRichText(
label: 'Grid Size',
value: '${size.width} x ${size.height}',
),
_CrosswordInfoRichText(
label: 'Words in grid',
value: displayInfo.wordsInGridCount,
),
_CrosswordInfoRichText(
label: 'Candidate words',
value: displayInfo.candidateWordsCount,
),
_CrosswordInfoRichText(
label: 'Locations to explore',
value: displayInfo.locationsToExploreCount,
),
_CrosswordInfoRichText(
label: 'Known bad locations',
value: displayInfo.knownBadLocationsCount,
),
_CrosswordInfoRichText(
label: 'Grid filled',
value: displayInfo.gridFilledPercentage,
),
_CrosswordInfoRichText( // Add from here
label: 'Max worker count',
value: workerCount,
), // To here.
switch ((startTime, endTime)) {
(null, _) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: 'Not started yet',
),
(DateTime start, null) => TickerBuilder(
builder: (context) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: DateTime.now().difference(start).formatted,
),
),
(DateTime start, DateTime end) => _CrosswordInfoRichText(
label: 'Completed in',
value: end.difference(start).formatted,
),
},
if (startTime != null && endTime == null)
_CrosswordInfoRichText(
label: 'Est. remaining',
value: remaining.formatted,
),
],
),
),
),
),
),
),
);
}
}
- Modify the
crossword_generator_app.dartfile by adding the following section to the_CrosswordGeneratorMenuwidget:
lib/widgets/crossword_generator_app.dart
class _CrosswordGeneratorMenu extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) => MenuAnchor(
menuChildren: [
for (final entry in CrosswordSize.values)
MenuItemButton(
onPressed: () => ref.read(sizeProvider.notifier).setSize(entry),
leadingIcon: entry == ref.watch(sizeProvider)
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
child: Text(entry.label),
),
MenuItemButton(
leadingIcon: ref.watch(showDisplayInfoProvider)
? Icon(Icons.check_box_outlined)
: Icon(Icons.check_box_outline_blank_outlined),
onPressed: () => ref.read(showDisplayInfoProvider.notifier).toggle(),
child: Text('Display Info'),
),
for (final count in BackgroundWorkers.values) // Add from here
MenuItemButton(
leadingIcon: count == ref.watch(workerCountProvider)
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
onPressed: () =>
ref.read(workerCountProvider.notifier).setCount(count),
child: Text(count.label), // To here.
),
],
builder: (context, controller, child) => IconButton(
onPressed: () => controller.open(),
icon: Icon(Icons.settings),
),
);
}
If you run the app now, you will be able to modify the number of background isolates being instantiated to search for words to slot into the crossword.
- Click the gear icon in the to open the contextual menu containing sizing for the crossword, whether to display the statistics on the generated crossword, and now, the number of isolates to use.

Checkpoint: Multi-threaded Performance
Running the crossword generator has significantly reduced the compute time for an 80x44 crossword by using multiple cores concurrently. You should notice:
- Faster crossword generation with higher worker counts
- Smooth UI responsiveness during generation
- Real-time statistics showing generation progress
- Visual feedback of algorithm exploration areas
9. Turn it into a game
What we're building: A Playable Crossword Game
This last section is really a bonus round. You will take all the techniques you have learned while constructing the crossword generator and use these techniques to build a game. You will:
- Generate puzzles : Use the crossword generator to create solvable puzzles
- Create word choices : Provide multiple word options for each position
- Enable interaction : Let users select and place words
- Validate solutions : Check if the completed crossword is correct
You will use the crossword generator to create a crossword puzzle. You will reuse the contextual menu idioms to enable the user to select and deselect words to put in the various word-shaped holes in the grid. All with the aim of completing the crossword.
I'm not going to say this game is polished or finished, it's far from in fact. There are balance and difficulty issues which can be solved with improving the choice of alternate words. There is no tutorial to lead users into the puzzle. I'm not even going to mention the bare bones "You've won!" screen.
The tradeoff here is that to properly polish this proto-game into a full game will take significantly more code. More code than should be in a single codelab. So, instead, this is a speed run step designed to reinforce the techniques learned so far in this codelab by changing where and how they are used. Hopefully this reinforces the lessons learned earlier in this codelab. Alternatively, you can go ahead and build your own experiences based on this code. We'd love to see what you build!
To begin, follow these steps:
- Delete everything in the
lib/widgetsdirectory. You will be creating shiny new widgets for your game. That just happens to borrow a lot from the old widgets.
- Edit your
model.dartfile to updateCrossword'saddWordmethod as follows:
lib/model.dart
/// Add a word to the crossword at the given location and direction.
Crossword? addWord({
required Location location,
required String word,
required Direction direction,
bool requireOverlap = true, // Add this parameter
}) {
// Require that the word is not already in the crossword.
if (words.map((crosswordWord) => crosswordWord.word).contains(word)) {
return null;
}
final wordCharacters = word.characters;
bool overlap = false;
// Check that the word fits in the crossword.
for (final (index, character) in wordCharacters.indexed) {
final characterLocation = switch (direction) {
Direction.across => location.rightOffset(index),
Direction.down => location.downOffset(index),
};
final target = characters[characterLocation];
if (target != null) {
overlap = true;
if (target.character != character) {
return null;
}
if (direction == Direction.across && target.acrossWord != null ||
direction == Direction.down && target.downWord != null) {
return null;
}
}
}
// Edit from here
// If overlap is required, make sure that the word overlaps with an existing
// word. Skip this test if the crossword is empty.
if (words.isNotEmpty && !overlap && requireOverlap) { // To here.
return null;
}
final candidate = rebuild(
(b) => b
..words.add(
CrosswordWord.word(
word: word,
direction: direction,
location: location,
),
),
);
if (candidate.valid) {
return candidate;
} else {
return null;
}
}
This minor modification of your Crossword model enables words to be added that don't overlap. It's useful to allow players to play anywhere on a board and still be able to use Crossword as a base model for storing the player's moves. It is just a list of words at specific locations placed in a specific direction.
- Add the
CrosswordPuzzleGamemodel class to the end of yourmodel.dartfile.
lib/model.dart
/// Creates a puzzle from a crossword and a set of candidate words.
abstract class CrosswordPuzzleGame
implements Built<CrosswordPuzzleGame, CrosswordPuzzleGameBuilder> {
static Serializer<CrosswordPuzzleGame> get serializer =>
_$crosswordPuzzleGameSerializer;
/// The [Crossword] that this puzzle is based on.
Crossword get crossword;
/// The alternate words for each [CrosswordWord] in the crossword.
BuiltMap<Location, BuiltMap<Direction, BuiltList<String>>> get alternateWords;
/// The player's selected words.
BuiltList<CrosswordWord> get selectedWords;
bool canSelectWord({
required Location location,
required String word,
required Direction direction,
}) {
final crosswordWord = CrosswordWord.word(
word: word,
location: location,
direction: direction,
);
if (selectedWords.contains(crosswordWord)) {
return true;
}
var puzzle = this;
if (puzzle.selectedWords
.where((b) => b.direction == direction && b.location == location)
.isNotEmpty) {
puzzle = puzzle.rebuild(
(b) => b
..selectedWords.removeWhere(
(selectedWord) =>
selectedWord.location == location &&
selectedWord.direction == direction,
),
);
}
return null !=
puzzle.crosswordFromSelectedWords.addWord(
location: location,
word: word,
direction: direction,
requireOverlap: false,
);
}
CrosswordPuzzleGame? selectWord({
required Location location,
required String word,
required Direction direction,
}) {
final crosswordWord = CrosswordWord.word(
word: word,
location: location,
direction: direction,
);
if (selectedWords.contains(crosswordWord)) {
return rebuild((b) => b.selectedWords.remove(crosswordWord));
}
var puzzle = this;
if (puzzle.selectedWords
.where((b) => b.direction == direction && b.location == location)
.isNotEmpty) {
puzzle = puzzle.rebuild(
(b) => b
..selectedWords.removeWhere(
(selectedWord) =>
selectedWord.location == location &&
selectedWord.direction == direction,
),
);
}
// Check if the selected word meshes with the already selected words.
// Note this version of the crossword does not enforce overlap to
// allow the player to select words anywhere on the grid. Enforcing words
// to be solved in order is a possible alternative.
final updatedSelectedWordsCrossword = puzzle.crosswordFromSelectedWords
.addWord(
location: location,
word: word,
direction: direction,
requireOverlap: false,
);
// Make sure the selected word is in the crossword or is an alternate word.
if (updatedSelectedWordsCrossword != null) {
if (puzzle.crossword.words.contains(crosswordWord) ||
puzzle.alternateWords[location]?[direction]?.contains(word) == true) {
return puzzle.rebuild(
(b) => b
..selectedWords.add(
CrosswordWord.word(
word: word,
location: location,
direction: direction,
),
),
);
}
}
return null;
}
/// The crossword from the selected words.
Crossword get crosswordFromSelectedWords => Crossword.crossword(
width: crossword.width,
height: crossword.height,
words: selectedWords,
);
/// Test if the puzzle is solved. Note, this allows for the possibility of
/// multiple solutions.
bool get solved =>
crosswordFromSelectedWords.valid &&
crosswordFromSelectedWords.words.length == crossword.words.length &&
crossword.words.isNotEmpty;
/// Create a crossword puzzle game from a crossword and a set of candidate
/// words.
factory CrosswordPuzzleGame.from({
required Crossword crossword,
required BuiltSet<String> candidateWords,
}) {
// Remove all of the currently used words from the list of candidates
candidateWords = candidateWords.rebuild(
(p0) => p0.removeAll(crossword.words.map((p1) => p1.word)),
);
// This is the list of alternate words for each word in the crossword
var alternates =
BuiltMap<Location, BuiltMap<Direction, BuiltList<String>>>();
// Build the alternate words for each word in the crossword
for (final crosswordWord in crossword.words) {
final alternateWords = candidateWords.toBuiltList().rebuild(
(b) => b
..where((b) => b.length == crosswordWord.word.length)
..shuffle()
..take(4)
..sort(),
);
candidateWords = candidateWords.rebuild(
(b) => b.removeAll(alternateWords),
);
alternates = alternates.rebuild(
(b) => b.updateValue(
crosswordWord.location,
(b) => b.rebuild(
(b) => b.updateValue(
crosswordWord.direction,
(b) => b.rebuild((b) => b.replace(alternateWords)),
ifAbsent: () => alternateWords,
),
),
ifAbsent: () => {crosswordWord.direction: alternateWords}.build(),
),
);
}
return CrosswordPuzzleGame((b) {
b
..crossword.replace(crossword)
..alternateWords.replace(alternates);
});
}
factory CrosswordPuzzleGame([
void Function(CrosswordPuzzleGameBuilder)? updates,
]) = _$CrosswordPuzzleGame;
CrosswordPuzzleGame._();
}
/// Construct the serialization/deserialization code for the data model.
@SerializersFor([
Location,
Crossword,
CrosswordWord,
CrosswordCharacter,
WorkQueue,
DisplayInfo,
CrosswordPuzzleGame, // Add this line
])
final Serializers serializers = _$serializers;
The updates to the providers.dart file are an interesting grab bag of changes. Most of the providers that were present to support statistics gathering have been removed. The ability to change the number of background isolates has been removed and replaced with a constant. There is also a new provider that gives access to the new CrosswordPuzzleGame model you added previously.
lib/providers.dart
import 'dart:convert';
// Drop the dart:math import
import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'isolates.dart';
import 'model.dart' as model;
part 'providers.g.dart';
const backgroundWorkerCount = 4; // Add this line
/// A provider for the wordlist to use when generating the crossword.
@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
// This codebase requires that all words consist of lowercase characters
// in the range 'a'-'z'. Words containing uppercase letters will be
// lowercased, and words containing runes outside this range will
// be removed.
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter()
.convert(words)
.toBuiltSet()
.rebuild(
(b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)),
);
}
/// An enumeration for different sizes of [model.Crossword]s.
enum CrosswordSize {
small(width: 20, height: 11),
medium(width: 40, height: 22),
large(width: 80, height: 44),
xlarge(width: 160, height: 88),
xxlarge(width: 500, height: 500);
const CrosswordSize({required this.width, required this.height});
final int width;
final int height;
String get label => '$width x $height';
}
/// A provider that holds the current size of the crossword to generate.
@Riverpod(keepAlive: true)
class Size extends _$Size {
var _size = CrosswordSize.medium;
@override
CrosswordSize build() => _size;
void setSize(CrosswordSize size) {
_size = size;
ref.invalidateSelf();
}
}
@riverpod
Stream<model.WorkQueue> workQueue(Ref ref) async* {
final size = ref.watch(sizeProvider); // Drop the ref.watch(workerCountProvider)
final wordListAsync = ref.watch(wordListProvider);
final emptyCrossword = model.Crossword.crossword(
width: size.width,
height: size.height,
);
final emptyWorkQueue = model.WorkQueue.from(
crossword: emptyCrossword,
candidateWords: BuiltSet<String>(),
startLocation: model.Location.at(0, 0),
);
// Drop the startTimeProvider and endTimeProvider refs
yield* wordListAsync.when(
data: (wordList) => exploreCrosswordSolutions(
crossword: emptyCrossword,
wordList: wordList,
maxWorkerCount: backgroundWorkerCount, // Edit this line
),
error: (error, stackTrace) async* {
debugPrint('Error loading word list: $error');
yield emptyWorkQueue;
},
loading: () async* {
yield emptyWorkQueue;
},
);
} // Drop the endTimeProvider ref
@riverpod // Add from here to end of file
class Puzzle extends _$Puzzle {
model.CrosswordPuzzleGame _puzzle = model.CrosswordPuzzleGame.from(
crossword: model.Crossword.crossword(width: 0, height: 0),
candidateWords: BuiltSet<String>(),
);
@override
model.CrosswordPuzzleGame build() {
final size = ref.watch(sizeProvider);
final wordList = ref.watch(wordListProvider).value;
final workQueue = ref.watch(workQueueProvider).value;
if (wordList != null &&
workQueue != null &&
workQueue.isCompleted &&
(_puzzle.crossword.height != size.height ||
_puzzle.crossword.width != size.width ||
_puzzle.crossword != workQueue.crossword)) {
compute(_puzzleFromCrosswordTrampoline, (
workQueue.crossword,
wordList,
)).then((puzzle) {
_puzzle = puzzle;
ref.invalidateSelf();
});
}
return _puzzle;
}
Future<void> selectWord({
required model.Location location,
required String word,
required model.Direction direction,
}) async {
final candidate = await compute(_puzzleSelectWordTrampoline, (
_puzzle,
location,
word,
direction,
));
if (candidate != null) {
_puzzle = candidate;
ref.invalidateSelf();
} else {
debugPrint('Invalid word selection: $word');
}
}
bool canSelectWord({
required model.Location location,
required String word,
required model.Direction direction,
}) {
return _puzzle.canSelectWord(
location: location,
word: word,
direction: direction,
);
}
}
// Trampoline functions to disentangle these Isolate target calls from the
// unsendable reference to the [Puzzle] provider.
Future<model.CrosswordPuzzleGame> _puzzleFromCrosswordTrampoline(
(model.Crossword, BuiltSet<String>) args,
) async =>
model.CrosswordPuzzleGame.from(crossword: args.$1, candidateWords: args.$2);
model.CrosswordPuzzleGame? _puzzleSelectWordTrampoline(
(model.CrosswordPuzzleGame, model.Location, String, model.Direction) args,
) => args.$1.selectWord(location: args.$2, word: args.$3, direction: args.$4);
The most interesting parts of the Puzzle provider are the stratagems undertaken to gloss over the expense of creating the CrosswordPuzzleGame from a Crossword and a wordList , and the expense of selecting a word. Both of these actions when undertaken without the aid of a background Isolate cause sluggish UI interaction. By using some sleight of hand to push out an intermediate result while computing the final result in the background, you wind up with a responsive UI while the required computations are taking place in the background.
- In the now-empty
lib/widgetsdirectory, create acrossword_puzzle_app.dartfile with the following content:
lib/widgets/crossword_puzzle_app.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
import 'crossword_generator_widget.dart';
import 'crossword_puzzle_widget.dart';
import 'puzzle_completed_widget.dart';
class CrosswordPuzzleApp extends StatelessWidget {
const CrosswordPuzzleApp({super.key});
@override
Widget build(BuildContext context) {
return _EagerInitialization(
child: Scaffold(
appBar: AppBar(
actions: [_CrosswordPuzzleAppMenu()],
titleTextStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 16,
fontWeight: FontWeight.bold,
),
title: Text('Crossword Puzzle'),
),
body: SafeArea(
child: Consumer(
builder: (context, ref, _) {
final workQueueAsync = ref.watch(workQueueProvider);
final puzzleSolved = ref.watch(
puzzleProvider.select((puzzle) => puzzle.solved),
);
return workQueueAsync.when(
data: (workQueue) {
if (puzzleSolved) {
return PuzzleCompletedWidget();
}
if (workQueue.isCompleted &&
workQueue.crossword.characters.isNotEmpty) {
return CrosswordPuzzleWidget();
}
return CrosswordGeneratorWidget();
},
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(child: Text('$error')),
);
},
),
),
),
);
}
}
class _EagerInitialization extends ConsumerWidget {
const _EagerInitialization({required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(wordListProvider);
return child;
}
}
class _CrosswordPuzzleAppMenu extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) => MenuAnchor(
menuChildren: [
for (final entry in CrosswordSize.values)
MenuItemButton(
onPressed: () => ref.read(sizeProvider.notifier).setSize(entry),
leadingIcon: entry == ref.watch(sizeProvider)
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
child: Text(entry.label),
),
],
builder: (context, controller, child) => IconButton(
onPressed: () => controller.open(),
icon: Icon(Icons.settings),
),
);
}
Most of this file should be fairly familiar by now. Yes, there will be undefined widgets, which you will now start fixing.
- Create a
crossword_generator_widget.dartfile and add the following content to it:
lib/widgets/crossword_generator_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart';
import '../model.dart';
import '../providers.dart';
class CrosswordGeneratorWidget extends ConsumerWidget {
const CrosswordGeneratorWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
return TableView.builder(
diagonalDragBehavior: DiagonalDragBehavior.free,
cellBuilder: _buildCell,
columnCount: size.width,
columnBuilder: (index) => _buildSpan(context, index),
rowCount: size.height,
rowBuilder: (index) => _buildSpan(context, index),
);
}
TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
final location = Location.at(vicinity.column, vicinity.row);
return TableViewCell(
child: Consumer(
builder: (context, ref, _) {
final character = ref.watch(
workQueueProvider.select(
(workQueueAsync) => workQueueAsync.when(
data: (workQueue) => workQueue.crossword.characters[location],
error: (error, stackTrace) => null,
loading: () => null,
),
),
);
final explorationCell = ref.watch(
workQueueProvider.select(
(workQueueAsync) => workQueueAsync.when(
data: (workQueue) =>
workQueue.locationsToTry.keys.contains(location),
error: (error, stackTrace) => false,
loading: () => false,
),
),
);
if (character != null) {
return AnimatedContainer(
duration: Durations.extralong1,
curve: Curves.easeInOut,
color: explorationCell
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onPrimary,
child: Center(
child: AnimatedDefaultTextStyle(
duration: Durations.extralong1,
curve: Curves.easeInOut,
style: TextStyle(
fontSize: 24,
color: explorationCell
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.primary,
),
child: Text('•'), // https://www.compart.com/en/unicode/U+2022
),
),
);
}
return ColoredBox(
color: Theme.of(context).colorScheme.primaryContainer,
);
},
),
);
}
TableSpan _buildSpan(BuildContext context, int index) {
return TableSpan(
extent: FixedTableSpanExtent(32),
foregroundDecoration: TableSpanDecoration(
border: TableSpanBorder(
leading: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
trailing: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
);
}
}
This should also be reasonably familiar. The primary difference is that instead of displaying the characters of the words being generated, you are now displaying a unicode character to denote the presence of an unknown character. This really could use some work to improve the aesthetics.
- Create
crossword_puzzle_widget.dartfile and add the following content to it:
lib/widgets/crossword_puzzle_widget.dart
import 'package:built_collection/built_collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart';
import '../model.dart';
import '../providers.dart';
class CrosswordPuzzleWidget extends ConsumerWidget {
const CrosswordPuzzleWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = ref.watch(sizeProvider);
return TableView.builder(
diagonalDragBehavior: DiagonalDragBehavior.free,
cellBuilder: _buildCell,
columnCount: size.width,
columnBuilder: (index) => _buildSpan(context, index),
rowCount: size.height,
rowBuilder: (index) => _buildSpan(context, index),
);
}
TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
final location = Location.at(vicinity.column, vicinity.row);
return TableViewCell(
child: Consumer(
builder: (context, ref, _) {
final character = ref.watch(
puzzleProvider.select(
(puzzle) => puzzle.crossword.characters[location],
),
);
final selectedCharacter = ref.watch(
puzzleProvider.select(
(puzzle) =>
puzzle.crosswordFromSelectedWords.characters[location],
),
);
final alternateWords = ref.watch(
puzzleProvider.select((puzzle) => puzzle.alternateWords),
);
if (character != null) {
final acrossWord = character.acrossWord;
var acrossWords = BuiltList<String>();
if (acrossWord != null) {
acrossWords = acrossWords.rebuild(
(b) => b
..add(acrossWord.word)
..addAll(
alternateWords[acrossWord.location]?[acrossWord
.direction] ??
[],
)
..sort(),
);
}
final downWord = character.downWord;
var downWords = BuiltList<String>();
if (downWord != null) {
downWords = downWords.rebuild(
(b) => b
..add(downWord.word)
..addAll(
alternateWords[downWord.location]?[downWord.direction] ??
[],
)
..sort(),
);
}
return MenuAnchor(
builder: (context, controller, _) {
return GestureDetector(
onTapDown: (details) =>
controller.open(position: details.localPosition),
child: AnimatedContainer(
duration: Durations.extralong1,
curve: Curves.easeInOut,
color: Theme.of(context).colorScheme.onPrimary,
child: Center(
child: AnimatedDefaultTextStyle(
duration: Durations.extralong1,
curve: Curves.easeInOut,
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.primary,
),
child: Text(selectedCharacter?.character ?? ''),
),
),
),
);
},
menuChildren: [
if (acrossWords.isNotEmpty && downWords.isNotEmpty)
Padding(
padding: const EdgeInsets.all(4),
child: Text('Across'),
),
for (final word in acrossWords)
_WordSelectMenuItem(
location: acrossWord!.location,
word: word,
selectedCharacter: selectedCharacter,
direction: Direction.across,
),
if (acrossWords.isNotEmpty && downWords.isNotEmpty)
Padding(
padding: const EdgeInsets.all(4),
child: Text('Down'),
),
for (final word in downWords)
_WordSelectMenuItem(
location: downWord!.location,
word: word,
selectedCharacter: selectedCharacter,
direction: Direction.down,
),
],
);
}
return ColoredBox(
color: Theme.of(context).colorScheme.primaryContainer,
);
},
),
);
}
TableSpan _buildSpan(BuildContext context, int index) {
return TableSpan(
extent: FixedTableSpanExtent(32),
foregroundDecoration: TableSpanDecoration(
border: TableSpanBorder(
leading: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
trailing: BorderSide(
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
);
}
}
class _WordSelectMenuItem extends ConsumerWidget {
const _WordSelectMenuItem({
required this.location,
required this.word,
required this.selectedCharacter,
required this.direction,
});
final Location location;
final String word;
final CrosswordCharacter? selectedCharacter;
final Direction direction;
@override
Widget build(BuildContext context, WidgetRef ref) {
final notifier = ref.read(puzzleProvider.notifier);
return MenuItemButton(
onPressed:
ref.watch(
puzzleProvider.select(
(puzzle) => puzzle.canSelectWord(
location: location,
word: word,
direction: direction,
),
),
)
? () => notifier.selectWord(
location: location,
word: word,
direction: direction,
)
: null,
leadingIcon:
switch (direction) {
Direction.across => selectedCharacter?.acrossWord?.word == word,
Direction.down => selectedCharacter?.downWord?.word == word,
}
? Icon(Icons.radio_button_checked_outlined)
: Icon(Icons.radio_button_unchecked_outlined),
child: Text(word),
);
}
}
This widget is a bit more intense than the last one, even though it has been constructed from pieces you have seen used in other places in the past. Now, each populated cell produces a context menu when clicked, which lists the words a user can select. If words have been selected, then words that conflict aren't selectable. To deselect a word, the user taps on the menu item for that word.
Assuming the player can select words to fill the entire crossword, you need a "You've won!" screen.
- Create a
puzzle_completed_widget.dartfile and then add the following content to it:
lib/widgets/puzzle_completed_widget.dart
import 'package:flutter/material.dart';
class PuzzleCompletedWidget extends StatelessWidget {
const PuzzleCompletedWidget({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'Puzzle Completed!',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
),
);
}
}
I'm sure you can take this and make it more interesting. To learn more about animation tools, see the Building next generation UIs in Flutter codelab.
- Edit your
lib/main.dartfile as follows:
lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'widgets/crossword_puzzle_app.dart'; // Update this line
void main() {
runApp(
ProviderScope(
child: MaterialApp(
title: 'Crossword Puzzle', // Update this line
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorSchemeSeed: Colors.blueGrey,
brightness: Brightness.light,
),
home: CrosswordPuzzleApp(), // Update this line
),
),
);
}
When you run this app, you will see the animation as the crossword generator generates your puzzle. Then you will be presented with a blank puzzle to solve. Assuming you solve it, you should be presented with a screen that looks like this:

১০. অভিনন্দন
Congratulations! You succeeded in building a puzzle game with Flutter!
You built a crossword generator that became a puzzle game. You mastered running background computations in a pool of isolates. You used immutable data structures to ease the implementation of a backtracking algorithm. And you spent quality time with TableView , which will come in handy the next time you need to display tabular data.