Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4주차 기본/심화/공유 과제] API 통신 #5

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
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
24 changes: 24 additions & 0 deletions week3/assignment/assignment3/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
8 changes: 8 additions & 0 deletions week3/assignment/assignment3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# React + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
38 changes: 38 additions & 0 deletions week3/assignment/assignment3/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import js from '@eslint/js'
import globals from 'globals'
import react from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'

export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
settings: { react: { version: '18.3' } },
plugins: {
react,
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
...reactHooks.configs.recommended.rules,
'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
]
14 changes: 14 additions & 0 deletions week3/assignment/assignment3/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id = "modal"></div>
<div id = "root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
31 changes: 31 additions & 0 deletions week3/assignment/assignment3/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "assignment3",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"lodash": "^4.17.21",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"eslint": "^9.13.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.11.0",
"vite": "^5.4.10"
}
}
18 changes: 18 additions & 0 deletions week3/assignment/assignment3/src/App.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Global, ThemeProvider} from '@emotion/react';
import Home from './Home'
import global from './styles/global'
import {Theme} from './styles/theme'

function App() {

return (
<>
<ThemeProvider theme={Theme}>
<Global styles={global} />
<Home />
</ThemeProvider>
</>
)
}

export default App;
48 changes: 48 additions & 0 deletions week3/assignment/assignment3/src/Home.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import styled from "@emotion/styled";
import { useState } from 'react';
import Header from './components/Header';
import Game from './components/Game';
import Rank from './components/Rank'

const Home = () =>{
const [menu, setMenu] = useState("game");
const [level, setLevel] = useState(1);
const [timer, setTimer] = useState(0);

const handleMenuChange = (menu) => {
setMenu(menu);
}
const handleLevelSelect = (level) => {
setLevel(level);
};
const handleTimerChange = (timer) => {
setTimer(timer);
};

return (
<>
<Header
menu={menu}
timer={timer}
handleMenuChange={handleMenuChange}
handleLevelSelect={handleLevelSelect}
/>
<Main>
{menu === "game" ? (
<Game level={level} timer={timer} handleTimerChange={handleTimerChange}/>
):(
<Rank/>
)}
</Main>
</>
);
};

const Main = styled.main`
width: 100%;
height: 100%;
margin: 0 auto;
padding-top: 2rem;
`;

export default Home;
111 changes: 111 additions & 0 deletions week3/assignment/assignment3/src/algorithm/GameAlgorithm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { useState, useEffect } from 'react';

// 숫자를 섞어주는 함수
const randomArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};

// 숫자를 생성해서 랜덤으로 배열에 넣는 함수
const createNums = (min, max) => {
const nums = [];
for (let i = min; i <= max; i++) {
nums.push(i);
}
return randomArray(nums);
};

// 결과 저장 및 local 저장소에서 넣고 빼기
const saveResult = (time, level) => {
const result = {
timestamp: new Date().toISOString(),
time,
level,
};
const savedResults = JSON.parse(localStorage.getItem('results')) || [];
savedResults.push(result);
localStorage.setItem('results', JSON.stringify(savedResults));
};

// 게임 알고리즘
const gameAlgorith = (level, timer, handleTimeChange) => {
const rowNum = level + 2;
const boardSize = rowNum * rowNum;
const maxNum = boardSize * 2;
const [currentNum, setCurrentNum] = useState(1);
const [timeId, setTimeId] = useState(null);
const [isFinish, setIsFinish] = useState(false);
const [beforeNums, setBeforeNums] = useState(createNums(1, boardSize));
const [afterNums, setAfterNums] = useState(createNums(boardSize + 1, maxNum));

const checkNumberClick = (number) => {
// 게임을 시작 할때 타이머를 시작시키는 로직
if (currentNum === 1) {
const id = setInterval(() => {
handleTimeChange((previousTime) => {
const updatedTime = (previousTime + 0.01).toFixed(2);
return parseFloat(updatedTime);
});
}, 10);
setTimeId(id);
}

if (currentNum <= boardSize) {
const newNum = afterNums.pop();
const updateBoard = beforeNums.map((num) =>
num === number ? newNum : num
);
setBeforeNums(updateBoard);
}
// 카드를 없애는 로직
else if (currentNum > boardSize && currentNum < maxNum) {
const updatedBoard = beforeNums.map((num) =>
num === number ? null : num
);
setBeforeNums(updatedBoard);
}

setCurrentNum(currentNum + 1);

if (number === maxNum) {
clearInterval(timeId);
saveResult(timer, level);
setIsFinish(true);
return;
}
};

const closeModal = () => {
setBeforeNums(createNums(1, boardSize));
setAfterNums(createNums(boardSize + 1, maxNum));
setIsFinish(false);
setCurrentNum(1);
handleTimeChange(0);
};

useEffect(() => {
setBeforeNums(createNums(1, boardSize));
setAfterNums(createNums(boardSize + 1, maxNum));
setIsFinish(false);
clearInterval(timeId);
setCurrentNum(1);
handleTimeChange(0);
return () => clearInterval(timeId);
}, [level]); //level이 변경될 때 마다 렌더링이 되도록

return {
rowNum,
maxNum,
beforeNums,
currentNum,
isFinish,
closeModal,
createNums,
checkNumberClick,
};
};

export default gameAlgorith;
22 changes: 22 additions & 0 deletions week3/assignment/assignment3/src/algorithm/formatDate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const formatDate = (timestamp) => {
const dateObj = new Date(timestamp);

let [year, month, day, hour, minute, second] = [
dateObj.getFullYear(),
dateObj.getMonth() + 1,
dateObj.getDate(),
dateObj.getHours(),
dateObj.getMinutes(),
dateObj.getSeconds(),
];

const period = hour >= 12 ? '오후' : '오전';
hour = hour % 12 || 12;

const pad = (num) => num.toString().padStart(2, '0');
const formattedDate = `${year}.${pad(month)}.${pad(day)}`;
const formattedTime = `${period} ${pad(hour)}시 ${pad(minute)}분 ${pad(second)}초`;
return `${formattedDate} ${formattedTime}`;
};

export default formatDate;
Loading