0% found this document useful (0 votes)
2 views14 pages

Best Codes Notes'

The document is a Flutter application that implements multiple games including Snake, Tic Tac Toe, and Memory. It features a user interface with buttons for game selection and gameplay mechanics for each game, including score tracking and game state management. The code includes various widgets and state management techniques to handle user interactions and game logic.

Uploaded by

tecagen846
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Best Codes Notes'

The document is a Flutter application that implements multiple games including Snake, Tic Tac Toe, and Memory. It features a user interface with buttons for game selection and gameplay mechanics for each game, including score tracking and game state management. The code includes various widgets and state management techniques to handle user interactions and game logic.

Uploaded by

tecagen846
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

import 'package:flutter/material.

dart';
import 'dart:async';
import 'dart:math';
import 'package:flutter/services.dart';

void main() {
runApp(N_GAMES());
}

.black), // Change icon color


onPressed: () {
// Add functionality to open Tiktok page
},
),
IconButton(
icon: Icon(Icons.apple, color: Colors.black), // Change
icon color
onPressed: () {
// Add functionality to open Apple page
},
),
IconButton(
icon: Icon(Icons.facebook_outlined, color:
Colors.blue), // Change icon color
onPressed: () {
// Add functionality to open Facebook page
},
),
IconButton(
icon: Icon(Icons.discord_outlined, color: Colors.purple),
// Change icon color
onPressed: () {
// Add functionality to open Discord page
},
),
IconButton(
icon: Icon(Icons.wechat, color: Colors.green), // Change
icon color
onPressed: () {
// Add functionality to open Wechat page
},
),
],
),
],
);
},
),
],
),
),
backgroundColor: Colors.white, // Change background color
);
}

void setState(Null Function() param0) {}


}

class GameOption extends StatelessWidget {


final String gameN;
final VoidCallback onPressed;

const GameOption({
required this.gameN,
required this.onPressed,
});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(gameN, style: TextStyle(color: Colors.blue, fontSize: 15)),
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black, // Change button color
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
),
),
);
}
}

class GamePage extends StatefulWidget {


@override
_GamePageState createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> {


static const int rows = 20;
static const int columns = 20;
static const int initialSnakeLength = 1;
static const int speed = 200;

List<int> snake = [];


int food = -1;
bool isPlaying = false;
bool isPaused = false;
Direction direction = Direction.right;
Timer? timer;
int score = 0;

Offset? swipeStartPosition;
static const double swipeThreshold = 50.0;

@override
void initState() {
super.initState();
startGame();
RawKeyboard.instance.addListener(handleKeyboard);
}

@override
void dispose() {
RawKeyboard.instance.removeListener(handleKeyboard);
timer?.cancel();
super.dispose();
}

void handleKeyboard(RawKeyEvent event) {


// No longer handling keyboard input
}

void startGame() {
snake.clear();
final int mid = (rows * columns / 2).toInt();
for (int i = 0; i < initialSnakeLength; i++) {
snake.add(mid - i);
}
generateFood();
isPlaying = true;
timer?.cancel();
timer = Timer.periodic(Duration(milliseconds: speed), (timer) {
if (!isPaused) {
move();
}
});
}

void generateFood() {
final random = Random();
food = random.nextInt(rows * columns);
}

void move() {
setState(() {
int head = snake.first;

int newHead;
switch (direction) {
case Direction.up:
newHead = head - columns;
break;
case Direction.down:
newHead = head + columns;
break;
case Direction.left:
newHead = head - 1;
break;
case Direction.right:
newHead = head + 1;
break;
}

if (newHead == food) {
score++;
generateFood();
snake.insert(0, newHead);
} else {
snake.removeLast();
snake.insert(0, newHead);
}

if (isGameOver()) {
gameOver();
}
});
}

bool isGameOver() {
for (int i = 1; i < snake.length; i++) {
if (snake[i] == snake.first) {
return true;
}
}

if (snake.first < 0 ||
snake.first >= rows * columns ||
(direction == Direction.left && snake.first % columns == 0) ||
(direction == Direction.right && (snake.first + 1) % columns == 0)) {
return true;
}

return false;
}

void gameOver() {
setState(() {
isPlaying = false;
timer?.cancel();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(

title: Text('𝙉𝙤𝙤𝙗 𝙋𝙡𝙖𝙮𝙚𝙧'),


backgroundColor: Colors.black,

titleTextStyle: TextStyle(color: Colors.white),


content: Text('Score : $score'),
contentTextStyle: TextStyle(color: Colors.white),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();

child: Text('𝗢𝗞'),
},

style: ButtonStyle(foregroundColor:
MaterialStateProperty.all<Color>(Colors.white),
),
)
],
);
},
);
});
}

void pauseGame() {
setState(() {
isPaused = !isPaused;
timer?.cancel();
if (!isPaused) {
timer = Timer.periodic(Duration(milliseconds: speed), (timer) {
if (!isPaused) {
move();
}
});
}
});
}

void changeDirection(Direction newDirection) {


if ((direction == Direction.up && newDirection == Direction.down) ||
(direction == Direction.down && newDirection == Direction.up) ||
(direction == Direction.left && newDirection == Direction.right) ||
(direction == Direction.right && newDirection == Direction.left)) {
return;
}
setState(() {
direction = newDirection;
});
}

@override
Widget build(BuildContext context) {
return GestureDetector(
onHorizontalDragStart: (details) {
swipeStartPosition = details.globalPosition;
},
onHorizontalDragEnd: (details) {
if (swipeStartPosition != null) {
double dx = details.velocity.pixelsPerSecond.dx;
if (dx.abs() > swipeThreshold) {
if (dx > 0) {
changeDirection(Direction.right);
} else {
changeDirection(Direction.left);
}
}
}
swipeStartPosition = null;
},
onVerticalDragStart: (details) {
swipeStartPosition = details.globalPosition;
},
onVerticalDragEnd: (details) {
if (swipeStartPosition != null) {
double dy = details.velocity.pixelsPerSecond.dy;
if (dy.abs() > swipeThreshold) {
if (dy > 0) {
changeDirection(Direction.down);
} else {
changeDirection(Direction.up);
}
}
}
swipeStartPosition = null;
},
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,

title: Text('𝙉_𝙎𝙉𝘼𝙆𝙀 𝙂𝘼𝙈𝙀'),


titleTextStyle: TextStyle(color: Colors.white),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
Navigator.pop(context);
},
),
),
backgroundColor: Colors.black,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Score : $score',
style: TextStyle(fontSize: 20, color: Colors.white),
),
SizedBox(height: 20),
Container(
width: 300,
height: 300,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
),
itemCount: rows * columns,
itemBuilder: (context, index) {
return buildGridItem(index);
},
),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
pauseGame();
},
child: Text(isPaused ? 'Resume' : 'Pause'),
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white, backgroundColor: Colors.black,
),
),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Quit'),
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white, backgroundColor: Colors.black,
),
),
],
),
],
),
),
),
);
}

Widget buildGridItem(int index) {


if (snake.contains(index)) {
return buildSnakeCell();
} else if (index == food) {
return buildFoodCell();
} else {
return buildEmptyCell();
}
}

Widget buildSnakeCell() {return Container(


decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(5),
),
);
}

Widget buildFoodCell() {
return Container(
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(5),
),
);
}

Widget buildEmptyCell() {
return Container(
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(5),
),
);
}
}

enum Direction { up, down, left, right }

class TicTacToeGameOption extends StatelessWidget {


final String gameN;
final VoidCallback onPressed;

const TicTacToeGameOption({
required this.gameN,
required this.onPressed,
});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(gameN, style: TextStyle(color: Colors.blue,fontSize: 15)),
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black, // Change button color
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
),
),
);
}
}

class TicTacToeGame extends StatefulWidget {


@override
_TicTacToeGameState createState() => _TicTacToeGameState();
}

class _TicTacToeGameState extends State<TicTacToeGame> {


List<List<String>> board = List.generate(3, (_) => List.filled(3, ''));

bool xTurn = true;


int filledCells = 0;

void resetGame() {
setState(() {
board = List.generate(3, (_) => List.filled(3, ''));
xTurn = true;
filledCells = 0;
});
}

void makeMove(int row, int col) {


if (board[row][col] == '') {
setState(() {
board[row][col] = xTurn ? 'X' : 'O';
xTurn = !xTurn;
filledCells++;
});
checkWinner(row, col);
}
}

void checkWinner(int row, int col) {


String player = board[row][col];
// Check row
if (board[row].every((cell) => cell == player)) {
showWinner(player);
return;
}
// Check column
if (board.every((row) => row[col] == player)) {
showWinner(player);
return;
}
// Check diagonals
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player)
||
(board[0][2] == player && board[1][1] == player && board[2][0] == player))
{
showWinner(player);
return;
}
// Check draw
if (filledCells == 9) {
showWinner('draw');
}
}

void showWinner(String player) {


showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Colors.black,

player == 'draw' ? '𝘿𝙧𝙖𝙬 !' : '𝙒𝙞𝙣𝙣𝙚𝙧 : $player',


title: Text(

style: TextStyle(color: Colors.white),


),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
resetGame();
},

'𝗣𝗟𝗔𝗬 𝗔𝗚𝗔𝗜𝗡',
child: Text(

style: TextStyle(color: Colors.white),


),
),
],
);
},
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
Navigator.pop(context);
},
),

'𝙉_𝙏𝙄𝘾 𝙏𝘼𝘾 𝙏𝙊𝙀 𝙂𝘼𝙈𝙀',


title: Text(

style: TextStyle(color: Colors.white,fontSize: 15),


),
),
body: Container(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
for (int i = 0; i < 3; i++)
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int j = 0; j < 3; j++)
GestureDetector(
onTap: () => makeMove(i, j),
child: Container(
width: 50,
height: 50,
decoration: BoxDecoration(
border: Border.all(),
color: Colors.grey,
),
child: Center(
child: Text(
board[i][j],
style: TextStyle(
fontSize: 24,
color: board[i][j] == 'X' ? Colors.blue : Colors.red,
),
),
),
),
),
],
),
SizedBox(height: 20), // Adding space below the game board
ElevatedButton(
onPressed: resetGame,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black, // Change background color to black
),
child: Text(
'Reset',
style: TextStyle(color: Colors.white),
),
),
],
),
),
);
}
}

class MemoryOption extends StatelessWidget {


final String gameN;
final VoidCallback onPressed;

const MemoryOption({
required this.gameN,
required this.onPressed,
});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(gameN, style: TextStyle(color: Colors.blue, fontSize: 15)),
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black, // Change button color
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
),
),
);
}
}

class MemoryGame extends StatefulWidget {


@override
_MemoryGameState createState() => _MemoryGameState();
}

class _MemoryGameState extends State<MemoryGame> {


List<String> items = ['🍎', '🍊', '🍋', '🍉', '🍇', '🍌', '🍒', '🍍'];
List<String> tiles = [];
List<bool> flipped = [];
List<int> matchedIndices = [];
bool gameActive = true;
int moves = 0;

@override
void initState() {
super.initState();
generateItems();
items.shuffle();
int length = items.length;
if (length > 0 && length % 2 == 0) {
tiles = List.filled(length, ''); // Initialize with empty strings
flipped = List.filled(length, false); // Initialize with false values
} else {
// Handle invalid length of items list
throw Exception("Invalid length of items list");
}
}

void generateItems() {
List<String> originalItems = ['🍎', '🍊', '🍋', '🍉', '🍇', '🍌', '🍒', '🍍'];
items = [];
for (String item in originalItems) {
items.addAll([item, item]); // Duplicate each item
}
}

void resetGame() {
setState(() {
items.shuffle();
tiles = List.generate(items.length, (index) => items[index]);
flipped = List.generate(items.length, (index) => false);
matchedIndices.clear();
gameActive = true;
moves = 0;
});
}

void checkMatch(int index) {


if (flipped.where((element) => element).length == 2) {
// If already 2 tiles are flipped, return
return;
}
setState(() {
flipped[index] = true;
});
List<int> flippedIndices = [];
for (int i = 0; i < flipped.length; i++) {
if (flipped[i]) {
flippedIndices.add(i);
}
}
if (flippedIndices.length == 2) {
if (tiles[flippedIndices[0]] == tiles[flippedIndices[1]]) {
// Match found
matchedIndices.addAll(flippedIndices);
if (matchedIndices.length == items.length) {
// All tiles are matched, end game
gameActive = false;
showWinnerDialog();
}
} else {
// Not a match, flip tiles back
Future.delayed(Duration(seconds: 1), () {
setState(() {
flipped[flippedIndices[0]] = false;
flipped[flippedIndices[1]] = false;
});
});
}
}
}

void showWinnerDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Congratulations!'),
content: Text('You won in $moves moves!'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
resetGame();
},
child: Text('Play Again'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
Navigator.of(context).pop();
},

title: Text('𝙉_𝙈𝙀𝙈𝙊𝙍𝙔 𝙂𝘼𝙈𝙀', style: TextStyle(color:


),

Colors.white,fontSize: 15)),
),
backgroundColor: Colors.black,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: GridView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
childAspectRatio: 1,
),
itemCount: tiles.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
if (!flipped[index] && gameActive) {
setState(() {
moves++;
});
checkMatch(index);
}
},
child: Container(
margin: EdgeInsets.all(4),
color: flipped[index] || matchedIndices.contains(index)
? Colors.grey
: Colors.blue,
child: Center(
child: Text(
flipped[index] || matchedIndices.contains(index)
? tiles[index]
: '',
style: TextStyle(fontSize: 32),
),
),
),
);
},
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: resetGame,
child: Text('Reset', style: TextStyle(color: Colors.white)),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 50),
),
),
],
),
);
}
}

You might also like