آموزش جاوا اسکریپت پروژه محور | ۱۵ پروژه عملی و کاربردی

۱۴۰۴ بازدید
آخرین به‌روزرسانی: ۰۷ شهریور ۱۴۰۲
زمان مطالعه: ۵۶ دقیقه
آموزش جاوا اسکریپت پروژه محور  | ۱۵ پروژه عملی و کاربردی

جاوا اسکریپت یک زبان سبک و تفسیری برنامه‌نویسی است که برای ایجاد اپلیکیشن‌های مبتنی بر اینترنت طراحی شده است. پیاده‌سازی جاوا اسکریپت بسیار آسان است، ‌زیرا با HTML ادغام شده است. جاوا اسکریپت یک زبان باز و چند پلتفرمی است. در این مقاله به معرفی این زبان و ارائه آموزش جاوا اسکریپت پروژه محور خواهیم پرداخت.

فهرست مطالب این نوشته

چرا باید جاوا اسکریپت یاد بگیریم؟

جاوا اسکریپت یک زبان ضروری برای دانشجویان و شاغلان حرفه‌ای در مسیر تبدیل شدن به یک مهندس ‌‌نرم‌افزار به خصوص در زمان کار در حوزه توسعه وب محسوب می‌شود. در این بخش برخی از آموزش جاوا اسکریپت پروژه محور مزیت‌های کلیدی یادگیری جاوا اسکریپت را توضیح می‌دهیم:

جاوا اسکریپت رایج‌ترین زبان برنامه‌نویسی در دنیا است و به همین جهت به یک گزینه عالی برای برنامه‌نویس‌ها تبدیل شده است. زمانی که جاوا اسکریپت را بیاموزید، به شما کمک می‌کند که فرانت‌اند‌های عالی را طراحی کنید و با استفاده از فریمورک‌های مختلف مبتنی بر جاوا اسکریپت مانند jQuery ،Node.JS و غیره، نرم‌افزارهای بک‌اند را طراحی کنید.

جاوا اسکریپت همه جا حضور دارد و روی همه مرورگرهای مدرن وب از قبل نصب شده است. از این رو برای نوشتن کدهای جاوا اسکریپت عملاً به هیچ چیز نیاز ندارید. مرورگرهای مختلف شامل کروم، فایرفاکس، سافاری و هر مرورگر دیگر که امروزه می‌شناسیم از جاوا اسکریپت پشتیبانی می‌کند.

آموزش جاوا اسکریپت پروژه محور

جاوا اسکریپت به ایجاد وب‌سایت‌های واقعاً زیبا و کاملاً سریع کمک می‌کند. بدین ترتیب می‌توانید وب‌سایت خود را با یک کنسول توسعه دهید، ‌طوری که حس و ظاهر آن بهترین تجربه کاربری گرافیکی را در اختیار کاربر قرار دهد. کاربرد جاوا اسکریپت اینک به توسعه اپلیکیشن‌های موبایل، توسعه اپلیکیشن‌های دسکتاپ و توسعه بازی نیز گسترش یافته است. بدین ترتیب فرصت‌های زیادی در پیش روی برنامه‌نویس جاوا اسکریپت قرار می‌گیرد.

به دلیل تقاضای بالایی که برای جاوا اسکریپت وجود دارد، رشد شغلی بالا و پرداخت حقوقی زیادی برای افرادی که با جاوا اسکریپت برنامه‌نویسی می‌کنند وجود دارد. شما می‌توانید به سایت‌های شغل‌یابی مختلف بروید تا مهارت‌های جاوا اسکریپت مختلفی را که در بازار کار مورد نیاز هستند، ببینید. نکته عالی در مورد جاوا اسکریپت این است که هزاران فریمورک و کتابخانه مختلف وجود دارند که می‌توان مستقیماً در توسعه نرم‌افزار برای کاهش زمان ارائه به بازار مورد استفاده قرار داد.

برای یادگیری زبان برنامه‌نویسی دلایل بسیار زیادی وجود دارند، اما نکته‌ای که باید مطمئن باشیم این است که برای یادگیری هر نوع زبان برنامه‌نویسی، نه فقط جاوا اسکریپت، تنها لازم است که به تمرین کدنویسی بپردازید تا به یک فرد متبحر تبدیل شوید.

برنامه Hello World با استفاده از جاوا اسکریپت

در نخستین گام از آموزش جاوا اسکریپت پروژه محور برای اینکه اندکی آشنایی عملی با این زبان برنامه نویسی پیدا کنید، یک برنامه آزمایشی کوچک Hello World می‌نویسیم:

1<html>
2   <body>   
3      <script language = "javascript" type = "text/javascript">
4         <!--
5            document.write("Hello World!")
6         //-->
7      </script>      
8   </body>
9</html>

فریمورک‌ها و کتابخانه‌های مختلف و زیادی برای جاوا اسکریپت وجود دارند:

  • Angular
  • React
  • jQuery
  • Vue.js
  • Ext.js
  • Ember.js
  • Meteor
  • Mithril
  • Node.js
  • Polymer
  • Aurelia
  • Backbone.js

ارائه لیست کاملی از همه فریمورک‌ها و کتابخانه‌های جاوا اسکریپت مقدور نیست، زیرا دنیای جاوا اسکریپت بسیار بزرگ است و هر روز اتفاقات جدید زیادی در آن رخ می‌دهند.

کاربردهای برنامه‌نویسی جاوا اسکریپت

همچنان که پیش‌تر توضیح دادیم، جاوا اسکریپت یکی از پراستفاده‌ترین زبان‌های برنامه‌نویسی دنیا چه در حوزه فرانت‌اند و چه بک‌اند است. این زبان تقریباً در همه زمینه‌های توسعه نرم‌افزار حضور دارد. در ادامه آموزش جاوا اسکریپت پروژه محور برخی از این موارد را فهرست‌بندی کرده‌ایم.

  • اعتبارسنجی سمت کلاینت: اعتبارسنجی سمت کلاینت برای تأیید همه ورودی‌های کاربر، پیش از تحویل به سرور کمکی زیادی می‌کند و در این مسیر جاوا اسکریپت نقش مهمی در اعتبارسنجی ورودی‌های کاربر در همان سمت فرانت‌اند ایفا می‌کند.
  • دست‌کاری صفحات HTML: جاوا اسکریپت به دست‌کاری صفحه‌های HTML به صورت درجا کمک می‌کند. به این ترتیب می‌توان تگ‌های ‌HTML را به روشی بسیار ساده با استفاده از جاوا اسکریپت حذف یا اضافه کرد و همچنین فایل HTML را مورد ویرایش قرار داد تا حس و ظاهر آن بر مبنای دستگا‌ه‌ها و شرایط مختلف تغییر یابد.
  • نوتیفکیشن‌های کاربر: شما می‌توانید از جاوا اسکریپت برای باز کردن پاپ‌آپ‌های دینامیک روی صفحه‌های وب و ارائه انواع مختلفی از نوتیفکیشن‌ها به بازدیدکنندگان وب‌سایت استفاده کنید.
  • بارگذاری داده‌ها در بک‌اند: جاوا اسکریپت کتابخانه Ajax را ارائه کرده است که به بارگذاری داده‌ها از بک‌اند در زمان اجرای برخی پردازش‌های دیگر کمک می‌کند. به این ترتیب تجربه شگفت‌انگیزی برای بازدیدکنندگان وب‌سایت خلق می‌شود.
  • ارائه: جاوا اسکریپت یک امکان برای ایجاد ارائه نیز فراهم ساخته است که روی حس و ظاهر وب‌سایت تأثیر می‌گذارد. به این منظور کتابخانه‌های RevealJS و BespokeJS برای ساخت ارائه‌های مبتنی بر وب ارائه شده‌اند.
  • اپلیکیشن‌های سرور: NodeJS بر مبنای محیط زمان اجری جاوا اسکریپت در کروم برای ایجاد اپلیکیشن‌های سریع و مقیاس‌پذیر سرور ساخته شده است. این یک کتابخانه مبتنی بر رویداد است که به توسعه بسیاری از اپلیکیشن‌های پیچیده سمت سرور به همراه وب‌سرورها کمک می‌کند.

این لیست همچنان ادامه دارد و زمینه‌های مختلفی وجود دارند که میلیون‌ها توسعه‌دهنده نرم‌افزار در آن‌ها از جاوا اسکریپت برای توسعه وب‌سایت‌ها و دیگر نرم‌افزارهای عالی بهره می‌گیرند.

مطلب آموزش جاوا اسکریپت پروژه محور برای افراد مبتدی نگارش یافته است تا با مبانی مقدماتی زبان برنامه‌نویسی جاوا اسکریپت و روش طراحی صفحه‌های وب دینامیک آشنا شوید، اما برای مطالعه این راهنما و اجرای کد‌های آن می‌بایست دست‌کم دانشی مقدماتی از HTML داشته باشید. همچنین در صورتی که دانش اندکی در مورد برنامه‌نویسی شیءگرا و ایده‌ای کلی در مورد اپلیکیشن‌های آنلاین داشته باشید، کمک بزرگی خواهد بود.

جاوا اسکریپت چیست؟

جاوا اسکریپت چیست

جاوا اسکریپت یک زبان برنامه‌نویسی دینامیک است. این زبان سبک و پرکاربرد به عنوان بخشی از صفحه‌های وب استفاده می‌شود و پیاده‌سازی آن در اسکریپت‌های سمت کلاینت موجب می‌شود که امکان تعامل با کاربر و دینامیک ساختن صفحه‌های وب فراهم آید. جاوا اسکریپت یک زبان برنامه‌نویسی تفسیرشونده با ظرفیت‌های شیءگرایی است.

جاوا اسکریپت در ابتدا به نام LiveScript شناخته می‌شد، اما در ادامه شرکت Netscape نام آن را به JavaScript تغییر داد. دلیل احتمالی این تغییر نام، وجود هیجان زیادی است که در آن زمان با معرفی زبان جدیداً مطرح‌شده جاوا پدید آمده بود. جاوا اسکریپت نخستین بار در مرورگر نت‌اسکیپ 2.0 در سال 1995 با نام LiveScript ظاهر شد. هسته چندمنظوره این زبان در نت‌اسکیپ، اینترنت اکسپلورر و دیگر مرورگرهای وب قرار گرفت. در ادامه مشخصات ECMA-262 یک نسخه استاندارد برای هسته زبان جاوا اسکریپت زیر تعریف کرد.

  • جاوا اسکریپت یک زبان برنامه‌نویسی سبک و تفسیرشونده است.
  • این زبان برای طراحی اپلیکیشن‌های آنلاین طراحی شده است.
  • مکمل جاوا بوده و در آن ادغام می‌شود.
  • مکمل HTML بوده و در آن ادغام می‌شود.
  • جاوا اسکریپت یک زبان باز و چند پلتفرمی است.

جاوا اسکریپت سمت کلاینت

جاوا اسکریپت سمت کلاینت رایج‌ترین زبان برنامه‌نویسی دنیا محسوب می‌شود. این اسکریپت‌ها را می‌توان در یک سند HTML قرار داده یا ارجاعاتی به آن‌ها داد تا از سوی مرورگر تفسیر شوند.

این بدان معنی است که لزومی ندارد یک صفحه وب به صورت استاتیک باشد، بلکه می‌تواند شامل برنامه‌ای باشد که با کاربر تعامل پیدا می‌کند، مرورگر را کنترل کرده و به صورت دینامیکی محتوای HTML را ایجاد می‌کند.

مکانیسم سمت کلاینت جاوا اسکریپت مزیت‌های زیادی نسبت به اسکریپت‌های CGI سمت سرور سنتی ارائه می‌کند. برای نمونه می‌توانید از جاوا اسکریپت برای بررسی معتبر بودن ایمیل وارد شده از سوی کاربر استفاده کنید.

کد جاوا اسکریپت زمانی که کاربر فرم را تحویل می‌دهد، اجرا شده و تنها در صورتی که همه مدخل‌های ورودی معتبر باشند، آن را تحویل وب‌سرور می‌دهد. از جاوا اسکریپت می‌توان برای به دام انداختن رویدادهای آغازشده از سوی کاربر مانند کلیک کردن دکمه‌ها، ناوبری بین لینک‌ها و دیگر اقداماتی که کاربر به صورت صریح یا ضمنی در مرورگر انجام می‌دهد بهره گرفت.

مزایای جاوا اسکریپت

مزیت‌های استفاده از جاوا اسکریپت به شرح زیر هستند:

  • تعامل کمتر با سرور: با استفاده از جاوا اسکریپت، می‌توان ورودی‌‌های کاربر را پیش از ارسال فرم به سرور اعتبارسنجی کنید. به این ترتیب در ترافیک شبکه صرفه‌جویی می‌‌شود، یعنی بار کمتری به سرور وارد می‌شود.
  • بازخورد آنی به بازدیدکنندگان:  با استفاده از جاوا اسکریپت دیگر لازم نیست بازدیدکنندگان منتظر بمانند تا یک صفحه بارگذاری مجدد شود تا ببینند آیا وارد کردن چیزی را فراموش کرده‌اند یا نه.
  • افزایش تعامل‌پذیری: امکان ایجاد تعامل در اینترفیس‌ها پدید می‌آید. به این ترتیب وقتی کاربر ماوس را روی آن‌ها می‌برد و یا آن‌ها را از طریق کیبورد فعال می‌کند، واکنش نشان می‌دهند.
  • اینترفیس‌های غنی‌تر: می‌توان از جاوا اسکریپت برای گنجاندن آیتم‌ها به صورت اجزای کشیدنی و رها کردنی و اسلایدرها برای طراحی اینترفیس کاربری غنی استفاده کرد.

محدودیت‌های جاوا اسکریپت

جاوا اسکریپت را نمی‌توان یک زبان برنامه‌نویسی با امکانات کامل دانست. دلیل این مسئله آن است که این زبان برخی محدودیت‌های خاص خود را دارد:

  • جاوا اسکریپت سمت کلاینت مجاز به خواندن و نوشتن فایل‌ها نیست. این مسئله به دلیل امنیتی منع شده است.
  • از جاوا اسکریپت نمی‌توان برای اپلیکیشن‌های شبکه استفاده کرد، زیرا از چنین قابلیتی پشتیبانی نمی‌کند.
  • جاوا اسکریپت از قابلیت‌های چندنخی و یا چندپردازنده‌ای پشتیبانی نمی‌کند.

یک بار دیگر در این آموزش جاوا اسکریپت پروژه محور باید اشاره کنیم که جاوا اسکریپت یک زبان برنامه‌نویسی سبُکِ تفسیرشونده است که امکان ایجاد تعامل را در صفحه‌های استاتیک HTML فراهم می‌سازد.

ابزارهای توسعه جاوا اسکریپت

ابزارهای توسعه جاوا اسکریپت

یکی از مزیت‌های اصلی جاوا اسکریپت این است که به ابزارهای گران‌قیمت برای کدنویسی نیاز ندارد. شما می‌توانید کار خود را با یک ادیتور متنی ساده مانند Notepad آغاز کنید. از آنجا که این یک زبان تفسیرشونده در چارچوب یک مرورگر وب است، حتی نیازی به خرید یک کامپایلر هم ندارید.

ساختار جاوا اسکریپت

اجازه بدهید پیش از آنکه وارد مباحث اصلی آموزش جاوا اسکریپت پروژه محور بشویم، قدری ساختارها را یادآوری کنیم. زبان جاوا اسکریپت می‌تواند با استفاده از گزاره‌های جاوا اسکریپت که درون تگ‌های <script>... </script> در صفحه وب با ساختار HTML قرار می‌گیرند، ‌پیاده‌سازی شود. امکان قرار دادن تگ‌های <script> شامل کد جاوا اسکریپت در هر جایی درون صفحه وب وجود دارد، اما به طور معمول توصیه می‌شود که این تگ‌ها درون تگ <head> قرار گیرند.

تگ <script> به برنامه مرورگر اعلام می‌کند که همه متن بین این تگ‌ها را به عنوان یک اسکریپت تفسیر کند. یک ساختار ساده کد جاوا اسکریپت به صورت زیر است:

1<script ...>
2   JavaScript code
3</script>

این تگ اسکریپت دو خصوصیت مهم می‌گیرد:

  • Language – این خصوصیت زبانی که برای اسکریپت‌نویسی استفاده شده است را مشخص می‌سازد. به طور معمول این مقدار javascript است. با این که نسخه‌های جدید HTML (و XHTML و نسخه‌های قبلی آن) استفاده از این خصوصیت را کنار گذاشته‌اند.
  • Type – این خصوصیت برای تعیین زبان اسکریپت‌نویسی مورد استفاده مورد تأکید قرار گرفته است و مقدار آن باید text/javascript باشد.

بنابراین قطعه جاوا اسکریپت باید مانند زیر باشد:

1<script language = "javascript" type = "text/javascript">
2   JavaScript code
3</script>

نخستین کد جاوا اسکریپت

در این بخش از آموزش پروژه محور جاو اسکریپت برنامه کوچک Hello World که قبلاً نوشتیم را با هم بررسی می‌کنیم. ابتدا یک کامنت اختصاری HTML اضافه می‌کنیم که کد جاوا اسکریپت را در بر می‌گیرد. این کامنت با علامت <--//‎ پایان می‌یابد. در اینجا منظور از // این است که یک کامنت جاوا اسکریپت است و از این رو باید اضافه شود تا انتهای اسکریپت به عنوان یک کد از سوی مرورگر تفسیر نشود. سپس یک تابع به نام document.write می‌نویسیم که یک رشته را در سند HTML می‌نویسد. از این تابع برای نوشتن متن، HTML یا هر دو استفاده می‌کنیم. به کد زیر نگاه کنید:

1<html>
2   <body>   
3      <script language = "javascript" type = "text/javascript">
4         <!--
5            document.write("Hello World!")
6         //-->
7      </script>      
8   </body>
9</html>

این کد خروجی زیر را تولید می‌کند:

Hello World!

فاصله خالی و شکستن خطوط در جاوا اسکریپت

جاوا اسکریپت فاصله‌های خالی، علامت tab و newline را که در برنامه‌های جاوا اسکریپت ظاهر شوند، نادیده می‌گیرد و خطوط جدید را می‌توان آزادانه در برنامه استفاده کرد و کد را به صورت دلخواه دندانه‌گذاری و قالب‌بندی کرد. البته این کار باید به روشی منسجم و روشن انجام یابد تا خواندن و درک کد آسان شود.

نقطه‌ویرگول‌ها در جاوا اسکریپت اختیاری هستند

در ادامه از آموزش جاوا اسکریپت پروژه محور لازم است یادآور شویم، به طور معمول گزاره‌های ساده در جاوا اسکریپت به یک کاراکتر نقطه‌ویرگول (;) ختم می‌شوند که این وضعیت شبیه زبان‌های ++C ‎،C و جاوا است. با این حال جاوا اسکریپت اجازه حذف نقطه‌ویرگول را در صورت درج گزاره‌های مختلف در خطوط جدید فراهم می‌سازد. برای نمونه کد زیر را می‌توان بدون نقطه‌ویرگول نیز نوشت:

1<script language = "javascript" type = "text/javascript">
2   <!--
3      var1 = 10
4      var2 = 20
5   //-->
6</script>

اما زمانی که آن را در یک خط قالب‌بندی کنیم، باید از نقطه‌ویرگول استفاده کنیم:

1<script language = "javascript" type = "text/javascript">
2   <!--
3      var1 = 10; var2 = 20;
4   //-->
5</script>

نکته: استفاده از نقطه‌ویرگول یک رویه خوب برنامه‌نویسی محسوب می‌شود.

حساسیت جاوا اسکریپت به کوچکی/بزرگی حروف

جاوا اسکریپت یک زبان است که در آن کوچکی/بزرگی حروف مهم است. این بدان معنی است که کلیدواژه‌های این زبان، متغیرها، ‌نام توابع و دیگر شناسه‌ها باید همواره با یک نوع خاص از کوچکی/بزرگی حروف نوشته شوند.

بنابراین شناسه‌های Time و TIME از نظر جاوا اسکریپت معانی متفاوتی دارند.

نکته: در زمان نوشتن متغیرها و نام توابع در جاوا اسکریپت باید دقت ویژه‌ای به این مسئله مبذول شود.

کامنت ها در جاوا اسکریپت

جاوا اسکریپت از هر دو نوع کامنت به سبک زبان C و به سبک زبان ++C پشتیبانی می‌کند. بدین ترتیب:

  • هر متن بین // و انتهای یک خط به عنوان یک کامنت تلقی شده و از سوی جاوا اسکریپت نادیده گرفته می‌شود.
  • هر متن بین کاراکترهای /* و */ به عنوان یک کامنت نگریسته می‌شود. این نوع کامنت را می‌توان در چند خط نوشت.
  • جاوا اسکریپت همچنین کاراکتر باز کردن کامنت‌های HTML یعنی —!> را شناسایی می‌کند و با آن همچون علامت // مانند یک کامنت تک‌خطی رفتار می‌کند.
  • علامت بستن کامنت‌های HTML یعنی <-- از سوی جاوا اسکریپت شناسایی نمی‌شود و از این رو باید به صورت <---// نوشته شود.

مثالی از کامنت در جاوا اسکریپت

مثال زیر شیوه استفاده از کامنت در جاوا اسکریپت را نشان می‌دهد:

1<script language = "javascript" type = "text/javascript">
2   <!--
3      // This is a comment. It is similar to comments in C++
4   
5      /*
6      * This is a multi-line comment in JavaScript
7      * It is very similar to comments in C Programming
8      */
9   //-->
10</script>

منظور از جاوا اسکریپت ساده چیست؟

جاوا اسکریپت وانیلی

جاوا اسکریپت ساده یا جاوا اسکریپت وانیلی (Vanilla JavaScript) به زبان جاوا اسکریپت همچنان که هست و بدون هیچ گونه ابزار دیگر جهت تسهیل کدنویسی یا کارآمدتر ساختن آن گفته می‌شود. می‌توان از جاوا اسکریپت ساده برای ساخت پروژ‌ه‌های مختلف استفاده کرد، اما به مرور که با این زبان بیشتر آشنا می‌شوید، خواهید دید که ابزارهای بسیار مختلفی برای پیاده‌سازی آسان‌تر و استفاده کارآمدتر از جاوا اسکریپت معرفی ‌شده‌اند.

ابزارها و کتابخانه‌های جاوا اسکریپت

همچنان که احتمالاً می‌دانید، استفاده از جاوا اسکریپت صرف زمان زیادی از توسعه‌دهندگان می‌گیرد و همچنان که مجدداً شاید بدانید زمان طلا است. به همین جهت است که فریمورک‌ها و کتابخانه‌های جاوا اسکریپت خلق شده‌اند. ما در مطلب آموزش جاوا اسکریپت پروژه محور برخی پروژه‌های ساده جاوا اسکریپت را معرفی می‌کنیم که برای نوشتن آن‌ها به هیچ ابزار بیرونی نیاز دارید و صرفاً برای آشنا ساختن شما با روش‌‌های مقدماتی کدنویسی جاوا اسکریپت معرفی می‌شوند.

پروژ‌ه‌های عملی جاوا اسکریپت

اگر می‌خواهید یک توسعه‌دهنده وب شوید، باید کار خود را با تمرین کردن مهارت‌های جاوا اسکریپت به صورت عملی و در اولین فرصت ممکن آغاز کنید. زمانی که دانشی ابتدایی از این زبان یافتید، می‌توانید شروع به نوشتن پروژه‌های کوچک بکنید. برای آشنایی مقدماتی با زبان جاوا اسکریپت پیشنهاد می‌کنیم مجموعه مقالات زیر را مطالعه کنید:

همچنین دوره‌های آموزش ویدیویی که در این صفحه آمده‌اند، نیز می‌توانند به روند یادگیری و کسب مهارت شما در کدنویسی جاوا اسکریپت کمک کنند:

با این حال گاهی اوقات یافتن ایده‌های پروژه‌های جاوا اسکریپت که با مهارت‌های شما تطبیق داشته باشند و سرگرم‌کننده نیز باشند کار دشواری است. در این مقاله با عنوان آموزش جاوا اسکریپت پروژه محور به معرفی 15 پروژه سرگرم‌کننده می‌پردازیم که می‌توانید بی‌درنگ شروع به ساخت آن‌ها بکنید. همه این پروژه‌ها اوپن سورس هستند و می‌توانید از این کدها به هر نحو که تمایل دارید استفاده کنید.

یکی از بهترین روش‌های برای یادگیری جاوا اسکریپت یا هر زبان دیگر برنامه‌نویسی این است که زمانی را صرف ساخت تعداد زیادی پروژه بکنید. با این حال زمان ما محدود است و از این رو بهتر است روی پروژه‌هایی کار کنیم که ساخت آن‌ها آسان‌تر است. با این وجود اگر به مطالعه چیزهایی بپردازید که از قبل می‌دانید، در نهایت چیز جدیدی نخواهید آموخت. همچنین باید پروژه‌هایی برای آموزش انتخاب کنید که یادگیری آن‌ها زیاد دشوارتر از سطح کنونی مهارت‌تان نباشد.

بنابراین پیشنهاد می‌کنیم پروژه‌هایی را که در ادامه ارائه شده‌اند را ابتدا به طور اجمالی بررسی کنید و سپس آن‌ها را که با شرایط پیش‌گفته مطابقت دارند به ترتیب مورد مطالعه تفصیلی و تمرین عملی قرار دهید.

پروژه اول: ساخت و توسعه کرنومتر با جاوا اسکریپت ساده

راهنمای پروژه محور جاوا اسکریپت

ساخت یک کرنومتر با استفاده از جاوا اسکریپت کار بسیار آسانی است و حتی به عنوان یک مبتدی می‌تواند در زمان کمی این برنامه را بنویسید پس اولین پروژه ما در آموزش جاوا اسکریپت پروژه محور خواهد بود. این کرنومتر به سه دکمه نیاز دارد که کاربر از طریق آن‌ها با کرنومتر تعامل می‌یابد:

  1. شروع
  2. توقف
  3. ریست

فایل‌های این پروژه به صورت زیر هستند.

  • فایل HTML پروژه ساخت کرنومتر با جاوا اسکریپت
1<div class="wrapper">
2<h1>Stopwatch</h1>
3<h2>Vanilla JavaScript Stopwatch</h2>
4<p><span id="seconds">00</span>:<span id="tens">00</span></p>
5<button id="button-start">Start</button>
6<button id="button-stop">Stop</button>
7<button id="button-reset">Reset</button>
8</div> 
  • فایل CSS پروژه توسعه کرنومتر با جاوا اسکریپت
1/* Variabes */  
2$orange: #ffa600;
3$grey:#f3f3f3;
4$white: #fff;
5$base-color:$orange ;
6
7
8/* Mixin's */  
9@mixin transition {
10-webkit-transition: all 0.5s ease-in-out;
11-moz-transition: all 0.5s ease-in-out;
12transition: all 0.5s ease-in-out;
13}
14@mixin corners ($radius) {
15-moz-border-radius: $radius;
16-webkit-border-radius: $radius;
17border-radius: $radius; 
18-khtml-border-radius: $radius; 
19}
20
21body {
22background:$base-color;
23font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
24height:100%;
25}
26
27.wrapper {
28width: 800px;
29margin: 30px auto;
30color:$white;
31text-align:center;
32}
33
34h1, h2, h3 {
35  font-family: 'Roboto', sans-serif;
36  font-weight: 100;
37  font-size: 2.6em;
38  text-transform: uppercase;
39}
40
41#seconds, #tens{
42  font-size:2em;
43}
44
45button{
46@include corners (5px);
47background:$base-color;
48color:$white;
49border: solid 1px $white;
50text-decoration:none;
51cursor:pointer;
52font-size:1.2em;
53padding:18px 10px;
54width:180px;
55margin: 10px;
56 outline: none;
57  &:hover{
58	@include transition;
59	background:$white;
60	border: solid 1px $white;
61	color:$base-color;
62	}
63}
64
65
66
67
68
69
70
  • فایل جاوا اسکریپت پروژه طراحی کرنومتر با جاوا اسکریپت
1window.onload = function () {
2  
3  var seconds = 00; 
4  var tens = 00; 
5  var appendTens = document.getElementById("tens")
6  var appendSeconds = document.getElementById("seconds")
7  var buttonStart = document.getElementById('button-start');
8  var buttonStop = document.getElementById('button-stop');
9  var buttonReset = document.getElementById('button-reset');
10  var Interval ;
11
12  buttonStart.onclick = function() {
13    
14     clearInterval(Interval);
15     Interval = setInterval(startTimer, 10);
16  }
17  
18    buttonStop.onclick = function() {
19       clearInterval(Interval);
20  }
21  
22
23  buttonReset.onclick = function() {
24     clearInterval(Interval);
25    tens = "00";
26  	seconds = "00";
27    appendTens.innerHTML = tens;
28  	appendSeconds.innerHTML = seconds;
29  }
30  
31   
32  
33  function startTimer () {
34    tens++; 
35    
36    if(tens < 9){
37      appendTens.innerHTML = "0" + tens;
38    }
39    
40    if (tens > 9){
41      appendTens.innerHTML = tens;
42      
43    } 
44    
45    if (tens > 99) {
46      console.log("seconds");
47      seconds++;
48      appendSeconds.innerHTML = "0" + seconds;
49      tens = 0;
50      appendTens.innerHTML = "0" + 0;
51    }
52    
53    if (seconds > 9){
54      appendSeconds.innerHTML = seconds;
55    }
56  
57  }
58  
59
60}

برای مشاهده نسخه عملیاتی این پروژه می‌توانید به این لینک (+) رجوع کنید.

پروژه دوم: کدنویسی ساعت با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

ساخت یک ساعت دیجیتال با جاوا اسکریپت کار نسبتاً آسانی است، پس پروژه دوم ما در آموزش جاوا اسکریپت پروژه محور همین موضوع خواهد بود. این یک پروژه نسبتاً کوچک است که با نوشتن آن می‌توانید با متغیرها و حلقه‌های ساده IF آشنا شوید. در این مورد نیز با استفاده از CSS طراحی خود را سفارشی‌سازی می‌کنیم تا ظاهر ساعت دیجیتالمان بهبود پیدا کند.

  • فایل HTML پروژه توسعه ساعت با جاوا اسکریپت
1<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
2
  • فایل CSS پروژه ساخت ساعت با جاوا اسکریپت
1body {
2    background: black;
3}
4
5.clock {
6    position: absolute;
7    top: 50%;
8    left: 50%;
9    transform: translateX(-50%) translateY(-50%);
10    color: #17D4FE;
11    font-size: 60px;
12    font-family: Orbitron;
13    letter-spacing: 7px;
14   
15
16
17}
  • فایل جاوا اسکریپت پروژه طراحی ساعت با جاوا اسکریپت
1function showTime(){
2    var date = new Date();
3    var h = date.getHours(); // 0 - 23
4    var m = date.getMinutes(); // 0 - 59
5    var s = date.getSeconds(); // 0 - 59
6    var session = "AM";
7    
8    if(h == 0){
9        h = 12;
10    }
11    
12    if(h > 12){
13        h = h - 12;
14        session = "PM";
15    }
16    
17    h = (h < 10) ? "0" + h : h;
18    m = (m < 10) ? "0" + m : m;
19    s = (s < 10) ? "0" + s : s;
20    
21    var time = h + ":" + m + ":" + s + " " + session;
22    document.getElementById("MyClockDisplay").innerText = time;
23    document.getElementById("MyClockDisplay").textContent = time;
24    
25    setTimeout(showTime, 1000);
26    
27}
28
29showTime();

برای مشاهده نسخه عملیاتی این مورد از آموزش جاوا اسکریپت پروژه محور به این صفحه (+)‌ مراجعه کنید.

پروژه سوم: ساخت ماشین حساب با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

کدنویسی یک ماشین حساب قدیمی، رویه‌ای جالب برای بهبود مهارت‌های جاوا اسکریپت محسوب می‌شود پس سومین پروژه از آموزش جاوا اسکریپت پروژه محور را روی این موضوع متمرکز می‌کنیم. در این پروژه ابتدا اقدام به ایجاد یک اینترفیس تمیز و زیبا با استفاده از HTML و CSS و سپس قابلیت‌های مختلف را با استفاده از جاوا اسکریپت به آن اضافه می‌کنیم. کار خود را با چند عملگر و دکمه ساده برای جمع، تفریق، ‌ضرب و تقسیم آغاز می‌کنیم.

  • فایل HTML ساخت ماشین حساب با جاوا اسکریپت
1<div class="calculator">
2  <div class="input" id="input"></div>
3  <div class="buttons">
4    <div class="operators">
5      <div>+</div>
6      <div>-</div>
7      <div>×</div>
8      <div>÷</div>
9    </div>
10    <div class="leftPanel">
11      <div class="numbers">
12        <div>7</div>
13        <div>8</div>
14        <div>9</div>
15      </div>
16      <div class="numbers">
17        <div>4</div>
18        <div>5</div>
19        <div>6</div>
20      </div>
21      <div class="numbers">
22        <div>1</div>
23        <div>2</div>
24        <div>3</div>
25      </div>
26      <div class="numbers">
27        <div>0</div>
28        <div>.</div>
29        <div id="clear">C</div>
30      </div>
31    </div>
32    <div class="equal" id="result">=</div>
33  </div>
34</div>
  • فایل CSS پروژه کدنویسی ماشین حساب با جاوا اسکریپت
1body {
2  width: 500px;
3  margin: 4% auto;
4  font-family: 'Source Sans Pro', sans-serif;
5  letter-spacing: 5px;
6  font-size: 1.8rem;
7  -moz-user-select: none;
8  -webkit-user-select: none;
9  -ms-user-select: none;
10}
11
12.calculator {
13  padding: 20px;
14  -webkit-box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
15  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
16  border-radius: 1px;
17}
18
19.input {
20  border: 1px solid #ddd;
21  border-radius: 1px;
22  height: 60px;
23  padding-right: 15px;
24  padding-top: 10px;
25  text-align: right;
26  margin-right: 6px;
27  font-size: 2.5rem;
28  overflow-x: auto;
29  transition: all .2s ease-in-out;
30}
31
32.input:hover {
33  border: 1px solid #bbb;
34  -webkit-box-shadow: inset 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
35  box-shadow: inset 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
36}
37
38.buttons {}
39
40.operators {}
41
42.operators div {
43  display: inline-block;
44  border: 1px solid #bbb;
45  border-radius: 1px;
46  width: 80px;
47  text-align: center;
48  padding: 10px;
49  margin: 20px 4px 10px 0;
50  cursor: pointer;
51  background-color: #ddd;
52  transition: border-color .2s ease-in-out, background-color .2s, box-shadow .2s;
53}
54
55.operators div:hover {
56  background-color: #ddd;
57  -webkit-box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
58  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
59  border-color: #aaa;
60}
61
62.operators div:active {
63  font-weight: bold;
64}
65
66.leftPanel {
67  display: inline-block;
68}
69
70.numbers div {
71  display: inline-block;
72  border: 1px solid #ddd;
73  border-radius: 1px;
74  width: 80px;
75  text-align: center;
76  padding: 10px;
77  margin: 10px 4px 10px 0;
78  cursor: pointer;
79  background-color: #f9f9f9;
80  transition: border-color .2s ease-in-out, background-color .2s, box-shadow .2s;
81}
82
83.numbers div:hover {
84  background-color: #f1f1f1;
85  -webkit-box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
86  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
87  border-color: #bbb;
88}
89
90.numbers div:active {
91  font-weight: bold;
92}
93
94div.equal {
95  display: inline-block;
96  border: 1px solid #3079ED;
97  border-radius: 1px;
98  width: 17%;
99  text-align: center;
100  padding: 127px 10px;
101  margin: 10px 6px 10px 0;
102  vertical-align: top;
103  cursor: pointer;
104  color: #FFF;
105  background-color: #4d90fe;
106  transition: all .2s ease-in-out;
107}
108
109div.equal:hover {
110  background-color: #307CF9;
111  -webkit-box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
112  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
113  border-color: #1857BB;
114}
115
116div.equal:active {
117  font-weight: bold;
118}
  • فایل جاوا اسکریپت پروژه توسعه ماشین حساب با جاوا اسکریپت
1"use strict";
2
3var input = document.getElementById('input'), // input/output button
4  number = document.querySelectorAll('.numbers div'), // number buttons
5  operator = document.querySelectorAll('.operators div'), // operator buttons
6  result = document.getElementById('result'), // equal button
7  clear = document.getElementById('clear'), // clear button
8  resultDisplayed = false; // flag to keep an eye on what output is displayed
9
10// adding click handlers to number buttons
11for (var i = 0; i < number.length; i++) {
12  number[i].addEventListener("click", function(e) {
13
14    // storing current input string and its last character in variables - used later
15    var currentString = input.innerHTML;
16    var lastChar = currentString[currentString.length - 1];
17
18    // if result is not diplayed, just keep adding
19    if (resultDisplayed === false) {
20      input.innerHTML += e.target.innerHTML;
21    } else if (resultDisplayed === true && lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷") {
22      // if result is currently displayed and user pressed an operator
23      // we need to keep on adding to the string for next operation
24      resultDisplayed = false;
25      input.innerHTML += e.target.innerHTML;
26    } else {
27      // if result is currently displayed and user pressed a number
28      // we need clear the input string and add the new input to start the new opration
29      resultDisplayed = false;
30      input.innerHTML = "";
31      input.innerHTML += e.target.innerHTML;
32    }
33
34  });
35}
36
37// adding click handlers to number buttons
38for (var i = 0; i < operator.length; i++) {
39  operator[i].addEventListener("click", function(e) {
40
41    // storing current input string and its last character in variables - used later
42    var currentString = input.innerHTML;
43    var lastChar = currentString[currentString.length - 1];
44
45    // if last character entered is an operator, replace it with the currently pressed one
46    if (lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷") {
47      var newString = currentString.substring(0, currentString.length - 1) + e.target.innerHTML;
48      input.innerHTML = newString;
49    } else if (currentString.length == 0) {
50      // if first key pressed is an opearator, don't do anything
51      console.log("enter a number first");
52    } else {
53      // else just add the operator pressed to the input
54      input.innerHTML += e.target.innerHTML;
55    }
56
57  });
58}
59
60// on click of 'equal' button
61result.addEventListener("click", function() {
62
63  // this is the string that we will be processing eg. -10+26+33-56*34/23
64  var inputString = input.innerHTML;
65
66  // forming an array of numbers. eg for above string it will be: numbers = ["10", "26", "33", "56", "34", "23"]
67  var numbers = inputString.split(/\+|\-||/g);
68
69  // forming an array of operators. for above string it will be: operators = ["+", "+", "-", "*", "/"]
70  // first we replace all the numbers and dot with empty string and then split
71  var operators = inputString.replace(/[0-9]|\./g, "").split("");
72
73  console.log(inputString);
74  console.log(operators);
75  console.log(numbers);
76  console.log("----------------------------");
77
78  // now we are looping through the array and doing one operation at a time.
79  // first divide, then multiply, then subtraction and then addition
80  // as we move we are alterning the original numbers and operators array
81  // the final element remaining in the array will be the output
82
83  var divide = operators.indexOf("÷");
84  while (divide != -1) {
85    numbers.splice(divide, 2, numbers[divide] / numbers[divide + 1]);
86    operators.splice(divide, 1);
87    divide = operators.indexOf("÷");
88  }
89
90  var multiply = operators.indexOf("×");
91  while (multiply != -1) {
92    numbers.splice(multiply, 2, numbers[multiply] * numbers[multiply + 1]);
93    operators.splice(multiply, 1);
94    multiply = operators.indexOf("×");
95  }
96
97  var subtract = operators.indexOf("-");
98  while (subtract != -1) {
99    numbers.splice(subtract, 2, numbers[subtract] - numbers[subtract + 1]);
100    operators.splice(subtract, 1);
101    subtract = operators.indexOf("-");
102  }
103
104  var add = operators.indexOf("+");
105  while (add != -1) {
106    // using parseFloat is necessary, otherwise it will result in string concatenation :)
107    numbers.splice(add, 2, parseFloat(numbers[add]) + parseFloat(numbers[add + 1]));
108    operators.splice(add, 1);
109    add = operators.indexOf("+");
110  }
111
112  input.innerHTML = numbers[0]; // displaying the output
113
114  resultDisplayed = true; // turning flag if result is displayed
115});
116
117// clearing the input on press of clear
118clear.addEventListener("click", function() {
119  input.innerHTML = "";
120})

برای مشاهده نسخه نهایی خروجی این بخش از آموزش جاوا اسکریپت پروژه محور به این صفحه (+) مراجعه کنید.

پروژه چهارم: ساخت کیت درام با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

اگر می‌خواهید یک پروژه جاوا اسکریپت ایجاد کنید که سرگرمی زیادی داشته باشد، اما شما را در مسیر یادگیری این زبان نیز یاری کند، از مثال چهارم آموزش جاوا اسکریپت پروژه محور لذت زیادی خواهید برد. همه کسانی که روی این پروژه کار کرده‌اند، آن را پروژه جذابی توصیف می‌کنند، زیرا ساخت یک کیت درام موسیقی موجب سرگرمی و لذت زیادی می‌شود.

  • فایل HTML ساخت کیت دارم با جاوا اسکریپت
1<main>
2  <section class="main-wrapper">
3    <div class="key-map-wrapper">
4      <h2>Key Mapping</h2>
5      <ul class="key-map-list">
6        <li>
7          <kbd class="key-code">E</kbd>
8          <span class="key-sound">Crash</span>
9        </li>
10        <li>
11          <kbd class="key-code">R</kbd>
12          <span class="key-sound">Ride</span>
13        </li>
14        <li>
15          <kbd class="key-code">F</kbd>
16          <span class="key-sound">Floor tom</span>
17        </li>
18        <li>
19          <kbd class="key-code">G</kbd>
20          <span class="key-sound">Mid tom</span>
21        </li>
22        <li>
23          <kbd class="key-code">H</kbd>
24          <span class="key-sound">High tom</span>
25        </li>
26        <li>
27          <kbd class="key-code">V</kbd>
28          <kbd class="key-code">B</kbd>
29          <span class="key-sound">Kick</span>
30        </li>
31        <li>
32          <kbd class="key-code">J</kbd>
33          <span class="key-sound">Snare</span>
34        </li>
35        <li>
36          <kbd class="key-code">I</kbd>
37          <span class="key-sound">Hi-Hat Open</span>
38        </li>
39        <li>
40          <kbd class="key-code">K</kbd>
41          <span class="key-sound">Hi-Hat Closed</span>
42        </li>
43      </ul>
44    </div>
45    <h1 class="main-title">JavaScript Drum Kit</h1>
46    <div class="drum-kit-wrapper">
47      <img id="crash-ride" class="crash-cymbal" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/img/crash.png" alt="Crash cymbal">
48      <img id="hihat-top" class="hihat-top-cymbal" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/img/hihat-top.png" alt="Hi Hat cymbal">
49      <div data-key="74" class="key snare">
50        <kbd>J</kbd>
51      </div>
52      <div data-key="66" class="key kick">
53        <kbd>B</kbd>
54      </div>
55      <div data-key="86" class="key kick2">
56        <kbd>V</kbd>
57      </div>
58      <div data-key="72" class="key tom-high">
59        <kbd>H</kbd>
60      </div>
61      <div data-key="71" class="key tom-mid">
62        <kbd>G</kbd>
63      </div>
64      <div data-key="70" class="key tom-low">
65        <kbd>F</kbd>
66      </div>
67      <div data-key="69" class="key crash">
68        <kbd>E</kbd>
69      </div>
70      <div data-key="82" class="key ride">
71        <kbd>R</kbd>
72      </div>
73      <div data-key="73" class="key hihat-open">
74        <kbd>I</kbd>
75      </div>
76      <div data-key="75" class="key hihat-close">
77        <kbd>K</kbd>
78      </div>
79      <img class="drum-kit" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/img/drum-kit.png" alt="Drum Kit" />
80    </div>
81  </section>
82</main>
83<audio data-key="74" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/snare.wav"></audio>
84<audio data-key="66" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/kick.wav"></audio>
85<audio data-key="86" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/kick.wav"></audio>
86<audio data-key="72" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/tom-high.wav"></audio>
87<audio data-key="71" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/tom-mid.wav"></audio>
88<audio data-key="70" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/tom-low.wav"></audio>
89<audio data-key="69" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/crash.wav"></audio>
90<audio data-key="82" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/ride.wav"></audio>
91<audio data-key="73" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/hihat-open.wav"></audio>
92<audio data-key="75" src="https://raw.githubusercontent.com/ArunMichaelDsouza/javascript-30-course/master/src/01-javascript-drum-kit/sounds/hihat-close.wav"></audio>
  • فایل CSS توسعه کیت دارم با جاوا اسکریپت
1@import url(https://fonts.googleapis.com/css?family=Handlee|Pacifico);
2
3html,
4body {
5	padding: 0;
6	margin: 0;
7	background-color: #fff;
8}
9
10.main-wrapper {
11	margin: 30px auto 0;
12	width: 1080px;
13	text-align: center;
14}
15
16.main-title {
17	font-family: 'Pacifico', cursive;
18	text-align: center;
19	font-size: 3.2em;
20	color: #cb2026;
21	text-shadow: 1px 1px 1px #5a0b0d;
22}
23
24.drum-kit-wrapper {
25	position: relative;
26	width: 600px;
27	margin: -100px auto 0;
28}
29
30.drum-kit {
31	width: 100%;
32	height: 520px;
33	position: relative;
34}
35
36.crash-cymbal {
37	position: absolute;
38	top: 114px;
39    left: 80px;
40    transform: rotate(-7.2deg) scale(1.5);
41    transition: all ease-in-out .042s;
42}
43
44.hihat-top-cymbal {
45	position: absolute;
46    top: 166px;
47    right: 71px;
48    transform: scale(1.35);
49    z-index: 0;
50    transition: all ease-in-out .042s;
51}
52
53.key {
54	display: inline-block;
55	transition: all ease-in-out .042s;
56	position: absolute;
57	background: #eaeaea;
58    font-size: 1.5em;
59    height: 32px;
60    width: 32px;
61    text-align: center;
62    border-radius: 4px;
63    border: 3px solid #aaa;
64    color: #444;
65    box-shadow: 1px 1px 1px rgba(0,0,0,.65);
66    z-index: 2;
67}
68
69.key.kick {
70	top: 355px;
71    right: 250px;
72}
73
74.key.kick2 {
75    top: 355px;
76    right: 308px;
77}
78
79.key.snare {
80	right: 145px;
81    top: 280px;
82}
83
84.key.tom-high {
85	right: 227px;
86    top: 240px;
87}
88
89.key.tom-mid {
90	left: 222px;
91    top: 220px;
92}
93
94.key.tom-low {
95	top: 320px;
96    left: 133px;
97}
98
99.key.crash {
100	top: 80px;
101    left: 75px;
102}
103
104.key.ride {
105	left: 165px;
106    top: 87px;
107}
108
109.key.hihat-open {
110	right: 165px;
111    top: 144px;
112}
113
114.key.hihat-close {
115	right: 60px;
116    top: 150px;
117}
118
119.playing {
120	transform: scale(1.12);
121}
122
123.key-map-wrapper {
124	position: absolute;
125    right: 0;
126    top: 0;
127    height: 700px;
128    background: #111;
129    width: 250px;
130    z-index: 3;
131}
132
133.key-map-wrapper > h2 {
134	color: #fff;
135	font-family: 'Handlee', cursive;
136	margin-bottom: 35px;
137	border-bottom: 1px solid #fff;
138    padding-bottom: 20px;
139}
140
141.key-map-list {
142	list-style: none;
143	color: #fff;
144	text-align: left;
145}
146
147.key-map-list > li {
148	margin-bottom: 25px;
149}
150
151.key-code {
152	color: #444;
153    background-color: #eaeaea;
154    font-size: 1.25em;
155    padding: 5px 10px;
156    border-radius: 4px;
157    border: 3px solid #aaa;
158}
159
160.key-sound {
161	font-size: 1.2em;
162	margin-left: 10px;
163	font-family: 'Handlee', cursive;
164	vertical-align: middle;
165}
  • فایل جاوا اسکریپت پروژه کدنویسی کیت درام با جاوا اسکریپت
1// JavaScript Drum Kit App
2
3{
4	const playingClass = 'playing',
5		crashRide = document.getElementById('crash-ride'),
6		hiHatTop = document.getElementById('hihat-top');
7
8	const animateCrashOrRide = () => {
9		crashRide.style.transform = 'rotate(0deg) scale(1.5)';
10	};
11
12	const animateHiHatClosed = () => {
13		hiHatTop.style.top = '171px';
14	};
15
16	const playSound = e => {
17		const keyCode = e.keyCode,
18			keyElement = document.querySelector(`div[data-key="${keyCode}"]`);
19
20		if(!keyElement) return;
21
22		const audioElement = document.querySelector(`audio[data-key="${keyCode}"]`);
23		audioElement.currentTime = 0;
24		audioElement.play();
25
26		switch(keyCode) {
27			case 69:
28			case 82:
29				animateCrashOrRide();
30				break;
31			case 75:
32				animateHiHatClosed();
33				break;
34		}
35
36		keyElement.classList.add(playingClass);
37	};
38
39	const removeCrashRideTransition = e => {
40		if(e.propertyName !== 'transform') return;
41
42		e.target.style.transform = 'rotate(-7.2deg) scale(1.5)';
43	};
44
45	const removeHiHatTopTransition = e => {
46		if(e.propertyName !== 'top') return;
47
48		e.target.style.top = '166px';
49	};	
50
51	const removeKeyTransition = e => {
52		if(e.propertyName !== 'transform') return;
53
54		e.target.classList.remove(playingClass)
55	};
56
57	const drumKeys = Array.from(document.querySelectorAll('.key'));
58
59	drumKeys.forEach(key => {
60		key.addEventListener('transitionend', removeKeyTransition);
61	});
62
63	crashRide.addEventListener('transitionend', removeCrashRideTransition);
64	hiHatTop.addEventListener('transitionend', removeHiHatTopTransition);
65
66	window.addEventListener('keydown', playSound);
67}

برای مشاهده نسخه نهایی این پروژه به این صفحه (+) مراجعه کنید.

پروژه پنجم: کدنویسی بازی حدس زدن رنگ با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

کدنویسی یک بازی حدس زدن رنگ با جاوا اسکریپت کار بسیار آسانی محسوب می‌شود پس اجازه بدهید پنجمین پروژه از آموزش جاوا اسکریپت پروژه محور را به این موضوع اختصاص دهیم. در این پروژه، یک بازی می‌سازیم که در آن بازیکن یک مقدار منفرد RGB برای یک رنگ می‌بیند. این بازیکن باید روی رنگی که با مقدار RGB نمایش یافته منطبق است کلیک کند.

امکان افزودن قابلیت‌های بیشتر به این پروژه جهت دشوارتر ساختن آن وجود دارد. برای نمونه می‌توانید تعداد حدس‌ها را محدود سازید یا به بازیکن‌ها «جان» (Live) بدهید تا در صورت اشتباه‌های مکرر، جان‌های خود را از دست بدهند.

  • فایل HTML توسعه بازی حدس زدن رنگ با جاوا اسکریپت
1<html>
2<head>
3	<title>Color Game</title>
4	<link rel="stylesheet" type="text/css" href="style.css">
5	<link href='https://fonts.googleapis.com/css?family=Raleway:300' rel='stylesheet' type='text/css'>	
6
7</head>
8<body>
9	<h1>The Great <span id="color-display">RGB</span> Guessing Game</h1>
10	<div id ="stripe">
11		<button id="reset">New Colors</button>
12		<span id="message"></span>
13		<button class="mode">Easy</button>
14		<button class="mode selected">Hard</button>
15	</div>
16	<div id="container">
17		<div class="square"></div>
18		<div class="square"></div>
19		<div class="square"></div>
20		<div class="square"></div>
21		<div class="square"></div>
22		<div class="square"></div>
23	</div>
24
25	<script type="text/javascript" src="script.js"></script>
26<!-- 	<script type="text/javascript" src="colorGame.js"></script>
27 --></body>
28</html>
  • فایل CSS ساخت بازی حدس زدن رنگ با جاوا اسکریپت
1body {
2	background-color: #232323;
3	font-family: "Raleway", Sans-serif;
4	font-size: 62.5%; /*1 em = 10px */
5	margin: 0;
6}
7
8#container {
9	max-width: 600px;
10	margin: 0 auto;
11	padding-top: 20px;
12
13}
14.square {
15	width: 30%;
16	background-color: purple;
17	padding-bottom: 30%;
18	float: left;
19	margin: 1.66%;
20	transition: background .5s;
21	-webkit-transition: background .5s;
22	-moz-transition: background .5s;
23	o-transition: background .5s;
24} 
25
26h1 {
27	color: white;
28	background-color: #2C8E99;
29	font-size: 3.5em;
30	text-align: center;
31	text-transform: uppercase;
32	margin: 0;
33	padding: 10px 0;
34}
35
36#color-display {
37	display: block;
38	font-size: 2em;
39}
40
41#stripe {
42	background: white;
43	height: 30px;
44	text-align: center;
45	color: black;
46}
47
48#message {
49	text-transform: uppercase;
50	color: #2C8E99;
51	font-size: 1.5em;
52	display: inline-block;
53	width: 20%;
54}
55
56button {
57	outline: none;
58	color: #2C8E99;
59	font-family: "Raleway", Sans-serif;
60	text-transform: uppercase;
61	font-size: 1.5em;
62	background-color: white;
63	height: 100%;
64	letter-spacing: 1px;
65	transition: all 0.3s;
66	-webkit-transition: all 0.3s;
67	-moz-transition: all 0.3s;
68	o-transition: all 0.3s;
69}
70
71button:hover {
72	background-color: #2C8E99;
73	color: white;
74}
75
76.selected {
77	background-color: #2C8E99;
78	color: white;
79}
80
81.square {
82	border-radius: 20%;
83}
84
85* {
86	border: 0px solid red;
87}
88
89
90
  • فایل جاوا اسکریپت پروژه کدنویسی بازی حدس زدن رنگ با جاوا اسکریپت
1var numSquares = 6;
2var colors = [];
3var pickedColor;
4
5var squares = document.querySelectorAll(".square");
6var colorDisplay = document.querySelector("#color-display");
7var messageDisplay = document.querySelector("#message");
8var h1 = document.querySelector("h1");
9var resetButton = document.querySelector("#reset");
10var modeButtons = document.querySelectorAll(".mode");
11var easyButton = document.querySelector(".mode");
12
13init();
14
15function init() {
16	colorDisplay.textContent = pickedColor;
17	setupSquares();
18	setupMode();
19	reset();
20}
21
22resetButton.addEventListener("click", function() {
23	reset();
24});
25
26function setupSquares() {
27	for (var i = 0; i < squares.length; i++) {
28		squares[i].style.backgroundColor = colors[i];
29		squares[i].addEventListener("click", function() {
30			var clickedColor = this.style.backgroundColor;
31			if(clickedColor === pickedColor) {
32				messageDisplay.textContent = "Correct";
33				resetButton.textContent = "Play Again";
34				changeColors(pickedColor);
35			}
36			else {
37				this.style.backgroundColor = "#232323";
38				messageDisplay.textContent = "try again";
39			}
40		});
41	}
42}
43
44function setupMode() {
45	for(var i = 0; i < modeButtons.length; i++) {
46		modeButtons[i].addEventListener("click", function() {
47			for (var i = 0; i < modeButtons.length; i++) {
48				modeButtons[i].classList.remove("selected");
49			}
50			this.classList.add("selected");
51			if (this.textContent === "Easy") {
52				numSquares = 3;
53			}
54			else {
55				numSquares = 6;
56			}
57			reset();
58		});
59	}
60}
61
62function reset() {
63	colors = genRandomColors(numSquares);
64	pickedColor = chooseColor();
65	colorDisplay.textContent = pickedColor;
66	h1.style.backgroundColor = "#2C8E99";
67	resetButton.textContent = "New Colors";
68	messageDisplay.textContent = "";
69	for (var i = 0; i < squares.length; i++) {
70		if(colors[i]) { 
71			squares[i].style.display = "block";
72			squares[i].style.backgroundColor = colors[i];
73		}
74		else {
75			squares[i].style.display = "none";
76		}
77	}
78}
79
80function changeColors(color) {
81	for(var i = 0; i < squares.length; i++) {
82		squares[i].style.backgroundColor = color;
83		h1.style.backgroundColor = color;
84	}
85}
86
87function chooseColor() {
88	var random = Math.floor(Math.random() * colors.length);
89	return colors[random];
90}
91
92function genRandomColors(num) {
93	var arr = [];
94	for (var i = 0; i < num; i++) {
95		arr.push(makeColor());
96	}
97	return arr;
98}
99
100function makeColor() {
101	var r = Math.floor(Math.random() * 256);
102	var g = Math.floor(Math.random() * 256);
103	var b = Math.floor(Math.random() * 256);
104	return "rgb(" + r + ", " + g + ", " + b + ")"; 
105}
106
107
108
109

برای مشاهده نسخه عملیاتی این بازی به این صفحه (+) مراجعه کنید.

پروژه ششم: ساخت بازی HANGMAN با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

ساخت بازی HANGMAN یکی از بهترین ایده‌ها برای تمرین توسط افراد مبتدی است که نیازمند کمی چالش هستند، از همین روش ششمین مورد از آموزش جاوا اسکریپت پروژه محور را به آن اختصاص داده‌ایم. این بازی در مورد حدس زدن یک کلمه تصادفی به صورت حرف به حرف است که در صورت پایان یافتن تعداد حدس‌های کاربر، بازی تمام می‌شود. با این که روند بازی ممکن است ساده به نظر بیاید، اما باید چند نکته مهم را در کد جاوا اسکریپت خود در نظر بگیرید:

  • حد بیشینه‌ای برای تعداد حدس‌ها در نظر بگیرید.
  • تعداد باقیمانده حدس‌های بازیکن را نمایش دهید.
  • یک رابط کاربری برای وارد کردن حدس‌ها در اختیار بازیکن قرار دهید.

نوشتن این پروژه جاوا اسکریپت احتمالاً به زمان بیشتری نیاز دارد و باید در مورد گزینه تصادفی، متغیرها، مقادیر بولی، ورودی‌ها، خروجی‌ها، رشته‌ها طول متغیرها و موارد دیگر بیاندیشید.

  • فایل HTML ساخت بازی HANGMAN با جاوا اسکریپت
1<div class="wrapper">
2   <h1>Hangman</h1>
3    <h2>Vanilla JavaScript Hangman Game</h2>
4    <p>Use the alphabet below to guess the word, or click hint to get a clue. </p>
5</div>
6<div class="wrapper">
7    <div id="buttons">
8    </div>  
9    <p id="catagoryName"></p>
10    <div id="hold">
11    </div>
12    <p id="mylives"></p>
13    <p id="clue">Clue -</p>  
14     <canvas id="stickman">This Text will show if the Browser does NOT support HTML5 Canvas tag</canvas>
15    <div class="container">
16      <button id="hint">Hint</button>
17      <button id="reset">Play again</button>
18    </div>
19</div>
20
21
22
  • فایل CSS کدنویسی بازی HANGMAN با جاوا اسکریپت
1/* Variabes */  
2$orange: #ffa600;
3$green: #c1d72e;
4$blue: #82d2e5;
5$grey:#f3f3f3;
6$white: #fff;
7$base-color:$green ;
8
9/* Mixin's */ 
10
11@mixin transition {
12  -webkit-transition: all 0.5s ease-in-out;
13  -moz-transition: all 0.5s ease-in-out;
14  transition: all 0.5s ease-in-out;
15}
16
17@mixin clear {
18  &:after {
19      content: "";
20      display: table;
21      clear: both;
22    }
23}
24
25 @mixin box-size {
26  -webkit-box-sizing: border-box;
27  -moz-box-sizing: border-box;
28  box-sizing: border-box;
29}
30
31 @mixin transition {
32  -webkit-transition: all 0.3s ease-in-out;
33  -moz-transition: all 0.3s ease-in-out;
34  transition: all 0.3s ease-in-out;
35}
36
37@mixin fade {
38  -moz-transition: all 1s ease-in;
39  -moz-transition:all 0.3s ease-in-out;
40  -webkit-transition:all 0.3s ease-in-out;
41}
42
43@mixin opacity {
44  opacity:0.4;
45  filter:alpha(opacity=40); 
46  @include fade;
47}
48
49@mixin corners ($radius) {
50  -moz-border-radius: $radius;
51  -webkit-border-radius: $radius;
52  border-radius: $radius; 
53  -khtml-border-radius: $radius; 
54}
55
56body {
57  background:$base-color;
58  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
59  color:$white;
60  height:100%;
61  text-align:center;
62  font-size:18px;
63}
64
65.wrappper{
66  @include clear;
67  width:100%;
68  margin:0 auto;
69}
70
71
72canvas{
73  color:$white;
74  border: $white dashed 2px;
75  padding:15px;
76}
77
78h1, h2, h3 {
79	font-family: 'Roboto', sans-serif;
80	font-weight: 100;
81	text-transform: uppercase;
82   margin:5px 0;
83}
84
85h1 {
86	font-size: 2.6em;
87}
88
89h2 {
90	font-size: 1.6em;
91}
92
93p{
94  font-size: 1.6em;
95}
96
97#alphabet {
98  @include clear;
99  margin:15px auto;
100  padding:0;
101  max-width:900px;
102}
103
104#alphabet li {
105  float:left;
106  margin: 0 10px 10px 0;
107  list-style:none;
108  width:35px;
109  height:30px;
110  padding-top:10px;
111  background:$white;
112  color:$base-color;
113  cursor:pointer;
114  @include corners(5px);
115  border: solid 1px $white;
116    
117    &:hover{
118      background:$base-color;
119      border: solid 1px $white;
120      color:$white;
121    }
122}
123
124#my-word {
125  margin: 0;
126  display: block;
127  padding: 0;
128  display:block;
129}
130
131#my-word li {
132  position: relative;
133  list-style: none;
134  margin: 0;
135  display: inline-block;
136  padding: 0 10px;
137  font-size:1.6em;
138}
139
140.active {
141  @include opacity;
142  cursor:default;
143    
144  &:hover{
145      @include fade;
146      @include opacity;
147    }
148}
149
150#mylives{
151  font-size:1.6em;
152  text-align:center;
153  display:block;
154}
155
156button{
157  @include corners (5px);
158  background:$base-color;
159  color:$white;
160  border: solid 1px $white;
161  text-decoration:none;
162  cursor:pointer;
163  font-size:1.2em;
164  padding:18px 10px;
165  width:180px;
166  margin: 10px;
167  outline: none;
168  
169    &:hover{
170      @include transition;
171      background:$white;
172      border: solid 1px $white;
173      color:$base-color;
174    }
175}
176
177@media (max-width: 767px) {
178  #alphabet {
179  padding:0 0 0 15px;
180}
181  }
182
183  @media (max-width: 480px) {
184  #alphabet {
185  padding:0 0 0 25px;
186}
187  }
  • فایل جاوا اسکریپت پروژه ساخت بازی HANGMAN با جاوا اسکریپت
1window.onload = function () {
2
3  var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
4        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
5        't', 'u', 'v', 'w', 'x', 'y', 'z'];
6  
7  var categories;         // Array of topics
8  var chosenCategory;     // Selected catagory
9  var getHint ;          // Word getHint
10  var word ;              // Selected word
11  var guess ;             // Geuss
12  var geusses = [ ];      // Stored geusses
13  var lives ;             // Lives
14  var counter ;           // Count correct geusses
15  var space;              // Number of spaces in word '-'
16
17  // Get elements
18  var showLives = document.getElementById("mylives");
19  var showCatagory = document.getElementById("scatagory");
20  var getHint = document.getElementById("hint");
21  var showClue = document.getElementById("clue");
22
23
24
25  // create alphabet ul
26  var buttons = function () {
27    myButtons = document.getElementById('buttons');
28    letters = document.createElement('ul');
29
30    for (var i = 0; i < alphabet.length; i++) {
31      letters.id = 'alphabet';
32      list = document.createElement('li');
33      list.id = 'letter';
34      list.innerHTML = alphabet[i];
35      check();
36      myButtons.appendChild(letters);
37      letters.appendChild(list);
38    }
39  }
40    
41  
42  // Select Catagory
43  var selectCat = function () {
44    if (chosenCategory === categories[0]) {
45      catagoryName.innerHTML = "The Chosen Category Is Premier League Football Teams";
46    } else if (chosenCategory === categories[1]) {
47      catagoryName.innerHTML = "The Chosen Category Is Films";
48    } else if (chosenCategory === categories[2]) {
49      catagoryName.innerHTML = "The Chosen Category Is Cities";
50    }
51  }
52
53  // Create geusses ul
54   result = function () {
55    wordHolder = document.getElementById('hold');
56    correct = document.createElement('ul');
57
58    for (var i = 0; i < word.length; i++) {
59      correct.setAttribute('id', 'my-word');
60      guess = document.createElement('li');
61      guess.setAttribute('class', 'guess');
62      if (word[i] === "-") {
63        guess.innerHTML = "-";
64        space = 1;
65      } else {
66        guess.innerHTML = "_";
67      }
68
69      geusses.push(guess);
70      wordHolder.appendChild(correct);
71      correct.appendChild(guess);
72    }
73  }
74  
75  // Show lives
76   comments = function () {
77    showLives.innerHTML = "You have " + lives + " lives";
78    if (lives < 1) {
79      showLives.innerHTML = "Game Over";
80    }
81    for (var i = 0; i < geusses.length; i++) {
82      if (counter + space === geusses.length) {
83        showLives.innerHTML = "You Win!";
84      }
85    }
86  }
87
88      // Animate man
89  var animate = function () {
90    var drawMe = lives ;
91    drawArray[drawMe]();
92  }
93
94  
95   // Hangman
96  canvas =  function(){
97
98    myStickman = document.getElementById("stickman");
99    context = myStickman.getContext('2d');
100    context.beginPath();
101    context.strokeStyle = "#fff";
102    context.lineWidth = 2;
103  };
104  
105    head = function(){
106      myStickman = document.getElementById("stickman");
107      context = myStickman.getContext('2d');
108      context.beginPath();
109      context.arc(60, 25, 10, 0, Math.PI*2, true);
110      context.stroke();
111    }
112    
113  draw = function($pathFromx, $pathFromy, $pathTox, $pathToy) {
114    
115    context.moveTo($pathFromx, $pathFromy);
116    context.lineTo($pathTox, $pathToy);
117    context.stroke(); 
118}
119
120   frame1 = function() {
121     draw (0, 150, 150, 150);
122   };
123   
124   frame2 = function() {
125     draw (10, 0, 10, 600);
126   };
127  
128   frame3 = function() {
129     draw (0, 5, 70, 5);
130   };
131  
132   frame4 = function() {
133     draw (60, 5, 60, 15);
134   };
135  
136   torso = function() {
137     draw (60, 36, 60, 70);
138   };
139  
140   rightArm = function() {
141     draw (60, 46, 100, 50);
142   };
143  
144   leftArm = function() {
145     draw (60, 46, 20, 50);
146   };
147  
148   rightLeg = function() {
149     draw (60, 70, 100, 100);
150   };
151  
152   leftLeg = function() {
153     draw (60, 70, 20, 100);
154   };
155  
156  drawArray = [rightLeg, leftLeg, rightArm, leftArm,  torso,  head, frame4, frame3, frame2, frame1]; 
157
158
159  // OnClick Function
160   check = function () {
161    list.onclick = function () {
162      var geuss = (this.innerHTML);
163      this.setAttribute("class", "active");
164      this.onclick = null;
165      for (var i = 0; i < word.length; i++) {
166        if (word[i] === geuss) {
167          geusses[i].innerHTML = geuss;
168          counter += 1;
169        } 
170      }
171      var j = (word.indexOf(geuss));
172      if (j === -1) {
173        lives -= 1;
174        comments();
175        animate();
176      } else {
177        comments();
178      }
179    }
180  }
181  
182    
183  // Play
184  play = function () {
185    categories = [
186        ["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
187        ["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
188        ["manchester", "milan", "madrid", "amsterdam", "prague"]
189    ];
190
191    chosenCategory = categories[Math.floor(Math.random() * categories.length)];
192    word = chosenCategory[Math.floor(Math.random() * chosenCategory.length)];
193    word = word.replace(/\s/g, "-");
194    console.log(word);
195    buttons();
196
197    geusses = [ ];
198    lives = 10;
199    counter = 0;
200    space = 0;
201    result();
202    comments();
203    selectCat();
204    canvas();
205  }
206
207  play();
208  
209  // Hint
210
211    hint.onclick = function() {
212
213      hints = [
214        ["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
215        ["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
216        ["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
217    ];
218
219    var catagoryIndex = categories.indexOf(chosenCategory);
220    var hintIndex = chosenCategory.indexOf(word);
221    showClue.innerHTML = "Clue: - " +  hints [catagoryIndex][hintIndex];
222  };
223
224   // Reset
225
226  document.getElementById('reset').onclick = function() {
227    correct.parentNode.removeChild(correct);
228    letters.parentNode.removeChild(letters);
229    showClue.innerHTML = "";
230    context.clearRect(0, 0, 400, 400);
231    play();
232  }
233}
234

برای مشاهده نسخه عملیاتی این پروژه به این صفحه (+) مراجعه کنید.

پروژه هفتم: ساخت بازی دوز با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

ساخت یک بازی دوز ساده با جاوا اسکریپت می‌توانید یک پروژه عالی دیگر باشد که می‌توانید در مدت کوتاهی آن را انجام دهید. در این پروژه ابتدا یک شبکه 3 در 3 ایجاد می‌کنیم که بازیکنان به ترتیب این شبکه را با علامت‌های ضربدر و دایره پر می‌کنند. بازیکن برنده کسی است که بتواند قبل از دیگری سه علامت را در یک ردیف افقی، عمودی یا قطری قرار دهد.

با این که این یک بازی ساده به حساب می‌آید، باید شیوه ایجاد منطق قواعد بازی را در جاوا اسکریپت بدانید. از این رو پیش از شروع به نوشتن این کد، ابتدا مراحل منطقی بازی را به صورت گام به گام تجزیه کنید. برای نمونه رسم یک فلوچارت برای بصری‌سازی خروج‌های مختلف بازی می‌تواند کمک شایان توجهی بکند. زمانی که توانستید فرایند بازی را روی کاغذ ببینید، می‌توانید شروع به کدنویسی عملی بکنید.

  • فایل HTML ساخت بازی دوز با جاوا اسکریپت
1<html>
2	<head>
3	  <meta charset="utf-8" />
4	  <meta http-equiv="X-UA-Compatible" content="IE=edge">
5	  <meta name="description" content="">
6	  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7	  <title>FreeCodeCamp: Tictactoe</title>
8		<link rel="stylesheet" href="../css/tictactoe.css" />
9	</head>
10
11	<body>
12		<div class="app">
13			<div class="container-fluid app-container">
14	    	<div class="row app-row">
15		    	<div class="col-xs-4 play-box" id="0">
16		    		<div class="symbol"></div>
17		    	</div>
18		    	<div class="col-xs-4 play-box" id="1">
19		    		<div class="symbol"></div>
20		    	</div>
21		    	<div class="col-xs-4 play-box last-right" id="2">
22		    		<div class="symbol"></div>
23		    	</div>
24		    	<div class="col-xs-4 play-box" id="3">
25		    		<div class="symbol"></div>
26		    	</div>
27		    	<div class="col-xs-4 play-box" id="4">
28		    		<div class="symbol"></div>
29		    	</div>
30		    	<div class="col-xs-4 play-box last-right" id="5">
31		    		<div class="symbol"></div>
32		    	</div>
33		    	<div class="col-xs-4 play-box last-bottom" id="6">
34		    		<div class="symbol"></div>
35		    	</div>
36		    	<div class="col-xs-4 play-box last-bottom" id="7">
37		    		<div class="symbol"></div>
38		    	</div>
39		    	<div class="col-xs-4 play-box last-right last-bottom" id="8">
40		    		<div class="symbol"></div>
41		    	</div>
42		    </div>
43			</div>
44		</div>
45
46		<div class="modal fade app-modal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
47		  <div class="modal-dialog modal-size">
48		    <div class="modal-content">
49		      <h3 class="content heading">Warning!!!</h3>
50		      <hr class="warning-hr">
51		      <div class="content body">
52			      Please save your time and don't even think you're smart. <br><strong><em>I'M SMARTER THAN YOU! HA-HA-HA!!!</em></strong> <br>
53			      Wana try me? Chose : <br>
54			      <div class="center-block symbol-options">
55			      	<button class="symbol-option btn btn-default btn-md" data-dismiss="modal">X</button> OR <button class="symbol-option btn btn-default btn-md" data-dismiss="modal">O</button>
56			      </div>
57		      </div>
58		    </div>
59		  </div>
60		</div>
61
62		<script src="../js/bundled/tictactoe.bundled.js">
63		</script>
64	</body>
65</html>
  • فایل CSS توسعه بازی دوز با جاوا اسکریپت
1@import url(https://fonts.googleapis.com/css?family=Yesteryear);
2
3$app-background-color : #508ABB;
4$app-row-height : 100%;
5$winAnimStartColor : cyan;
6$winAnimEndColor : #508ABB;
7
8// html, body, div, span, a, li, td, th {
9// 	font-family: 'Lato', sans-serif;
10// 	font-weight: 300;
11//
12// }
13
14@-webkit-keyframes winAnim{
15	0% {
16    background-color: $winAnimStartColor;
17  }
18  100% {
19    background-color: $winAnimEndColor;
20  }
21}
22@-moz-keyframes winAnim{
23  0% {
24    background-color: $winAnimStartColor;
25  }
26  100% {
27    background-color: $winAnimEndColor;
28  }
29}
30@-o-keyframes winAnim {
31  0% {
32    background-color: $winAnimStartColor;
33  }
34  100% {
35    background-color: $winAnimEndColor;
36  }
37}
38@keyframes winAnim {
39  0% {
40    background-color: $winAnimStartColor;
41  }
42  100% {
43    background-color: $winAnimEndColor;
44  }
45}
46
47@keyframes winAnim {
48  0% {
49    background-color: $winAnimStartColor;
50  }
51  100% {
52    background-color: $winAnimEndColor;
53  }
54}
55
56*{
57  -webkit-touch-callout: none;
58  -webkit-user-select: none;
59  -khtml-user-select: none;
60  -moz-user-select: none;
61  -ms-user-select: none;
62  user-select: none;
63  outline-style:none;/*IE*/
64}
65
66.center-box{
67	margin : auto;
68	position: absolute;
69	top : 0;
70	right : 0;
71	bottom : 0;
72	left : 0;
73}
74
75html,body{
76	//background-image: linear-gradient(to bottom,#dddbd1,#d2dbdc);
77	background-color: #d2dbdc;
78	height : 100%;
79	width  : 100%;
80}
81
82.app{
83	@extend .center-box;
84	width : 80%;
85	height : 70%;
86	max-width: 550px;
87	background-color : $app-background-color;
88	box-shadow: 0 5px 30px -5px rgba(0,0,0, .85);
89	border-radius: 10px;
90	.app-container,
91	.app-row{
92		height: $app-row-height;
93	}
94}
95.play-box,.symbol-option{
96	font-family: 'Yesteryear', cursive;
97}
98
99.play-box{
100	border-bottom : 2px solid #fff;
101	border-right : 2px solid #fff;
102	height : $app-row-height / 3;
103	cursor: pointer;
104	position: relative;
105	&.last-right{
106		border-right : none;
107	}
108	&.last-bottom{
109		border-bottom : none;
110	}
111	&.win {
112		-webkit-animation: winAnim .2s ease-out infinite;
113	  -moz-animation:    winAnim .2s ease-out infinite;
114	  -o-animation:      winAnim .2s ease-out infinite;
115	  animation:         winAnim .2s ease-out infinite;
116		animation : winAnim .5s infinite;
117	}
118	.symbol{
119		@extend .center-box;
120		width: 50%;
121		height : 50px;
122		text-align: center;
123		line-height : 50px;
124		font-size: 35px;
125		color : white;
126	}
127}
128
129.modal-content{
130	.content{
131		padding : 15px;
132		text-align: center;
133		margin : 0;
134		&.body{
135			line-height: 2;
136		}
137	}
138	.symbol-options{
139		width: 200px;
140		margin-top: 10px;
141		.symbol-option{
142			&:first-child{
143				margin-right: 10px;
144			}
145			&:last-child{
146				margin-left: 10px;
147			}
148		}
149	}
150	.warning-hr{
151		margin: 0;
152	}
153}

برای مشاهده کد جاوا اسکریپت و نسخه عملیاتی این بخش از آموزش جاوا اسکریپت پروژه محور به این صفحه (+) مراجعه کنید.

پروژه هشتم: ساخت بازی PONG با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

Pong یکی از بازی‌های محبوب بسیاری از کاربران است. ساخت این بازی در جاوا اسکریپت نیاز به کمی تلاش دارد، اما سرگرمی زیادی نیز ایجاد می‌کند. در این مورد نیز ابتدا باید در مورد قواعد بازی تأمل کنیم و رویدادهای مختلفی که باید کدنویسی شوند را مشخص سازیم. در زمان ساخت بازی احتمالاً ایده‌های مختلفی برای جذاب‌تر ساختن آن به ذهنتان می‌رسد.

همچنین ممکن است بخواهید سطوح مختلف دشواری برای بازی طراحی کنید. برای نمونه توپ می‌تواند پس از تعداد مشخصی دور، ‌سریع‌تر حرکت کند. ضمن اینکه به منظور دشوار شدن کارها برای بازیکن، می‌توانید کاری کنید که رایانه موانع را سریع‌تر جابجا کند.

در صورتی که به تازگی با جاوا اسکریپت آشنا شده باشید، پیاده‌سازی بازی Pong یک پروژه نسبتاً پیچیده برایتان خواهد بود. بنابراین در این حالت پیشنهاد می‌کنیم ابتدا کار خود را با پروژه‌های آسان‌تر که در بخش‌های قبلی مقاله آموزش جاوا اسکریپت پروژه محور معرفی کردیم آغاز کنید. احتمالاً دشوارترین بخش این پروژه آن است که مطمئن شوید رایانه همواره برنده نمی‌شود. از این رو باید اطمینان حاصل کنید که قبلاً برخی پروژه‌های آسان‌تر را پیاده‌سازی کرده‌اید، تا با ظرائف کارها آشنا شوید.

  • فایل HTML توسعه بازی PONG با جاوا اسکریپت
1<canvas></canvas>
  • فایل CSS ساخت بازی PONG با جاوا اسکریپت
1body {
2	text-align: center;
3}
  • فایل جاوا اسکریپت پروژه کدنویسی بازی PONG با جاوا اسکریپت
1// Global Variables
2var DIRECTION = {
3	IDLE: 0,
4	UP: 1,
5	DOWN: 2,
6	LEFT: 3,
7	RIGHT: 4
8};
9
10var rounds = [5, 5, 3, 3, 2];
11var colors = ['#1abc9c', '#2ecc71', '#3498db', '#e74c3c', '#9b59b6'];
12
13// The ball object (The cube that bounces back and forth)
14var Ball = {
15	new: function (incrementedSpeed) {
16		return {
17			width: 18,
18			height: 18,
19			x: (this.canvas.width / 2) - 9,
20			y: (this.canvas.height / 2) - 9,
21			moveX: DIRECTION.IDLE,
22			moveY: DIRECTION.IDLE,
23			speed: incrementedSpeed || 9
24		};
25	}
26};
27
28// The paddle object (The two lines that move up and down)
29var Paddle = {
30	new: function (side) {
31		return {
32			width: 18,
33			height: 70,
34			x: side === 'left' ? 150 : this.canvas.width - 150,
35			y: (this.canvas.height / 2) - 35,
36			score: 0,
37			move: DIRECTION.IDLE,
38			speed: 10
39		};
40	}
41};
42
43var Game = {
44	initialize: function () {
45		this.canvas = document.querySelector('canvas');
46		this.context = this.canvas.getContext('2d');
47
48		this.canvas.width = 1400;
49		this.canvas.height = 1000;
50
51		this.canvas.style.width = (this.canvas.width / 2) + 'px';
52		this.canvas.style.height = (this.canvas.height / 2) + 'px';
53
54		this.player = Paddle.new.call(this, 'left');
55		this.paddle = Paddle.new.call(this, 'right');
56		this.ball = Ball.new.call(this);
57
58		this.paddle.speed = 8;
59		this.running = this.over = false;
60		this.turn = this.paddle;
61		this.timer = this.round = 0;
62		this.color = '#2c3e50';
63
64		Pong.menu();
65		Pong.listen();
66	},
67
68	endGameMenu: function (text) {
69		// Change the canvas font size and color
70		Pong.context.font = '50px Courier New';
71		Pong.context.fillStyle = this.color;
72
73		// Draw the rectangle behind the 'Press any key to begin' text.
74		Pong.context.fillRect(
75			Pong.canvas.width / 2 - 350,
76			Pong.canvas.height / 2 - 48,
77			700,
78			100
79		);
80
81		// Change the canvas color;
82		Pong.context.fillStyle = '#ffffff';
83
84		// Draw the end game menu text ('Game Over' and 'Winner')
85		Pong.context.fillText(text,
86			Pong.canvas.width / 2,
87			Pong.canvas.height / 2 + 15
88		);
89
90		setTimeout(function () {
91			Pong = Object.assign({}, Game);
92			Pong.initialize();
93		}, 3000);
94	},
95
96	menu: function () {
97		// Draw all the Pong objects in their current state
98		Pong.draw();
99
100		// Change the canvas font size and color
101		this.context.font = '50px Courier New';
102		this.context.fillStyle = this.color;
103
104		// Draw the rectangle behind the 'Press any key to begin' text.
105		this.context.fillRect(
106			this.canvas.width / 2 - 350,
107			this.canvas.height / 2 - 48,
108			700,
109			100
110		);
111
112		// Change the canvas color;
113		this.context.fillStyle = '#ffffff';
114
115		// Draw the 'press any key to begin' text
116		this.context.fillText('Press any key to begin',
117			this.canvas.width / 2,
118			this.canvas.height / 2 + 15
119		);
120	},
121
122	// Update all objects (move the player, paddle, ball, increment the score, etc.)
123	update: function () {
124		if (!this.over) {
125			// If the ball collides with the bound limits - correct the x and y coords.
126			if (this.ball.x <= 0) Pong._resetTurn.call(this, this.paddle, this.player);
127			if (this.ball.x >= this.canvas.width - this.ball.width) Pong._resetTurn.call(this, this.player, this.paddle);
128			if (this.ball.y <= 0) this.ball.moveY = DIRECTION.DOWN;
129			if (this.ball.y >= this.canvas.height - this.ball.height) this.ball.moveY = DIRECTION.UP;
130
131			// Move player if they player.move value was updated by a keyboard event
132			if (this.player.move === DIRECTION.UP) this.player.y -= this.player.speed;
133			else if (this.player.move === DIRECTION.DOWN) this.player.y += this.player.speed;
134
135			// On new serve (start of each turn) move the ball to the correct side
136			// and randomize the direction to add some challenge.
137			if (Pong._turnDelayIsOver.call(this) && this.turn) {
138				this.ball.moveX = this.turn === this.player ? DIRECTION.LEFT : DIRECTION.RIGHT;
139				this.ball.moveY = [DIRECTION.UP, DIRECTION.DOWN][Math.round(Math.random())];
140				this.ball.y = Math.floor(Math.random() * this.canvas.height - 200) + 200;
141				this.turn = null;
142			}
143
144			// If the player collides with the bound limits, update the x and y coords.
145			if (this.player.y <= 0) this.player.y = 0;
146			else if (this.player.y >= (this.canvas.height - this.player.height)) this.player.y = (this.canvas.height - this.player.height);
147
148			// Move ball in intended direction based on moveY and moveX values
149			if (this.ball.moveY === DIRECTION.UP) this.ball.y -= (this.ball.speed / 1.5);
150			else if (this.ball.moveY === DIRECTION.DOWN) this.ball.y += (this.ball.speed / 1.5);
151			if (this.ball.moveX === DIRECTION.LEFT) this.ball.x -= this.ball.speed;
152			else if (this.ball.moveX === DIRECTION.RIGHT) this.ball.x += this.ball.speed;
153
154			// Handle paddle (AI) UP and DOWN movement
155			if (this.paddle.y > this.ball.y - (this.paddle.height / 2)) {
156				if (this.ball.moveX === DIRECTION.RIGHT) this.paddle.y -= this.paddle.speed / 1.5;
157				else this.paddle.y -= this.paddle.speed / 4;
158			}
159			if (this.paddle.y < this.ball.y - (this.paddle.height / 2)) {
160				if (this.ball.moveX === DIRECTION.RIGHT) this.paddle.y += this.paddle.speed / 1.5;
161				else this.paddle.y += this.paddle.speed / 4;
162			}
163
164			// Handle paddle (AI) wall collision
165			if (this.paddle.y >= this.canvas.height - this.paddle.height) this.paddle.y = this.canvas.height - this.paddle.height;
166			else if (this.paddle.y <= 0) this.paddle.y = 0;
167
168			// Handle Player-Ball collisions
169			if (this.ball.x - this.ball.width <= this.player.x && this.ball.x >= this.player.x - this.player.width) {
170				if (this.ball.y <= this.player.y + this.player.height && this.ball.y + this.ball.height >= this.player.y) {
171					this.ball.x = (this.player.x + this.ball.width);
172					this.ball.moveX = DIRECTION.RIGHT;
173
174					beep1.play();
175				}
176			}
177
178			// Handle paddle-ball collision
179			if (this.ball.x - this.ball.width <= this.paddle.x && this.ball.x >= this.paddle.x - this.paddle.width) {
180				if (this.ball.y <= this.paddle.y + this.paddle.height && this.ball.y + this.ball.height >= this.paddle.y) {
181					this.ball.x = (this.paddle.x - this.ball.width);
182					this.ball.moveX = DIRECTION.LEFT;
183
184					beep1.play();
185				}
186			}
187		}
188
189		// Handle the end of round transition
190		// Check to see if the player won the round.
191		if (this.player.score === rounds[this.round]) {
192			// Check to see if there are any more rounds/levels left and display the victory screen if
193			// there are not.
194			if (!rounds[this.round + 1]) {
195				this.over = true;
196				setTimeout(function () { Pong.endGameMenu('Winner!'); }, 1000);
197			} else {
198				// If there is another round, reset all the values and increment the round number.
199				this.color = this._generateRoundColor();
200				this.player.score = this.paddle.score = 0;
201				this.player.speed += 0.5;
202				this.paddle.speed += 1;
203				this.ball.speed += 1;
204				this.round += 1;
205
206				beep3.play();
207			}
208		}
209		// Check to see if the paddle/AI has won the round.
210		else if (this.paddle.score === rounds[this.round]) {
211			this.over = true;
212			setTimeout(function () { Pong.endGameMenu('Game Over!'); }, 1000);
213		}
214	},
215
216	// Draw the objects to the canvas element
217	draw: function () {
218		// Clear the Canvas
219		this.context.clearRect(
220			0,
221			0,
222			this.canvas.width,
223			this.canvas.height
224		);
225
226		// Set the fill style to black
227		this.context.fillStyle = this.color;
228
229		// Draw the background
230		this.context.fillRect(
231			0,
232			0,
233			this.canvas.width,
234			this.canvas.height
235		);
236
237		// Set the fill style to white (For the paddles and the ball)
238		this.context.fillStyle = '#ffffff';
239
240		// Draw the Player
241		this.context.fillRect(
242			this.player.x,
243			this.player.y,
244			this.player.width,
245			this.player.height
246		);
247
248		// Draw the Paddle
249		this.context.fillRect(
250			this.paddle.x,
251			this.paddle.y,
252			this.paddle.width,
253			this.paddle.height
254		);
255
256		// Draw the Ball
257		if (Pong._turnDelayIsOver.call(this)) {
258			this.context.fillRect(
259				this.ball.x,
260				this.ball.y,
261				this.ball.width,
262				this.ball.height
263			);
264		}
265
266		// Draw the net (Line in the middle)
267		this.context.beginPath();
268		this.context.setLineDash([7, 15]);
269		this.context.moveTo((this.canvas.width / 2), this.canvas.height - 140);
270		this.context.lineTo((this.canvas.width / 2), 140);
271		this.context.lineWidth = 10;
272		this.context.strokeStyle = '#ffffff';
273		this.context.stroke();
274
275		// Set the default canvas font and align it to the center
276		this.context.font = '100px Courier New';
277		this.context.textAlign = 'center';
278
279		// Draw the players score (left)
280		this.context.fillText(
281			this.player.score.toString(),
282			(this.canvas.width / 2) - 300,
283			200
284		);
285
286		// Draw the paddles score (right)
287		this.context.fillText(
288			this.paddle.score.toString(),
289			(this.canvas.width / 2) + 300,
290			200
291		);
292
293		// Change the font size for the center score text
294		this.context.font = '30px Courier New';
295
296		// Draw the winning score (center)
297		this.context.fillText(
298			'Round ' + (Pong.round + 1),
299			(this.canvas.width / 2),
300			35
301		);
302
303		// Change the font size for the center score value
304		this.context.font = '40px Courier';
305
306		// Draw the current round number
307		this.context.fillText(
308			rounds[Pong.round] ? rounds[Pong.round] : rounds[Pong.round - 1],
309			(this.canvas.width / 2),
310			100
311		);
312	},
313
314	loop: function () {
315		Pong.update();
316		Pong.draw();
317
318		// If the game is not over, draw the next frame.
319		if (!Pong.over) requestAnimationFrame(Pong.loop);
320	},
321
322	listen: function () {
323		document.addEventListener('keydown', function (key) {
324			// Handle the 'Press any key to begin' function and start the game.
325			if (Pong.running === false) {
326				Pong.running = true;
327				window.requestAnimationFrame(Pong.loop);
328			}
329
330			// Handle up arrow and w key events
331			if (key.keyCode === 38 || key.keyCode === 87) Pong.player.move = DIRECTION.UP;
332
333			// Handle down arrow and s key events
334			if (key.keyCode === 40 || key.keyCode === 83) Pong.player.move = DIRECTION.DOWN;
335		});
336
337		// Stop the player from moving when there are no keys being pressed.
338		document.addEventListener('keyup', function (key) { Pong.player.move = DIRECTION.IDLE; });
339	},
340
341	// Reset the ball location, the player turns and set a delay before the next round begins.
342	_resetTurn: function(victor, loser) {
343		this.ball = Ball.new.call(this, this.ball.speed);
344		this.turn = loser;
345		this.timer = (new Date()).getTime();
346
347		victor.score++;
348		beep2.play();
349	},
350
351	// Wait for a delay to have passed after each turn.
352	_turnDelayIsOver: function() {
353		return ((new Date()).getTime() - this.timer >= 1000);
354	},
355
356	// Select a random color as the background of each level/round.
357	_generateRoundColor: function () {
358		var newColor = colors[Math.floor(Math.random() * colors.length)];
359		if (newColor === this.color) return Pong._generateRoundColor();
360		return newColor;
361	}
362};
363
364var Pong = Object.assign({}, Game);
365Pong.initialize();

برای مشاهده نسخه عملیاتی این پروژه به این صفحه (+) مراجعه کنید.

پروژه نهم: ساخت بازی کارت‌های جفت با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

کدنویسی یک بازی تطبیق حافظه در جاوا اسکریپت نیز ایده سرگرم‌کننده‌ای برای یک پروژه آموزشی محسوب می‌شود، پس در ادامه مقاله آموزش جاوا اسکریپت پروژه محور به آن خواهیم پرداخت. منطق این بازی ساده است:

  1. تعداد مشخصی کارت روی میز هست و ما پشت کارت‌ها را می‌بینیم.
  2. بازیکن باید همه کارت‌های جفت را پیدا کند.

با استفاده از محدودسازی تعداد دفعات حدس یا تعیین محدودیت زمانی برای بازی، می‌توان آن را هیجان‌انگیزتر ساخت. این نیز یک پروژه عالی نه تنها برای تمرین مهارت‌های جاوا اسکریپت، بلکه ‌برای تمرین کدنویسی HTML و CSS محسوب می‌شود. آسان‌ترین روش برای ایجاد کارت‌های مطابق هم این است که رنگ‌های مختلفی روی آنها قرار دهیم تا بازیکن این رنگ‌ها را با هم تطبیق دهد. اما می‌توان از تصاویر آیکون‌ها و اعداد نیز به این منظور بهره جست.

  • فایل HTML توسعه بازی کارت‌های جفت با جاوا اسکریپت
1<div class="wrapper">
2  <h1>JavaScript pairs Game</h1>
3  <h3>Click any card to begin</h3>
4  <p><span id="seconds">00</span>:<span id="tens">00</span></p>
5  <p id ="text"></p>
6  <div id="container">
7
8  </div>
9</div>
  • فایل CSS کدنویسی بازی کارت‌های جفت با جاوا اسکریپت
1/* Variabes */  
2$orange: #ffa600;
3$green: #c1d72e;
4$blue: #82d2e5;
5$grey: #f3f3f3;
6$white: #fff;
7$base-color:$blue ;
8
9
10/* Mixin's */  
11@mixin transition {
12  -webkit-transition: all 0.5s ease-in-out;
13  -moz-transition: all 0.5s ease-in-out;
14  transition: all 0.5s ease-in-out;
15}
16
17@mixin corners ($radius) {
18  -moz-border-radius: $radius;
19  -webkit-border-radius: $radius;
20  border-radius: $radius; 
21  -khtml-border-radius: $radius; 
22}
23
24body {
25  background:$base-color;
26  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
27  height:100%;
28  color: $white;
29  text-align: center;
30}
31
32
33h1, h2 {
34  font-family: 'Roboto', sans-serif;
35  font-weight: 100;
36  font-size: 2.6em;
37  text-transform: uppercase;
38}
39
40h3 {
41  font-family: 'Roboto', sans-serif;
42  font-weight: 100;
43  font-size: 1.4em;
44  text-transform: uppercase;
45}
46
47#seconds, #tens{
48  font-size:2em;
49}
50
51button{
52  @include corners (5px);
53  background:$base-color;
54  color:$white;
55  border: solid 1px $white;
56  text-decoration:none;
57  cursor:pointer;
58  font-size:1.2em;
59  padding:18px 10px;
60  width:180px;
61  margin: 10px;
62  outline: none;
63 
64    &:hover {
65    	@include transition;
66    	background:$white;
67    	border: solid 1px $white;
68    	color:$base-color;
69  	}
70    
71}
72
73
74#container {
75  width: 630px;
76  margin: 10px auto;
77
78  &:after {
79    content: "";
80    display: table;
81    clear: both;
82  }
83  
84}
85
86[data-view="card"] {
87  transform: rotateY(180deg);
88  width: 100px;
89  height: 140px;
90  border: solid 1px #d3cece;
91  border-radius: 5px;
92  float: left;
93  margin: 10px;
94  cursor: pointer;
95  background:
96  linear-gradient(135deg, $grey 22px, $white 22px, $white 24px, transparent 24px, transparent 67px, $white 67px, $white 69px, transparent 69px),
97  linear-gradient(225deg, $grey 22px, $white 22px, $white 24px, transparent 24px, transparent 67px, $white 67px, $white 69px, transparent 69px)0 64px;
98  background-color: $grey;
99  background-size: 64px 128px
100}
101
102.flipped {
103  transition: 0.6s;
104	transform-style: preserve-3d;
105  position: relative;
106	transform: rotateY(0deg);
107}
108
109.reverse {
110  transition: 0.6s;
111	transform-style: preserve-3d;
112  position: relative;
113	transform: rotateY(180deg);
114}
115
116.correct {
117  opacity: .5;
118  cursor: default;
119	transform-style: preserve-3d;
120  position: relative;
121	transform: rotateY(0deg);
122}
123
124/* Icons */
125$cards: sass, gulp, grunt, git, css3;
126       
127@each $card in $cards  {
128
129  .correct[data-item="#{$card}"],
130  .flipped[data-item="#{$card}"]{
131    background:url("https://cathydutton.co.uk/assets/img/#{$card}.png") left center no-repeat $white;
132    background-size: contain;
133  }
134
135}
136
137
138
139
  • فایل جاوا اسکریپت پروژه کدنویسی بازی کارت‌های جفت با جاوا اسکریپت
1var myCards = document.getElementById('container');
2var resultsArray = [];
3var counter = 0;
4var text = document.getElementById('text');
5var seconds = 00; 
6var tens = 00; 
7var appendTens = document.getElementById("tens");
8var appendSeconds = document.getElementById("seconds");
9var Interval ;
10var images = [
11  'sass', 
12  'git', 
13  'gulp', 
14  'css3', 
15  'grunt'
16];
17
18var clone = images.slice(0); // duplicate array
19var cards = images.concat(clone); // merge to arrays 
20
21// Shufffel function
22function shuffle(o){
23  for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i],   o[i] = o[j], o[j] = x);
24  return o;
25}
26shuffle(cards);
27
28for (var i = 0; i < cards.length; i++) {
29  card = document.createElement('div');
30  card.dataset.item = cards[i];
31  card.dataset.view = "card";
32  myCards.appendChild(card);
33     
34  card.onclick = function () {
35   
36    if (this.className != 'flipped' && this.className != 'correct'){
37        this.className = 'flipped';
38        var result = this.dataset.item;
39        resultsArray.push(result);
40        clearInterval(Interval);
41        Interval = setInterval(startTimer, 10);
42    }
43  
44    if (resultsArray.length > 1) {
45
46      if (resultsArray[0] === resultsArray[1]) {
47        check("correct");
48        counter ++;
49        win();
50        resultsArray = [];
51      } else {
52        check("reverse");
53        resultsArray = [];
54      }
55      
56    }
57    
58  }
59   
60};
61
62
63var check = function(className) {
64  
65  var x = document.getElementsByClassName("flipped");
66  setTimeout(function() {
67
68    for(var i = (x.length - 1); i >= 0; i--) {
69      x[i].className = className;
70    }
71     
72  },500);
73   
74}
75
76var win = function () {
77
78  if(counter === 5) {
79    clearInterval(Interval);
80    text.innerHTML = "Your time was " + seconds + ":" + tens;
81  } 
82  
83}
84     
85function startTimer () {
86  tens++; 
87    
88  if(tens < 9){
89    appendTens.innerHTML = "0" + tens;
90  }
91    
92  if (tens > 9){
93    appendTens.innerHTML = tens;
94      
95  } 
96    
97  if (tens > 99) {
98    seconds++;
99    appendSeconds.innerHTML = "0" + seconds;
100    tens = 0;
101    appendTens.innerHTML = "0" + 0;
102  }
103    
104  if (seconds > 9){
105    appendSeconds.innerHTML = seconds;
106  }
107  
108}
109

برای مشاهده نسخه عملیاتی این پروژه به این صفحه (+) مراجعه کنید.

پروژه دهم: ساخت بازی MAZE با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

کدنویسی بازی MAZE نیز یک ایده عالی برای یک پروژه آموزش کدنویسی مفرح محسوب می‌شود. با این حال این پروژه برخی دشواری‌های خاص خود را نیز دارد. از این رو اگر به تازگی کار با جاوا اسکریپت را آغاز کرده‌اید باید مطمئن شوید که به قدر کافی در این زبان مهارت کسب کرده‌اید تا بتوانید شروع به ساخت این بازی بکنید. آموزش جاوا اسکریپت پروژه محور را با کدهای بازی MAZE ادامه می‌دهیم.

  • فایل HTML توسعه بازی MAZE با جاوا اسکریپت
1<html lang="en-GB">
2<head>
3  <meta charset="utf-8">
4  <body>
5    <div id="gradient"></div>
6    <div id="page">
7      <div id="Message-Container">
8        <div id="message">
9          <h1>Congratulations!</h1>
10          <p>You are done.</p>
11          <p id="moves"></p>
12          <input id="okBtn" type="button" onclick="toggleVisablity('Message-Container')" value="Cool!" />
13        </div>
14      </div>
15      <div id="menu">
16        <div class="custom-select">
17          <select id="diffSelect">
18                    <option value="10">Easy</option>
19                    <option value="15">Medium</option>
20                    <option value="25">Hard</option>
21                    <option value="38">Extreme</option>                                      
22                </select>
23        </div>
24        <input id="startMazeBtn" type="button" onclick="makeMaze()" value="Start" />
25      </div>
26      <div id="view">
27        <div id="mazeContainer">
28          <canvas id="mazeCanvas" class="border" height="1100" width="1100"></canvas>
29        </div>
30      </div>
31    </div>
32    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
33    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.18/jquery.touchSwipe.min.js"></script>
34  </body>
35</html>
  • فایل CSS کدنویسی بازی MAZE با جاوا اسکریپت
1$menuHeight: 65px+10px;
2@mixin transition {
3    transition-property: background-color opacity;
4    transition-duration: 0.2s;
5    transition-timing-function: ease-in-out;
6}
7
8html,
9body {
10    width: 100vw;
11    height: 100vh;
12    position: fixed;
13    padding: 0;
14    margin: 0;
15    top: 0;
16    bottom: 0;
17    left: 0;
18    right: 0;
19}
20
21#mazeContainer {
22    transition-property: opacity;
23    transition-duration: 1s;
24    transition-timing-function: linear;
25    top: $menuHeight;
26    opacity: 0;
27    display: inline-block;
28    background-color: rgba(0, 0, 0, 0.30);
29    margin: auto;
30
31    #mazeCanvas {
32        margin: 0;
33        display: block;
34        border: solid 1px black;
35    }
36}
37
38input,
39select {
40    @include transition;
41    cursor: pointer;
42    background-color: rgba(0, 0, 0, 0.30);
43    height: 45px;
44    width: 150px;
45    padding: 10px;
46    border: none;
47    border-radius: 5px;
48    color: white;
49    display: inline-block;
50    font-size: 15px;
51    text-align: center;
52    text-decoration: none;
53    appearance: none;
54    &:hover {
55        background-color: rgba(0, 0, 0, 0.70);
56    }
57    &:active {
58        background-color: black;
59    }
60    &:focus {
61        outline: none;
62    }
63}
64
65
66.custom-select {
67    display: inline-block;
68    select {
69        -webkit-appearance: none;
70        -moz-appearance: none;
71        appearance: none;
72        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAh0lEQVQ4T93TMQrCUAzG8V9x8QziiYSuXdzFC7h4AcELOPQAdXYovZCHEATlgQV5GFTe1ozJlz/kS1IpjKqw3wQBVyy++JI0y1GTe7DCBbMAckeNIQKk/BanALBB+16LtnDELoMcsM/BESDlz2heDR3WePwKSLo5eoxz3z6NNcFD+vu3ij14Aqz/DxGbKB7CAAAAAElFTkSuQmCC');
73        background-repeat: no-repeat;
74        background-position: 125px center;
75    }
76}
77
78#Message-Container {
79    visibility: hidden;
80    color: white;
81    display: block;
82    width: 100vw;
83    height: 100vh;
84    position: fixed;
85    top: 0;
86    left: 0;
87    bottom: 0;
88    right: 0;
89    background-color: rgba(0, 0, 0, 0.30);
90    z-index: 1;
91    #message {
92        width: 300px;
93        height: 300px;
94        position: fixed;
95        top: 50%;
96        left: 50%;
97        margin-left: -150px;
98        margin-top: -150px;
99    }
100}
101
102#page {
103    font-family: "Segoe UI", Arial, sans-serif;
104    text-align: center;
105    height: auto;
106    width: auto;
107    margin: auto;
108    #menu {
109        margin: auto;
110        padding: 10px;
111        height: 65px;
112        box-sizing: border-box;
113        h1 {
114            margin: 0;
115            margin-bottom: 10px;
116            font-weight: 600;
117            font-size: 3.2rem;
118        }
119    }
120    #view {
121        position: absolute;
122        top:65px;
123        bottom: 0;
124        left: 0;
125        right: 0;
126        width: 100%;
127        height: auto;
128           
129    }
130}
131
132.border {
133    border: 1px black solid;
134    border-radius: 5px;
135}
136
137
138
139#gradient {
140    z-index: -1;
141    position: fixed;
142    top: 0;
143    bottom: 0;
144    width: 100vw;
145    height: 100vh;
146    color: #fff;
147    background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
148    background-size: 400% 400%;
149    animation: Gradient 15s ease infinite;
150}
151
152@keyframes Gradient {
153    0% {
154        background-position: 0% 50%
155    }
156    50% {
157        background-position: 100% 50%
158    }
159    100% {
160        background-position: 0% 50%
161    }
162}
163
164 /* Extra small devices (phones, 600px and down) */
165 @media only screen and (max-width: 400px) {
166     input, select{
167         width: 120px;
168     }
169 }
  • فایل جاوا اسکریپت پروژه ساخت بازی MAZE با جاوا اسکریپت
1function rand(max) {
2  return Math.floor(Math.random() * max);
3}
4
5function shuffle(a) {
6  for (let i = a.length - 1; i > 0; i--) {
7    const j = Math.floor(Math.random() * (i + 1));
8    [a[i], a[j]] = [a[j], a[i]];
9  }
10  return a;
11}
12
13function changeBrightness(factor, sprite) {
14  var virtCanvas = document.createElement("canvas");
15  virtCanvas.width = 500;
16  virtCanvas.height = 500;
17  var context = virtCanvas.getContext("2d");
18  context.drawImage(sprite, 0, 0, 500, 500);
19
20  var imgData = context.getImageData(0, 0, 500, 500);
21
22  for (let i = 0; i < imgData.data.length; i += 4) {
23    imgData.data[i] = imgData.data[i] * factor;
24    imgData.data[i + 1] = imgData.data[i + 1] * factor;
25    imgData.data[i + 2] = imgData.data[i + 2] * factor;
26  }
27  context.putImageData(imgData, 0, 0);
28
29  var spriteOutput = new Image();
30  spriteOutput.src = virtCanvas.toDataURL();
31  virtCanvas.remove();
32  return spriteOutput;
33}
34
35function displayVictoryMess(moves) {
36  document.getElementById("moves").innerHTML = "You Moved " + moves + " Steps.";
37  toggleVisablity("Message-Container");  
38}
39
40function toggleVisablity(id) {
41  if (document.getElementById(id).style.visibility == "visible") {
42    document.getElementById(id).style.visibility = "hidden";
43  } else {
44    document.getElementById(id).style.visibility = "visible";
45  }
46}
47
48function Maze(Width, Height) {
49  var mazeMap;
50  var width = Width;
51  var height = Height;
52  var startCoord, endCoord;
53  var dirs = ["n", "s", "e", "w"];
54  var modDir = {
55    n: {
56      y: -1,
57      x: 0,
58      o: "s"
59    },
60    s: {
61      y: 1,
62      x: 0,
63      o: "n"
64    },
65    e: {
66      y: 0,
67      x: 1,
68      o: "w"
69    },
70    w: {
71      y: 0,
72      x: -1,
73      o: "e"
74    }
75  };
76
77  this.map = function() {
78    return mazeMap;
79  };
80  this.startCoord = function() {
81    return startCoord;
82  };
83  this.endCoord = function() {
84    return endCoord;
85  };
86
87  function genMap() {
88    mazeMap = new Array(height);
89    for (y = 0; y < height; y++) {
90      mazeMap[y] = new Array(width);
91      for (x = 0; x < width; ++x) {
92        mazeMap[y][x] = {
93          n: false,
94          s: false,
95          e: false,
96          w: false,
97          visited: false,
98          priorPos: null
99        };
100      }
101    }
102  }
103
104  function defineMaze() {
105    var isComp = false;
106    var move = false;
107    var cellsVisited = 1;
108    var numLoops = 0;
109    var maxLoops = 0;
110    var pos = {
111      x: 0,
112      y: 0
113    };
114    var numCells = width * height;
115    while (!isComp) {
116      move = false;
117      mazeMap[pos.x][pos.y].visited = true;
118
119      if (numLoops >= maxLoops) {
120        shuffle(dirs);
121        maxLoops = Math.round(rand(height / 8));
122        numLoops = 0;
123      }
124      numLoops++;
125      for (index = 0; index < dirs.length; index++) {
126        var direction = dirs[index];
127        var nx = pos.x + modDir[direction].x;
128        var ny = pos.y + modDir[direction].y;
129
130        if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
131          //Check if the tile is already visited
132          if (!mazeMap[nx][ny].visited) {
133            //Carve through walls from this tile to next
134            mazeMap[pos.x][pos.y][direction] = true;
135            mazeMap[nx][ny][modDir[direction].o] = true;
136
137            //Set Currentcell as next cells Prior visited
138            mazeMap[nx][ny].priorPos = pos;
139            //Update Cell position to newly visited location
140            pos = {
141              x: nx,
142              y: ny
143            };
144            cellsVisited++;
145            //Recursively call this method on the next tile
146            move = true;
147            break;
148          }
149        }
150      }
151
152      if (!move) {
153        //  If it failed to find a direction,
154        //  move the current position back to the prior cell and Recall the method.
155        pos = mazeMap[pos.x][pos.y].priorPos;
156      }
157      if (numCells == cellsVisited) {
158        isComp = true;
159      }
160    }
161  }
162
163  function defineStartEnd() {
164    switch (rand(4)) {
165      case 0:
166        startCoord = {
167          x: 0,
168          y: 0
169        };
170        endCoord = {
171          x: height - 1,
172          y: width - 1
173        };
174        break;
175      case 1:
176        startCoord = {
177          x: 0,
178          y: width - 1
179        };
180        endCoord = {
181          x: height - 1,
182          y: 0
183        };
184        break;
185      case 2:
186        startCoord = {
187          x: height - 1,
188          y: 0
189        };
190        endCoord = {
191          x: 0,
192          y: width - 1
193        };
194        break;
195      case 3:
196        startCoord = {
197          x: height - 1,
198          y: width - 1
199        };
200        endCoord = {
201          x: 0,
202          y: 0
203        };
204        break;
205    }
206  }
207
208  genMap();
209  defineStartEnd();
210  defineMaze();
211}
212
213function DrawMaze(Maze, ctx, cellsize, endSprite = null) {
214  var map = Maze.map();
215  var cellSize = cellsize;
216  var drawEndMethod;
217  ctx.lineWidth = cellSize / 40;
218
219  this.redrawMaze = function(size) {
220    cellSize = size;
221    ctx.lineWidth = cellSize / 50;
222    drawMap();
223    drawEndMethod();
224  };
225
226  function drawCell(xCord, yCord, cell) {
227    var x = xCord * cellSize;
228    var y = yCord * cellSize;
229
230    if (cell.n == false) {
231      ctx.beginPath();
232      ctx.moveTo(x, y);
233      ctx.lineTo(x + cellSize, y);
234      ctx.stroke();
235    }
236    if (cell.s === false) {
237      ctx.beginPath();
238      ctx.moveTo(x, y + cellSize);
239      ctx.lineTo(x + cellSize, y + cellSize);
240      ctx.stroke();
241    }
242    if (cell.e === false) {
243      ctx.beginPath();
244      ctx.moveTo(x + cellSize, y);
245      ctx.lineTo(x + cellSize, y + cellSize);
246      ctx.stroke();
247    }
248    if (cell.w === false) {
249      ctx.beginPath();
250      ctx.moveTo(x, y);
251      ctx.lineTo(x, y + cellSize);
252      ctx.stroke();
253    }
254  }
255
256  function drawMap() {
257    for (x = 0; x < map.length; x++) {
258      for (y = 0; y < map[x].length; y++) {
259        drawCell(x, y, map[x][y]);
260      }
261    }
262  }
263
264  function drawEndFlag() {
265    var coord = Maze.endCoord();
266    var gridSize = 4;
267    var fraction = cellSize / gridSize - 2;
268    var colorSwap = true;
269    for (let y = 0; y < gridSize; y++) {
270      if (gridSize % 2 == 0) {
271        colorSwap = !colorSwap;
272      }
273      for (let x = 0; x < gridSize; x++) {
274        ctx.beginPath();
275        ctx.rect(
276          coord.x * cellSize + x * fraction + 4.5,
277          coord.y * cellSize + y * fraction + 4.5,
278          fraction,
279          fraction
280        );
281        if (colorSwap) {
282          ctx.fillStyle = "rgba(0, 0, 0, 0.8)";
283        } else {
284          ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
285        }
286        ctx.fill();
287        colorSwap = !colorSwap;
288      }
289    }
290  }
291
292  function drawEndSprite() {
293    var offsetLeft = cellSize / 50;
294    var offsetRight = cellSize / 25;
295    var coord = Maze.endCoord();
296    ctx.drawImage(
297      endSprite,
298      2,
299      2,
300      endSprite.width,
301      endSprite.height,
302      coord.x * cellSize + offsetLeft,
303      coord.y * cellSize + offsetLeft,
304      cellSize - offsetRight,
305      cellSize - offsetRight
306    );
307  }
308
309  function clear() {
310    var canvasSize = cellSize * map.length;
311    ctx.clearRect(0, 0, canvasSize, canvasSize);
312  }
313
314  if (endSprite != null) {
315    drawEndMethod = drawEndSprite;
316  } else {
317    drawEndMethod = drawEndFlag;
318  }
319  clear();
320  drawMap();
321  drawEndMethod();
322}
323
324function Player(maze, c, _cellsize, onComplete, sprite = null) {
325  var ctx = c.getContext("2d");
326  var drawSprite;
327  var moves = 0;
328  drawSprite = drawSpriteCircle;
329  if (sprite != null) {
330    drawSprite = drawSpriteImg;
331  }
332  var player = this;
333  var map = maze.map();
334  var cellCoords = {
335    x: maze.startCoord().x,
336    y: maze.startCoord().y
337  };
338  var cellSize = _cellsize;
339  var halfCellSize = cellSize / 2;
340
341  this.redrawPlayer = function(_cellsize) {
342    cellSize = _cellsize;
343    drawSpriteImg(cellCoords);
344  };
345
346  function drawSpriteCircle(coord) {
347    ctx.beginPath();
348    ctx.fillStyle = "yellow";
349    ctx.arc(
350      (coord.x + 1) * cellSize - halfCellSize,
351      (coord.y + 1) * cellSize - halfCellSize,
352      halfCellSize - 2,
353      0,
354      2 * Math.PI
355    );
356    ctx.fill();
357    if (coord.x === maze.endCoord().x && coord.y === maze.endCoord().y) {
358      onComplete(moves);
359      player.unbindKeyDown();
360    }
361  }
362
363  function drawSpriteImg(coord) {
364    var offsetLeft = cellSize / 50;
365    var offsetRight = cellSize / 25;
366    ctx.drawImage(
367      sprite,
368      0,
369      0,
370      sprite.width,
371      sprite.height,
372      coord.x * cellSize + offsetLeft,
373      coord.y * cellSize + offsetLeft,
374      cellSize - offsetRight,
375      cellSize - offsetRight
376    );
377    if (coord.x === maze.endCoord().x && coord.y === maze.endCoord().y) {
378      onComplete(moves);
379      player.unbindKeyDown();
380    }
381  }
382
383  function removeSprite(coord) {
384    var offsetLeft = cellSize / 50;
385    var offsetRight = cellSize / 25;
386    ctx.clearRect(
387      coord.x * cellSize + offsetLeft,
388      coord.y * cellSize + offsetLeft,
389      cellSize - offsetRight,
390      cellSize - offsetRight
391    );
392  }
393
394  function check(e) {
395    var cell = map[cellCoords.x][cellCoords.y];
396    moves++;
397    switch (e.keyCode) {
398      case 65:
399      case 37: // west
400        if (cell.w == true) {
401          removeSprite(cellCoords);
402          cellCoords = {
403            x: cellCoords.x - 1,
404            y: cellCoords.y
405          };
406          drawSprite(cellCoords);
407        }
408        break;
409      case 87:
410      case 38: // north
411        if (cell.n == true) {
412          removeSprite(cellCoords);
413          cellCoords = {
414            x: cellCoords.x,
415            y: cellCoords.y - 1
416          };
417          drawSprite(cellCoords);
418        }
419        break;
420      case 68:
421      case 39: // east
422        if (cell.e == true) {
423          removeSprite(cellCoords);
424          cellCoords = {
425            x: cellCoords.x + 1,
426            y: cellCoords.y
427          };
428          drawSprite(cellCoords);
429        }
430        break;
431      case 83:
432      case 40: // south
433        if (cell.s == true) {
434          removeSprite(cellCoords);
435          cellCoords = {
436            x: cellCoords.x,
437            y: cellCoords.y + 1
438          };
439          drawSprite(cellCoords);
440        }
441        break;
442    }
443  }
444
445  this.bindKeyDown = function() {
446    window.addEventListener("keydown", check, false);
447
448    $("#view").swipe({
449      swipe: function(
450        event,
451        direction,
452        distance,
453        duration,
454        fingerCount,
455        fingerData
456      ) {
457        console.log(direction);
458        switch (direction) {
459          case "up":
460            check({
461              keyCode: 38
462            });
463            break;
464          case "down":
465            check({
466              keyCode: 40
467            });
468            break;
469          case "left":
470            check({
471              keyCode: 37
472            });
473            break;
474          case "right":
475            check({
476              keyCode: 39
477            });
478            break;
479        }
480      },
481      threshold: 0
482    });
483  };
484
485  this.unbindKeyDown = function() {
486    window.removeEventListener("keydown", check, false);
487    $("#view").swipe("destroy");
488  };
489
490  drawSprite(maze.startCoord());
491
492  this.bindKeyDown();
493}
494
495var mazeCanvas = document.getElementById("mazeCanvas");
496var ctx = mazeCanvas.getContext("2d");
497var sprite;
498var finishSprite;
499var maze, draw, player;
500var cellSize;
501var difficulty;
502// sprite.src = 'media/sprite.png';
503
504window.onload = function() {
505  let viewWidth = $("#view").width();
506  let viewHeight = $("#view").height();
507  if (viewHeight < viewWidth) {
508    ctx.canvas.width = viewHeight - viewHeight / 100;
509    ctx.canvas.height = viewHeight - viewHeight / 100;
510  } else {
511    ctx.canvas.width = viewWidth - viewWidth / 100;
512    ctx.canvas.height = viewWidth - viewWidth / 100;
513  }
514
515  //Load and edit sprites
516  var completeOne = false;
517  var completeTwo = false;
518  var isComplete = () => {
519    if(completeOne === true && completeTwo === true)
520       {
521         console.log("Runs");
522         setTimeout(function(){
523           makeMaze();
524         }, 500);         
525       }
526  };
527  sprite = new Image();
528  sprite.src =
529    "https://image.ibb.co/dr1HZy/Pf_RWr3_X_Imgur.png" +
530    "?" +
531    new Date().getTime();
532  sprite.setAttribute("crossOrigin", " ");
533  sprite.onload = function() {
534    sprite = changeBrightness(1.2, sprite);
535    completeOne = true;
536    console.log(completeOne);
537    isComplete();
538  };
539
540  finishSprite = new Image();
541  finishSprite.src = "https://image.ibb.co/b9wqnJ/i_Q7m_U25_Imgur.png"+
542  "?" +
543  new Date().getTime();
544  finishSprite.setAttribute("crossOrigin", " ");
545  finishSprite.onload = function() {
546    finishSprite = changeBrightness(1.1, finishSprite);
547    completeTwo = true;
548    console.log(completeTwo);
549    isComplete();
550  };
551  
552};
553
554window.onresize = function() {
555  let viewWidth = $("#view").width();
556  let viewHeight = $("#view").height();
557  if (viewHeight < viewWidth) {
558    ctx.canvas.width = viewHeight - viewHeight / 100;
559    ctx.canvas.height = viewHeight - viewHeight / 100;
560  } else {
561    ctx.canvas.width = viewWidth - viewWidth / 100;
562    ctx.canvas.height = viewWidth - viewWidth / 100;
563  }
564  cellSize = mazeCanvas.width / difficulty;
565  if (player != null) {
566    draw.redrawMaze(cellSize);
567    player.redrawPlayer(cellSize);
568  }
569};
570
571function makeMaze() {
572  //document.getElementById("mazeCanvas").classList.add("border");
573  if (player != undefined) {
574    player.unbindKeyDown();
575    player = null;
576  }
577  var e = document.getElementById("diffSelect");
578  difficulty = e.options[e.selectedIndex].value;
579  cellSize = mazeCanvas.width / difficulty;
580  maze = new Maze(difficulty, difficulty);
581  draw = new DrawMaze(maze, ctx, cellSize, finishSprite);
582  player = new Player(maze, mazeCanvas, cellSize, displayVictoryMess, sprite);
583  if (document.getElementById("mazeContainer").style.opacity < "100") {
584    document.getElementById("mazeContainer").style.opacity = "100";
585  }
586}
587

برای مشاهده نسخه نهایی این بازی به این صفحه (+) مراجعه کنید.

پروژه یازدهم: ساخت محاسبه‌گر انعام با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

گاهی اوقات، به خصوص اگر یک روز طولانی کدنویسی کرده باشید، محاسبه انعام به کاری دشوار تبدیل می‌شود. اگر می‌خواهید مشکل محاسبه انعام به صورت دستی را حل کنید، می‌توانید یک اپلیکیشن محاسبه‌گر انعام با جاوا اسکریپت برای خود بنویسید تا هر زمان که نیاز داشتید از آن استفاده کنید. به علاوه این ابزار موجب می‌شود مشکل اشتباه یا خطا در محاسبات از بین برود.

زمانی که یک محاسبه‌گر ساده انعام ایجاد می‌کنید، همواره می‌توانید قابلیت‌های بیشتری برای افزایش کاربرپسندی آن اضافه کنید. فرض کنید می‌خواهید به خارج از کشور سفر کنید. می‌توانید سطح مناسب انعام را در کشور مقصد به دست آورده و به عنوان یک گزینه به اپلیکیشن خود اضافه کنید.

  • فایل HTML توسعه محاسبه‌گر انعام با جاوا اسکریپت
1<!doctype html>
2<html lang="en">
3  <head>
4    <title>Tip Calculator</title>
5    <!-- Required meta tags -->
6    <meta charset="utf-8">
7    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
8
9    <!-- Bootstrap CSS -->
10    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
11
12  </head>
13  <body class="bg-dark">
14    <div class="container">
15      <div class="row">
16        <div class="col-md-6 mx-auto">
17          <div class="card card-body text-center mt-5">
18            <h1 class="heading display-5 pb-3">Tip Calculator</h1>
19            <form id="tip-form">
20              <div class="form-group">
21                <div class="input-group">
22                  <span class="input-group-addon">$</span>
23                  <input type="number" class="form-control" id="billTotal" placeholder="Total Bill">
24                </div>
25              </div>
26              <div class="form-group tipPersent">
27                <div class="input-group">
28                  <label for="">Tip:</label>
29
30
31                  <input type="range" class="form-control" id="tipInput" value="0">
32                  <span class="input-group-addon" id="tipOutput"></span>
33                </div>
34              </div>
35
36
37
38            </form>
39            <hr>
40
41            <!-- RESULTS -->
42            <div id="results" class="pt-4">
43              <h5>Results</h5>
44              <div class="form-group">
45                <div class="input-group">
46                  <span class="input-group-addon">Tip amount</span>
47                  <input type="number" class="form-control" id="tipAmount" disabled>
48                </div>
49              </div>
50
51              <div class="form-group">
52                <div class="input-group">
53                  <span class="input-group-addon">Total Bill with Tip</span>
54                  <input type="number" class="form-control" id="totalBillWithTip" disabled>
55                </div>
56              </div>
57
58
59            </div>
60          </div>
61        </div>
62      </div>
63    </div>
64
65    <!-- Optional JavaScript -->
66    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
67    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
68    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
69    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
70   
71  </body>
72</html>
  • فایل CSS ساخت محاسبه‌گر انعام با جاوا اسکریپت
1  #results {
2         display:none;
3       }
  • فایل جاوا اسکریپت پروژه کدنویسی محاسبه‌گر انعام با جاوا اسکریپت
1document.querySelector('#tip-form').onchange = function(){
2
3  var bill = Number(document.getElementById('billTotal').value);
4  var tip = document.getElementById('tipInput').value;
5  document.getElementById('tipOutput').innerHTML = `${tip}%`;
6  var tipValue = bill * (tip/100)
7  var finalBill = bill + tipValue
8console.log(finalBill)
9var tipAmount = document.querySelector('#tipAmount')
10var totalBillWithTip = document.querySelector('#totalBillWithTip')
11
12tipAmount.value = tipValue.toFixed(2);
13 totalBillWithTip.value =finalBill.toFixed(2);
14
15 //Show Results
16
17  document.getElementById('results').style.display='block'
18}

برای مشاهده نسخه عملیاتی پروژه یازدهم از آموزش جاوا اسکریپت پروژه محور به این صفحه (+) مراجعه کنید.

پروژه دوازدهم: بررسی PALINDROME با جاوا اسکریپت

PALINDROME یا «جناس قلب» به عبارت یا کلمه‌ای گفته می‌شود که هم از اول به آخر و هم از آخر به اول به طرز یکسانی خوانده می‌شود. ساخت یک بررسی‌‌کننده پالیندروم ایده‌ای عالی برای کار با رشته‌ها و دست‌کاری آن‌ها با جاوا اسکریپت محسوب می‌شود. به علاوه، بررسی پالیندورم سرگرمی بسیار مفرحی نیز محسوب شود. آموزش جاوا اسکریپت پروژه محور را با همین موضوع ادامه می‌دهیم.

  • فایل HTML بررسی PALINDROME با جاوا اسکریپت
1<h2>Javascript Palindrome Checking Function</h2>
  • فایل CSS بررسی PALINDROME با جاوا اسکریپت
1div{margin-top:20px;}
  • فایل جاوا اسکریپت پروژه بررسی PALINDROME با جاوا اسکریپت
1function palindrome(myString){
2
3/* remove special characters, spaces and make lowercase*/
4var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
5
6/* reverse removeChar for comparison*/
7var checkPalindrome = removeChar.split('').reverse().join('');
8
9/* Check to see if myString is a Palindrome*/
10if(removeChar === checkPalindrome){
11  
12  document.write("<div>"+ myString + " is a Palindrome <div>");
13}else{
14  
15  document.write("<div>" + myString + " is not a Palindrome </div>");
16}
17}
18palindrome('"Oh who was it I saw, oh who?"')
19palindrome('"Madam"')
20palindrome('"Star Wars"')
21palindrome('"2,3,4,3,2"')
22palindrome('"7,10,7,8,9"')

برای مشاهده نسخه عملیاتی این پروژه می‌توانید به این صفحه (+) مراجعه کنید.

پروژه سیزدهم: ساخت اپلیکیشن TO-DO با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

جاوا اسکریپت ابزاری شگفت‌انگیز برای ساخت یک اپلیکیشن TO-DO سفارشی محسوب می‌شود. کافی است پروژه را به صورت محدود آغاز کنید و صرفاً امکان افزودن و حذف برخی آیتم‌ها را به آن اضافه کنید.

به مرور که مهارت‌های شما بهبود می‌یابند، می‌توانید To-Do-های خود را به روش کارآمدتری مدیریت کنید. برای نمونه می‌توانید از لیست‌های چندگانه در کنار همدیگر برای دسته‌بندی آیتم‌های TO-DO بهره بگیرید. یک قابلیت بسیار مفید این است که امکان کشیدن و رها کردن را برای جابجایی بین لیست‌ها و ستون‌های مختلف فعال سازید. به این ترتیب وارد پروژه سیزدهم از آموزش جاوا اسکریپت پروژه محور می‌شویم.

  • فایل HTML کدنویسی اپلیکیشن TO-DO با جاوا اسکریپت
1<!--PEN CODE-->
2<div id="tasker" class="tasker">
3	<div id="error" class="error">Please enter a task</div>
4	<div id="tasker-header" class="tasker-header">
5		<input type="text" id="input-task" placeholder="Enter a task">
6		<button id="add-task-btn"><i class="fa fa-fw fa-plus"></i>
7		</button>
8	</div>
9	<div class="tasker-body">
10		<ul id="tasks"></ul>
11	</div>
12</div>
13<!--END PEN CODE-->
  • فایل CSS توسعه اپلیکیشن TO-DO با جاوا اسکریپت
1$primary: #313e50;
2$grey: #cdcdcd;
3$secondary: #1dd2af;
4
5%reset {
6	margin: 0;
7	padding: 0;
8	border: none;
9	outline: none;
10	background: transparent;
11}
12
13%transition {
14	transition: all 0.2s ease;
15	-webkit-transition: all 0.2s ease;
16}
17
18body {
19	background: #f1f1f1;
20	margin-top: 2rem;
21}
22
23/*PEN STYLES*/
24.tasker {
25	max-width: 400px;
26	margin: 0 auto;
27	.error {
28		display: none;
29		background: rgba(237, 28, 36, 0.7);
30		color: #fff;
31		padding: 14px;
32		margin-bottom: 10px;
33		border-radius: 5px;
34		text-align: center;
35	}
36
37	ul {
38		@extend %reset;
39		background: #fff;
40	}
41
42	li,
43	.error,
44	button,
45	input {
46		@extend %reset;
47		font: 18px/1.25em Helvetica, Arial, Sans-serif;
48	}
49}
50
51.tasker-header {
52	display: inline-flex;
53	background: $primary;
54	justify-content: space-between;
55	width: 100%;
56	input,
57	button {
58		color: #fff;
59		box-sizing: border-box;
60		font-size: 1.25em;
61		padding: 14px;
62	}
63
64	input {
65		flex-grow: 2;
66	}
67
68	button {
69		@extend %transition;
70		background: $secondary;
71		border-left: 1px solid ($secondary * 1.05);
72		&:hover {
73			background: $secondary * 1.1;
74		}
75	}
76}
77
78.tasker-body {
79	.task {
80		display: block;
81		position: relative;
82		padding: 14px 40px 14px 14px;
83		border-bottom: 1px solid rgba(0, 0, 0, 0.1);
84		&:last-child {
85			border-bottom: none;
86		}
87
88		&:hover > button {
89			opacity: 1;
90		}
91
92		&.completed {
93			color: $grey;
94			text-decoration: line-through;
95		}
96
97		input {
98			margin-right: 10px;
99		}
100
101		button {
102			@extend %transition;
103			color: $grey;
104			margin: 14px;
105			position: absolute;
106			top: 0;
107			right: 0;
108			opacity: 0;
109			&:hover {
110				color: #ed1c24;
111			}
112		}
113	}
114}
  • فایل جاوا اسکریپت پروژه ساخت اپلیکیشن TO-DO با جاوا اسکریپت
1(function() {
2	'use strict';
3	var tasker = {
4		init: function() {
5			this.cacheDom();
6			this.bindEvents();
7			this.evalTasklist();
8		},
9		cacheDom: function() {
10			this.taskInput = document.getElementById("input-task");
11			this.addBtn = document.getElementById("add-task-btn");
12			this.tasklist = document.getElementById("tasks");
13			this.tasklistChildren = this.tasklist.children;
14			this.errorMessage = document.getElementById("error");
15		},
16		bindEvents: function() {
17			this.addBtn.onclick = this.addTask.bind(this);
18			this.taskInput.onkeypress = this.enterKey.bind(this);
19		},
20		evalTasklist: function() {
21			var i, chkBox, delBtn;
22			//BIND CLICK EVENTS TO ELEMENTS
23			for (i = 0; i < this.tasklistChildren.length; i += 1) {
24				//ADD CLICK EVENT TO CHECKBOXES
25				chkBox = this.tasklistChildren[i].getElementsByTagName("input")[0];
26				chkBox.onclick = this.completeTask.bind(this, this.tasklistChildren[i], chkBox);
27				//ADD CLICK EVENT TO DELETE BUTTON
28				delBtn = this.tasklistChildren[i].getElementsByTagName("button")[0];
29				delBtn.onclick = this.delTask.bind(this, i);
30			}
31		},
32		render: function() {
33			var taskLi, taskChkbx, taskVal, taskBtn, taskTrsh;
34			//BUILD HTML
35			taskLi = document.createElement("li");
36			taskLi.setAttribute("class", "task");
37			//CHECKBOX
38			taskChkbx = document.createElement("input");
39			taskChkbx.setAttribute("type", "checkbox");
40			//USER TASK
41			taskVal = document.createTextNode(this.taskInput.value);
42			//DELETE BUTTON
43			taskBtn = document.createElement("button");
44			//TRASH ICON
45			taskTrsh = document.createElement("i");
46			taskTrsh.setAttribute("class", "fa fa-trash");
47			//INSTERT TRASH CAN INTO BUTTON
48			taskBtn.appendChild(taskTrsh);
49
50			//APPEND ELEMENTS TO TASKLI
51			taskLi.appendChild(taskChkbx);
52			taskLi.appendChild(taskVal);
53			taskLi.appendChild(taskBtn);
54
55			//ADD TASK TO TASK LIST
56			this.tasklist.appendChild(taskLi);
57
58		},
59		completeTask: function(i, chkBox) {
60			if (chkBox.checked) {
61				i.className = "task completed";
62			} else {
63				this.incompleteTask(i);
64			}
65		},
66		incompleteTask: function(i) {
67			i.className = "task";
68		},
69		enterKey: function(event) {
70			if (event.keyCode === 13 || event.which === 13) {
71				this.addTask();
72			}
73		},
74		addTask: function() {
75			var value = this.taskInput.value;
76			this.errorMessage.style.display = "none";
77
78			if (value === "") {
79				this.error();
80			} else {
81				this.render();
82				this.taskInput.value = "";
83				this.evalTasklist();
84			}
85		},
86		delTask: function(i) {
87			this.tasklist.children[i].remove();
88			this.evalTasklist();
89		},
90		error: function() {
91			this.errorMessage.style.display = "block";
92		}
93	};
94
95	tasker.init();
96}());

برای مشاهده نسخه نهایی این پروژه به این صفحه (+) مراجعه کنید.

پروژه چهاردهم: توسعه تایملاین جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

اگر می‌خواهید یک توسعه‌دهنده فرانت‌اند بشوید، می‌توانید کار خود را با ساخت یک تایملاین سفارشی جاوا اسکریپت آغاز کنید. برای نمونه این تایملاین می‌تواند یک قابلیت عالی برای وب‌سایت‌هایی مانند مشتری‌های فریلنس باشد. کسب و ‌کارها و استارتاپ‌ها عموماً از تایملاین برای نمایش مسیر پیشرفت خود و نقاط عطف در وب‌سایت‌هایشان بهره می‌گیرند.

ضمناً می‌توانید از کد تایملاین جاوا اسکریپت خود برای اپلیکیشن‌های مشابه بهره بگیرید. فرض کنید می‌خواهید مراحل مهم یک کار را به بخش‌های با اندازه کوچک برای بازدیدکنندگان وب‌سایت تقسیم کنید. به این منظور می‌توانید کد تایملاین را طوری تغییر دهید که بخش‌های کوچکی از یک داستان را به بازدیدکنندگان وب‌سایت نمایش دهد و به این ترتیب از سردرگم ساختن آن‌ها با اطلاعات بیش از حد جلوگیری کنید.

  • فایل HTML تایملاین جاوا اسکریپت
1<section class="intro">
2  <div class="container">
3    <h1>Vertical Timeline ↓</h1>
4  </div>
5</section>
6
7<section class="timeline">
8  <ul>
9    <li>
10      <div>
11        <time>1934</time> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium
12      </div>
13    </li>
14    <li>
15      <div>
16        <time>1937</time> Proin quam velit, efficitur vel neque vitae, rhoncus commodo mi. Suspendisse finibus mauris et bibendum molestie. Aenean ex augue, varius et pulvinar in, pretium non nisi.
17      </div>
18    </li>
19    <li>
20      <div>
21        <time>1940</time> Proin iaculis, nibh eget efficitur varius, libero tellus porta dolor, at pulvinar tortor ex eget ligula. Integer eu dapibus arcu, sit amet sollicitudin eros.
22      </div>
23    </li>
24    <li>
25      <div>
26        <time>1943</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
27      </div>
28    </li>
29    <li>
30      <div>
31        <time>1946</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
32      </div>
33    </li>
34    <li>
35      <div>
36        <time>1956</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
37      </div>
38    </li>
39    <li>
40      <div>
41        <time>1957</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
42      </div>
43    </li>
44    <li>
45      <div>
46        <time>1967</time> Aenean condimentum odio a bibendum rhoncus. Ut mauris felis, volutpat eget porta faucibus, euismod quis ante.
47      </div>
48    </li>
49    <li>
50      <div>
51        <time>1977</time> Vestibulum porttitor lorem sed pharetra dignissim. Nulla maximus, dui a tristique iaculis, quam dolor convallis enim, non dignissim ligula ipsum a turpis.
52      </div>
53    </li>
54    <li>
55      <div>
56        <time>1985</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
57      </div>
58    </li>
59    <li>
60      <div>
61        <time>2000</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
62      </div>
63    </li>
64    <li>
65      <div>
66        <time>2005</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
67      </div>
68    </li>
69  </ul>
70</section>
  • فایل CSS ساخت تایملاین با جاوا اسکریپت
1*,
2*::before,
3*::after {
4  margin: 0;
5  padding: 0;
6  box-sizing: border-box;
7}
8
9body {
10  font: normal 16px/1.5 "Helvetica Neue", sans-serif;
11  background: #456990;
12  color: #fff;
13  overflow-x: hidden;
14  padding-bottom: 50px;
15}  /* INTRO SECTION
16–––––––––––––––––––––––––––––––––––––––––––––––––– */
17
18.intro {
19  background: #F45B69;
20  padding: 100px 0;
21}
22
23.container {
24  width: 90%;
25  max-width: 1200px;
26  margin: 0 auto;
27  text-align: center;
28}
29
30h1 {
31  font-size: 2.5rem;
32}
33
34
35/* TIMELINE
36–––––––––––––––––––––––––––––––––––––––––––––––––– */
37
38.timeline ul {
39  background: #456990;
40  padding: 50px 0;
41}
42
43.timeline ul li {
44  list-style-type: none;
45  position: relative;
46  width: 6px;
47  margin: 0 auto;
48  padding-top: 50px;
49  background: #fff;
50}
51
52.timeline ul li::after {
53  content: '';
54  position: absolute;
55  left: 50%;
56  bottom: 0;
57  transform: translateX(-50%);
58  width: 30px;
59  height: 30px;
60  border-radius: 50%;
61  background: inherit;
62}
63
64.timeline ul li div {
65  position: relative;
66  bottom: 0;
67  width: 400px;
68  padding: 15px;
69  background: #F45B69;
70}
71
72.timeline ul li div::before {
73  content: '';
74  position: absolute;
75  bottom: 7px;
76  width: 0;
77  height: 0;
78  border-style: solid;
79}
80
81.timeline ul li:nth-child(odd) div {
82  left: 45px;
83}
84
85.timeline ul li:nth-child(odd) div::before {
86  left: -15px;
87  border-width: 8px 16px 8px 0;
88  border-color: transparent #F45B69 transparent transparent;
89}
90
91.timeline ul li:nth-child(even) div {
92  left: -439px;
93}
94
95.timeline ul li:nth-child(even) div::before {
96  right: -15px;
97  border-width: 8px 0 8px 16px;
98  border-color: transparent transparent transparent #F45B69;
99}
100
101time {
102  display: block;
103  font-size: 1.2rem;
104  font-weight: bold;
105  margin-bottom: 8px;
106}
107
108
109/* EFFECTS
110–––––––––––––––––––––––––––––––––––––––––––––––––– */
111
112.timeline ul li::after {
113  transition: background .5s ease-in-out;
114}
115
116.timeline ul li.in-view::after {
117  background: #F45B69;
118}
119
120.timeline ul li div {
121  visibility: hidden;
122  opacity: 0;
123  transition: all .5s ease-in-out;
124}
125
126.timeline ul li:nth-child(odd) div {
127  transform: translate3d(200px, 0, 0);
128}
129
130.timeline ul li:nth-child(even) div {
131  transform: translate3d(-200px, 0, 0);
132}
133
134.timeline ul li.in-view div {
135  transform: none;
136  visibility: visible;
137  opacity: 1;
138}
139
140
141/* GENERAL MEDIA QUERIES
142–––––––––––––––––––––––––––––––––––––––––––––––––– */
143
144@media screen and (max-width: 900px) {
145  .timeline ul li div {
146    width: 250px;
147  }
148  .timeline ul li:nth-child(even) div {
149    left: -289px;
150    /*250+45-6*/
151  }
152}
153
154@media screen and (max-width: 600px) {
155  .timeline ul li {
156    margin-left: 20px;
157  }
158  .timeline ul li div {
159    width: calc(100vw - 91px);
160  }
161  .timeline ul li:nth-child(even) div {
162    left: 45px;
163  }
164  .timeline ul li:nth-child(even) div::before {
165    left: -15px;
166    border-width: 8px 16px 8px 0;
167    border-color: transparent #F45B69 transparent transparent;
168  }
169}
  • فایل جاوا اسکریپت پروژه توسعه تایملاین با جاوا اسکریپت
1(function() {
2
3  'use strict';
4
5  // define variables
6  var items = document.querySelectorAll(".timeline li");
7
8  // check if an element is in viewport
9  // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
10  function isElementInViewport(el) {
11    var rect = el.getBoundingClientRect();
12    return (
13      rect.top >= 0 &&
14      rect.left >= 0 &&
15      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
16      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
17    );
18  }
19
20  function callbackFunc() {
21    for (var i = 0; i < items.length; i++) {
22      if (isElementInViewport(items[i])) {
23        items[i].classList.add("in-view");
24      }
25    }
26  }
27
28  // listen for events
29  window.addEventListener("load", callbackFunc);
30  window.addEventListener("resize", callbackFunc);
31  window.addEventListener("scroll", callbackFunc);
32
33})();

برای مشاهده نسخه عملیاتی این پروژه به این صفحه (+) مراجعه کنید.

پروژه پانزدهم: ساخت یک اپلیکیشن آزمون با جاوا اسکریپت

راهنمای پروژه محور جاوا اسکریپت

همه افراد از یک آزمون خوب لذت می‌برند. ساخت یک اپلیکیشن کوچک آزمون با استفاده از جاوا اسکریپت کار آسانی محسوب می‌شود و می‌تواند کمک بزرگی در مسیر یادگیری این زبان باشد.

اگر می‌خواهید از راه فریلنسری کسب درآمد بکنید، می‌توانید یک وب‌سایت پورتفولیو بسازید که پروژه‌هایتان را نمایش می‌دهد. همچنین از یک آزمون در سایت استفاده کنید تا مشتری‌های بالقوه بتوانند سرویس‌های مناسب خود را پیدا کنند.

همچنین اگر یک بلاگ در مورد برنامه‌نویسی داشته باشید، می‌توانید به خوانندگان خود در یافتن منابع مناسب برای آموزش کمک کنید. به این منظور کافی است یک آزمون کوچک ایجاد کنید تا اهداف و مسیر افراد را از طریق آن‌ها مشخص ساخته و راهنماها و نوشته‌های مناسب را در اختیار ایشان قرار دهید.

  • فایل HTML توسعه اپلیکیشن آزمون با جاوا اسکریپت
1<!DOCTYPE html>
2<html>
3	<head>
4		<title>Dynamic Quiz Project</title>
5		<link type='text/css' rel='stylesheet' href='stylesheet.css'/>
6		<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open Sans"/>
7	</head>
8	<body>
9		<div id='container'>
10			<div id='title'>
11				<h1>Learning Js Properly: Project #1 - Dynamic Quiz</h1>
12			</div>
13   			<br/>
14  			<div id='quiz'></div>
15    		<div class='button' id='next'><a href='#'>Next</a></div>
16    		<div class='button' id='prev'><a href='#'>Prev</a></div>
17    		<div class='button' id='start'> <a href='#'>Start Over</a></div>
18    		<!-- <button class='' id='next'>Next</a></button>
19    		<button class='' id='prev'>Prev</a></button>
20    		<button class='' id='start'> Start Over</a></button> -->
21    	</div>
22
23		<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
24		<script type="text/javascript" src='questions.json'></script>
25		<script type='text/javascript' src='jsquiz.js'></script>
26	</body>
27</html>
  • فایل CSS توسعه اپلیکیشن آزمون با جاوا اسکریپت
1body {
2    font-family: Open Sans;
3}
4
5h1 {
6    text-align: center;
7}
8
9#title {
10    text-decoration: underline;
11}
12
13#quiz {
14    text-indent: 10px;
15    display:none;
16}
17
18.button {
19    border:4px solid;
20    border-radius:5px;
21    width: 40px;
22    padding-left:5px;
23    padding-right: 5px;
24    position: relative;
25    float:right;
26    background-color: #DCDCDC;
27    color: black;
28    margin: 0 2px 0 2px;
29}
30
31.button.active {
32    background-color: #F8F8FF;
33    color: #525252;
34}
35
36button {
37    position: relative;
38    float:right;
39}
40
41.button a {
42    text-decoration: none;
43    color: black;
44}
45
46#container {
47    width:50%;
48    margin:auto;
49    padding: 0 25px 40px 10px;
50    background-color: #1E90FF;
51    border:4px solid #B0E0E6;
52    border-radius:5px;
53    color: #FFFFFF;
54    font-weight: bold;
55    box-shadow: 5px 5px 5px #888;
56}
57
58ul {
59    list-style-type: none;
60    padding: 0;
61    margin: 0;
62}
63
64#prev {
65    display:none;
66}
67
68#start {
69    display:none;
70    width: 90px;
71}
  • فایل جاوا اسکریپت پروژه ساخت اپلیکیشن آزمون با جاوا اسکریپت
1(function() {
2  var questions = [{
3    question: "What is 2*5?",
4    choices: [2, 5, 10, 15, 20],
5    correctAnswer: 2
6  }, {
7    question: "What is 3*6?",
8    choices: [3, 6, 9, 12, 18],
9    correctAnswer: 4
10  }, {
11    question: "What is 8*9?",
12    choices: [72, 99, 108, 134, 156],
13    correctAnswer: 0
14  }, {
15    question: "What is 1*7?",
16    choices: [4, 5, 6, 7, 8],
17    correctAnswer: 3
18  }, {
19    question: "What is 8*8?",
20    choices: [20, 30, 40, 50, 64],
21    correctAnswer: 4
22  }];
23  
24  var questionCounter = 0; //Tracks question number
25  var selections = []; //Array containing user choices
26  var quiz = $('#quiz'); //Quiz div object
27  
28  // Display initial question
29  displayNext();
30  
31  // Click handler for the 'next' button
32  $('#next').on('click', function (e) {
33    e.preventDefault();
34    
35    // Suspend click listener during fade animation
36    if(quiz.is(':animated')) {        
37      return false;
38    }
39    choose();
40    
41    // If no user selection, progress is stopped
42    if (isNaN(selections[questionCounter])) {
43      alert('Please make a selection!');
44    } else {
45      questionCounter++;
46      displayNext();
47    }
48  });
49  
50  // Click handler for the 'prev' button
51  $('#prev').on('click', function (e) {
52    e.preventDefault();
53    
54    if(quiz.is(':animated')) {
55      return false;
56    }
57    choose();
58    questionCounter--;
59    displayNext();
60  });
61  
62  // Click handler for the 'Start Over' button
63  $('#start').on('click', function (e) {
64    e.preventDefault();
65    
66    if(quiz.is(':animated')) {
67      return false;
68    }
69    questionCounter = 0;
70    selections = [];
71    displayNext();
72    $('#start').hide();
73  });
74  
75  // Animates buttons on hover
76  $('.button').on('mouseenter', function () {
77    $(this).addClass('active');
78  });
79  $('.button').on('mouseleave', function () {
80    $(this).removeClass('active');
81  });
82  
83  // Creates and returns the div that contains the questions and 
84  // the answer selections
85  function createQuestionElement(index) {
86    var qElement = $('<div>', {
87      id: 'question'
88    });
89    
90    var header = $('<h2>Question ' + (index + 1) + ':</h2>');
91    qElement.append(header);
92    
93    var question = $('<p>').append(questions[index].question);
94    qElement.append(question);
95    
96    var radioButtons = createRadios(index);
97    qElement.append(radioButtons);
98    
99    return qElement;
100  }
101  
102  // Creates a list of the answer choices as radio inputs
103  function createRadios(index) {
104    var radioList = $('<ul>');
105    var item;
106    var input = '';
107    for (var i = 0; i < questions[index].choices.length; i++) {
108      item = $('<li>');
109      input = '<input type="radio" name="answer" value=' + i + ' />';
110      input += questions[index].choices[i];
111      item.append(input);
112      radioList.append(item);
113    }
114    return radioList;
115  }
116  
117  // Reads the user selection and pushes the value to an array
118  function choose() {
119    selections[questionCounter] = +$('input[name="answer"]:checked').val();
120  }
121  
122  // Displays next requested element
123  function displayNext() {
124    quiz.fadeOut(function() {
125      $('#question').remove();
126      
127      if(questionCounter < questions.length){
128        var nextQuestion = createQuestionElement(questionCounter);
129        quiz.append(nextQuestion).fadeIn();
130        if (!(isNaN(selections[questionCounter]))) {
131          $('input[value='+selections[questionCounter]+']').prop('checked', true);
132        }
133        
134        // Controls display of 'prev' button
135        if(questionCounter === 1){
136          $('#prev').show();
137        } else if(questionCounter === 0){
138          
139          $('#prev').hide();
140          $('#next').show();
141        }
142      }else {
143        var scoreElem = displayScore();
144        quiz.append(scoreElem).fadeIn();
145        $('#next').hide();
146        $('#prev').hide();
147        $('#start').show();
148      }
149    });
150  }
151  
152  // Computes score and returns a paragraph element to be displayed
153  function displayScore() {
154    var score = $('<p>',{id: 'question'});
155    
156    var numCorrect = 0;
157    for (var i = 0; i < selections.length; i++) {
158      if (selections[i] === questions[i].correctAnswer) {
159        numCorrect++;
160      }
161    }
162    
163    score.append('You got ' + numCorrect + ' questions out of ' +
164                 questions.length + ' right!!!');
165    return score;
166  }
167})();

سخن پایانی

اگر می‌خواهید مسیر شغلی خود را به عنوان یک توسعه‌دهنده وب آغاز کنید، ‌بهترین کار برای یادگیری خوب زبان جاوا اسکریپت، ساخت پروژه‌های کوچک است. کار کردن روی پروژه‌های شخصی موجب می‌شود که درکی از طرز کار ساختار این زبان پیدا کنید و بتوانید مسائل مختلف را با آن حل کنید.

زمانی که شروع به یادگیری جاوا اسکریپت می‌کنید و نخستین پروژه سطح مبتدی خود را به پایان می‌برید، به میزان زیادی اعتماد به نفستان برای کار کردن به صورت مستقل افزایش می‌یابد. همچنین ایده‌های سرگرم‌کننده زیادی برای ادامه مسیر یادگیری پیدا می‌کنید. به این ترتیب آموزش جاوا اسکریپت پروژه محور را به پایان می‌بریم اما می‌تونید در مجله فرادرس مقالات و آموزش‌های مرتبط متعددی را در رابطه با این زبان برنامه‌نویسی مطالعه کنید.

بر اساس رای ۱۸ نفر
آیا این مطلب برای شما مفید بود؟
اگر بازخوردی درباره این مطلب دارید یا پرسشی دارید که بدون پاسخ مانده است، آن را از طریق بخش نظرات مطرح کنید.
منابع:
tutorialspointmikkegoes
۲ دیدگاه برای «آموزش جاوا اسکریپت پروژه محور | ۱۵ پروژه عملی و کاربردی»

خیلی عالی بود

خیلی عالی بودن
دمت گرم

نظر شما چیست؟

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *