Step 4: The Best Score Stays چالش 4 از جلسهی 40، سخت
قدم آخر: رکورد. یک خط تازه در صفحه هست: <p id="best">.
- اول برنامه رکورد را بخوان: let best = salam.load<number>("best", 0);
- در draw آن را نشان بده: setText("best", "Best: " + best);
- در answer، وقتی آخرین سؤال جواب داده شد و score از best بیشتر بود: best را برابر score کن و با salam.save("best", best); نگهش دار.
رکورد باید بعد از باز کردن دوبارهی صفحه بماند، و امتیاز کمتر نباید آن را عوض کند.
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>
<p id="msg"></p>
<button id="a" onclick="answer(0)">A</button>
<button id="b" onclick="answer(1)">B</button>
<button id="c" onclick="answer(2)">C</button>
<p id="score">Score: 0</p>
<button id="again" onclick="restart()">Again</button>
<p id="best">Best: 0</p>
<script type="text/typescript">
interface Question {
text: string;
choices: string[];
answer: number;
}
const questions: Question[] = [
{ text: "2 + 3", choices: ["4", "5", "6"], answer: 1 },
{ text: "10 / 2", choices: ["5", "2", "20"], answer: 0 },
{ text: "3 * 3", choices: ["6", "33", "9"], answer: 2 },
];
let current = 0;
let score = 0;
function isRight(q: Question, choice: number): boolean {
return q.answer === choice;
}
function result(points: number, total: number): string {
if (points === total) {
return "Perfect! " + points + " of " + total;
}
return "Done! " + points + " of " + total;
}
function setText(id: string, text: string): void {
const el = document.getElementById(id);
if (el) {
el.textContent = text;
}
}
function draw(): void {
setText("score", "Score: " + score);
if (current >= questions.length) {
setText("msg", result(score, questions.length));
return;
}
const q = questions[current];
setText("msg", q.text);
setText("a", q.choices[0]);
setText("b", q.choices[1]);
setText("c", q.choices[2]);
}
function answer(choice: number): void {
if (current >= questions.length) {
return;
}
if (isRight(questions[current], choice)) {
score = score + 1;
}
current = current + 1;
draw();
}
function restart(): void {
current = 0;
score = 0;
draw();
}
draw();
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 40: پروژه: کوییز روز، با تایپاسکریپت
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js