Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions memory-game/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions memory-game/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
Binary file added memory-game/app/favicon.ico
Binary file not shown.
26 changes: 26 additions & 0 deletions memory-game/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@import "tailwindcss";

:root {
--background: #ffffff;
--foreground: #171717;
}

@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}

@media (prefers-color-scheme: light) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}

body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
29 changes: 29 additions & 0 deletions memory-game/app/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";

const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});

const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});

export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

export default function RootLayout({ children }) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}
12 changes: 12 additions & 0 deletions memory-game/app/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import MemoryGame from '@/components/MemoryGame'
import React from 'react'

const page = () => {
return (
<div>
<MemoryGame/>
</div>
)
}

export default page
147 changes: 147 additions & 0 deletions memory-game/components/MemoryGame.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"use client";

import React, { useEffect, useState } from "react";

const MemoryGame = () => {
const [gridSize, setGridSize] = useState(2);

const [array, setArray] = useState([]);
const [flipped, setFlipped] = useState([]);
const [slectedPairs, setSelectedPairs] = useState([]);
const [disabled, setDisabled] = useState(false);

const [won, setWon] = useState(false);

const handleGridSize = (e) => {
const size = parseInt(e.target.value);
//console.log(size)
if (2 <= size && size <= 10) {
setGridSize(size);
}
};

const initalizeGame = () => {
const totalCards = gridSize * gridSize;
const pairCount = Math.floor(totalCards / 2);

const numbers = [...Array(pairCount).keys()].map((n) => n + 1);
const suffledCards = [...numbers, ...numbers]
.sort(() => Math.random() - 0.5)
.map((number, index) => ({
id: index,
number,
}));

setArray(suffledCards);
setFlipped([]);
setSelectedPairs([]);
setDisabled(false);
setWon(false);
};

const handleMatch = (secondId) => {
const [firstId] = flipped;

if (array[firstId].number == array[secondId].number) {
setSelectedPairs([...slectedPairs, firstId, secondId]);
setFlipped([]);
setDisabled(false);
} else {
setTimeout(() => {
setDisabled(false);
setFlipped([]);
}, 1000);
}
};

useEffect(() => {
initalizeGame();
}, [gridSize]);

const handleClick = (id) => {
if (disabled || won) return;

if (flipped.length === 0) {
setFlipped([id]);
return;
}

if (flipped.length === 1) {
setDisabled(true); //so we cant choose another one
if (id !== flipped[0]) {
setFlipped([...flipped, id]);
//check match logic
handleMatch(id);
} else {
setFlipped([]);
setDisabled(false);
}
}
};

const isFlipped = (id) => flipped.includes(id) || slectedPairs.includes(id);
const isselectedpairs = (id) => slectedPairs.includes(id);

useEffect(() => {
if (slectedPairs.length === array.length && array.length > 0) {
setWon(true);
}
}, [slectedPairs, array]);

return (
<div className="h-[100vh] flex flex-col justify-center items-center p-4 bg-gray-100 ">
{/* Heading */}
<h1 className="text-3xl font-bold mb-6 ">Memory Game</h1>
{/* Grid Size */}
<div className="mb-4">
<label htmlFor="gridSize">Grid Size:(max 10)</label>
<input
type="number"
className="w-[50px] ml-3 rounded border-2 px-1.5 py-1"
min="2"
max="10"
value={gridSize}
onChange={handleGridSize}
/>
</div>
{/* Cards */}
<div
className="grid gap-2 mb-4"
style={{
gridTemplateColumns: `repeat(${gridSize}, minmax(0,1fr))`,
width: `min(100%,${gridSize * 5.5}rem)`,
}}
>
{array.map((array) => (
<div
key={array.id}
onClick={() => handleClick(array.id)}
className={`aspect-square flex items-center justify-center text-xl transition-all duration-300 font-bold rounded-lg cursor-pointer ${
isFlipped(array.id)
? isselectedpairs(array.id)
? "bg-green-500 text-white"
: "bg-blue-500 text-white"
: "bg-gray-300 text-gray-400 "
}`}
>
{isFlipped(array.id) ? array.number : "?"}
</div>
))}
</div>
{/* Result */}
<div className="text-2xl text-green-500 font-bold">
{won ? "You Won!" : ""}
</div>

{/* Rest Button */}
<button
className="px-5 py-2 bg-green-500 rounded text-white mt-5"
onClick={initalizeGame}
>
Reset
</button>
</div>
);
};

export default MemoryGame;
25 changes: 25 additions & 0 deletions memory-game/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname,
});

const eslintConfig = [
...compat.extends("next/core-web-vitals"),
{
ignores: [
"node_modules/**",
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
],
},
];

export default eslintConfig;
7 changes: 7 additions & 0 deletions memory-game/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
4 changes: 4 additions & 0 deletions memory-game/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;
Loading