Разобраться в логике игры на сопоставление

Делается приложение по изучению английского языка. Так вот, есть 200 английских слов, переводы к ним соответственно.

Дополнительно хочется сделать игру по типу этой:

import 'dart:math';
import 'package:flutter/material.dart';

class MemoryGame extends StatefulWidget {
@override
_MemoryGameState createState() => _MemoryGameState();
}

class _MemoryGameState extends State<MemoryGame> {
List<Widget> widgetList = List<Widget>();
List<Key> keyList = List<Key>();
List<Key> matchedKeys = List<Key>();
String selectedText;
Key selectedKey;

List<Widget> _createListOfCards() {
// adding the text that to be shown
List<int> textInput = List<int>();
for (int i = 1; i <= 8; i++) {
  textInput.add(i);
  textInput.add(i);
}

//Randomly picking up the text and creating the card
final _random = new Random();
for (int i = 1; i <= 4; i++)
  for (int j = 1; j <= 4; j++) {
    var key = UniqueKey();
    keyList.add(key);
    int _inputVal = textInput[_random.nextInt(textInput.length)];
    widgetList.add(FlipCard(
      txt: _inputVal.toString(),
      key: key,
      onFlipChange: (Key val, String txt) {
        if (selectedKey != key) {
          if (selectedText == null) {
            selectedText = txt;
            selectedKey = val;
          } else if (selectedText == txt) {
            matchedKeys.add(val);
            matchedKeys.add(selectedKey);
            selectedText = null;
            selectedKey = null;
            _flipTheOtherOpenCards();
          } else {
            selectedText = null;
            selectedKey = null;
            _flipTheOtherOpenCards();
          }
        } else {
          selectedText = null;
          selectedKey = null;
        }
      },
    ));

    textInput.removeAt(textInput.lastIndexOf(_inputVal));
  }
return widgetList;
}

_flipTheOtherOpenCards() {
if (matchedKeys.length == 16) {
  _showSuccessDialog();
} else {
  Future.delayed(const Duration(milliseconds: 1000), () {
    widgetList.forEach((element) {
      if (matchedKeys.contains(element.key)) {
        (element as FlipCard).cardObject.disableAnimation();
      } else if (selectedKey == element.key) {
      } else {
        (element as FlipCard).cardObject.flipTheOpenCards();
      }
    });
  });
}
}

Future<void> _showSuccessDialog() async {
return showDialog<void>(
  context: context,
  barrierDismissible: false, // user must tap button!
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Awesome'),
      content: Text('Completed the game successfully'),
      actions: <Widget>[
        TextButton(
          child: Text('Close'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
);
}

@override
Widget build(BuildContext context) {
var lists = _createListOfCards();
return GridView.count(crossAxisCount: 4, children: lists);
}
}

// ignore: must_be_immutable
class FlipCard extends StatefulWidget {
final String txt;
final Function(Key, String) onFlipChange;

FlipCard({Key key, this.txt, this.onFlipChange}) : super(key: key);
_FlipCardState cardObject;

_FlipCardState getObject() {
cardObject = _FlipCardState(txt);
return cardObject;
}

@override
_FlipCardState createState() => getObject();
}

class _FlipCardState extends State<FlipCard>
with SingleTickerProviderStateMixin {
AnimationController _animationController;
Animation _animation;
AnimationStatus _animationStatus = AnimationStatus.dismissed;
final String txt;
bool clickDisabled = false;

_FlipCardState(this.txt);
@override
void initState() {
super.initState();
_animationController =
    AnimationController(vsync: this, duration: Duration(milliseconds: 500));
_animation = Tween(end: 0.0, begin: 1.0).animate(_animationController)
  ..addListener(() {
    setState(() {});
  })
  ..addStatusListener((status) {
    _animationStatus = status;
  });
 }

 void flipTheOpenCards() {
 if (_animationStatus != AnimationStatus.dismissed) {
  _animationController.reverse();
  }
 }

 void disableAnimation() {
 clickDisabled = true;
 }

 @override
 Widget build(BuildContext context) {
 return Container(
  child: Center(
    child: Transform(
      alignment: FractionalOffset.center,
      transform: Matrix4.identity()
        ..rotateY((pi * double.parse(_animation.value.toString()))),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: GestureDetector(
          onTap: () {
            if (!clickDisabled) {
              if (_animationStatus == AnimationStatus.dismissed) {
                _animationController.forward();
              } else {
                _animationController.reverse();
              }
              widget.onFlipChange(widget.key, widget.txt);
            }
          },
          child: _animation.value > 0.5
              ? Card(
                  elevation: 8,
                  shadowColor: Colors.tealAccent,
                  semanticContainer: true,
                  clipBehavior: Clip.antiAliasWithSaveLayer,
                  shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.all(Radius.circular(10.0))),
                  child: Container(
                    color: Colors.teal,
                    width: MediaQuery.of(context).size.width / 5,
                    height: MediaQuery.of(context).size.width / 5,
                    child: Icon(
                      Icons.ac_unit_sharp,
                      color: Colors.white70,
                      size: 50,
                    ),
                  ),
                )
              : Card(
                  elevation: 8,
                  shadowColor: Colors.amberAccent,
                  shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.all(Radius.circular(10.0))),
                  semanticContainer: true,
                  clipBehavior: Clip.antiAliasWithSaveLayer,
                  child: Container(
                      color: Colors.amber,
                      width: MediaQuery.of(context).size.width / 5,
                      height: MediaQuery.of(context).size.width / 5,
                      child: Center(
                        child: Text(
                          widget.txt,
                          style: TextStyle(
                              color: Colors.red,
                              fontWeight: FontWeight.bold,
                              fontSize: 32),
                          ),
                      )),
                ),
           ),
          ),
        ),
      ),
     );
     }
    }

Классическая карточная игра на сопоставление (на память), где нужно на перевернутых картах найти одинаковые числа. Так вот, идея такая, чтобы сделать нечто подобное, но сопоставлялись не цифры, а английское слово с его переводом.

Собственно вопрос заключается в помощи с этим советом, кодом.


Ответы (0 шт):