Skip to content

Instantly share code, notes, and snippets.

@micedreams
Last active November 12, 2023 10:38
Show Gist options
  • Save micedreams/0d370bd59a8ebaf941d18c1ba79351b9 to your computer and use it in GitHub Desktop.
Save micedreams/0d370bd59a8ebaf941d18c1ba79351b9 to your computer and use it in GitHub Desktop.
Cow and bull
Concept:
On a sheet of paper, the players each write a 4-digit secret number. 
The digits must be all different. Then, in turn, the players try to guess their opponent's number who 
gives the number of matches. If the matching digits are in their right positions, they are "bulls",
if in different positions, they are "cows". 

Example: Secret number: 4271 Opponent's try: 1234 
Answer: 1 bull and 2 cows. (The bull is "2", the cows are "4" and "1".)
Task:
 What steps you will take to make a mobile app for this game? 
 Write pseudo code for executing game logic?
  1. Create a new Flutter app.
  2. Add a function to calculate bulls and cows. Here we do 3 things ok 4.
    1. Send a user input as an argument.
    2. Have a random number generator to generate secret number.
    3. And then make checks on the user input number against the secret number.
    4. then return the secret number, cows and bulls. (We can either create a model to do this.. or behave badly and return it as a Map.)
  3. Add text Field for user input.
  4. Call the above function every time the user calls onSubmitted method.
  5. Show calculated cows and bulls along with secret numbers in a cool way.
  6. Finally, make sure the value changes every time the user inputs a new number!! (use a value listener builder or some other state management system.)

Pseudo code:

Map getBullsOrCows(String input) {
final random = Random();
String secret = '';
for (var i = 0; i < 4; i++) {
  secret = secret + random.nextInt(9).toString();
}

final a = x.split('');
final b = secret.split('');

int bull = 0;
int cow = 0;

for (int i = 0; i < a.length; i++) {
  if (b.contains(a[i])) {
    if (a[i] == b[i]) {
      cow++;
    } else {
      bull++;
    }
  }
}

return {'secret': secret, 'bull': '$bull', 'cow': '$cow'};
}

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
const digits = 4;
void main() {
runApp(CowNBull());
}
class CowNBull extends StatelessWidget {
CowNBull({super.key});
final valueNotifier = ValueNotifier<Map?>(null);
final controller = TextEditingController(text: '');
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'cow and bull',
theme: ThemeData(
brightness: Brightness.dark,
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('# cow and bull'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('Enter a $digits digit number'),
Row(
children: [
SizedBox(
width: 100,
child: TextField(
controller: controller,
maxLength: digits,
keyboardType: TextInputType.number,
onSubmitted: onSubmit,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
),
),
ElevatedButton(
onPressed: () => onSubmit(controller.text),
child: const Text('Go'),
)
],
),
ValueListenableBuilder(
valueListenable: valueNotifier,
builder: (context, value, _) {
if (null == value) {
return Container();
}
final list = <Widget>[];
for (int i = 0; i < value.length; i++) {
list.add(ListTile(
title: Text(value.keys.elementAt(i)),
subtitle: Text(value.values.elementAt(i)),
));
}
return Column(children: list);
},
),
],
),
),
);
}
void onSubmit(value) {
digits == value.length ? valueNotifier.value = getBullsOrCows(value) : null;
controller.clear();
}
}
Map getBullsOrCows(String x) {
var random = Random();
String secret = '';
for (var i = 0; i < 4; i++) {
secret = secret + random.nextInt(9).toString();
}
final a = x.split('');
final b = secret.split('');
int bull = 0;
int cow = 0;
for (int i = 0; i < a.length; i++) {
if (b.contains(a[i])) {
if (a[i] == b[i]) {
cow++;
} else {
bull++;
}
}
}
return {'My input': x, 'secret': secret, 'bull': '$bull', 'cow': '$cow'};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment