├── .editorconfig ├── .eslintrc.json ├── .github └── workflows │ └── gatsby.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── csv.js ├── gatsby-config.js ├── gatsby-node.js ├── lessons ├── build-process.md ├── code-formatting.md ├── code-style.md ├── conclusion.md ├── death.md ├── editor-setup.md ├── hello-world.md ├── images │ ├── FrontendMastersLogo.png │ └── brian.jpg ├── init.md ├── interacting-with-the-ui.md ├── intro.md ├── linting.md ├── organization.md ├── pooping.md ├── some-ui.md ├── state-machine.md ├── testing.md ├── the-project.md ├── the-states.md ├── transitioning-between-states.md └── type-checking.md ├── package-lock.json ├── package.json └── src ├── components ├── TOCCard.css └── TOCCard.js ├── layouts ├── index.css └── index.js ├── pages ├── 404.js ├── index.css └── index.js ├── templates └── lessonTemplate.js └── util └── helpers.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "eslint:recommended", 4 | "plugin:import/errors", 5 | "plugin:react/recommended", 6 | "plugin:jsx-a11y/recommended", 7 | "prettier", 8 | "prettier/react" 9 | ], 10 | "rules": { 11 | "react/prop-types": 0, 12 | "jsx-a11y/label-has-for": 0, 13 | "no-console": 1 14 | }, 15 | "plugins": ["react", "import", "jsx-a11y"], 16 | "parser": "babel-eslint", 17 | "parserOptions": { 18 | "ecmaVersion": 2018, 19 | "sourceType": "module", 20 | "ecmaFeatures": { 21 | "jsx": true 22 | } 23 | }, 24 | "env": { 25 | "es6": true, 26 | "browser": true, 27 | "node": true 28 | }, 29 | "settings": { 30 | "react": { 31 | "version": "16.5.2" 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.github/workflows/gatsby.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Gatsby Site to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@master 13 | - name: npm install and build 14 | run: | 15 | npm install 16 | npm run build 17 | - name: Deploy 🚀 18 | uses: JamesIves/github-pages-deploy-action@4.1.5 19 | with: 20 | branch: gh-pages 21 | folder: public 22 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Project dependencies 2 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 3 | node_modules 4 | .cache/ 5 | # Build directory 6 | public/ 7 | .DS_Store 8 | yarn-error.log 9 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial 4.0 International 4 | 5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 10 | 11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 12 | 13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 14 | 15 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 26 | 27 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 28 | 29 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 30 | 31 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 32 | 33 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 34 | 35 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 36 | 37 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 38 | 39 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 40 | 41 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 42 | 43 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 44 | 45 | ### Section 2 – Scope. 46 | 47 | a. ___License grant.___ 48 | 49 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 50 | 51 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 52 | 53 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 54 | 55 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 56 | 57 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 58 | 59 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 60 | 61 | 5. __Downstream recipients.__ 62 | 63 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 64 | 65 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 66 | 67 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 68 | 69 | b. ___Other rights.___ 70 | 71 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 72 | 73 | 2. Patent and trademark rights are not licensed under this Public License. 74 | 75 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 76 | 77 | ### Section 3 – License Conditions. 78 | 79 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 80 | 81 | a. ___Attribution.___ 82 | 83 | 1. If You Share the Licensed Material (including in modified form), You must: 84 | 85 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 86 | 87 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 88 | 89 | ii. a copyright notice; 90 | 91 | iii. a notice that refers to this Public License; 92 | 93 | iv. a notice that refers to the disclaimer of warranties; 94 | 95 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 96 | 97 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 98 | 99 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 100 | 101 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 102 | 103 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 104 | 105 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 106 | 107 | ### Section 4 – Sui Generis Database Rights. 108 | 109 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 110 | 111 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 112 | 113 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 114 | 115 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 116 | 117 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 118 | 119 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 120 | 121 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 122 | 123 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 124 | 125 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 126 | 127 | ### Section 6 – Term and Termination. 128 | 129 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 130 | 131 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 132 | 133 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 134 | 135 | 2. upon express reinstatement by the Licensor. 136 | 137 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 138 | 139 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 140 | 141 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 142 | 143 | ### Section 7 – Other Terms and Conditions. 144 | 145 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 146 | 147 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 148 | 149 | ### Section 8 – Interpretation. 150 | 151 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 152 | 153 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 154 | 155 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 156 | 157 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 158 | 159 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 160 | > 161 | > Creative Commons may be contacted at creativecommons.org -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Complete Front-End Project: Build a Game


2 | 3 |

4 | As taught by Brian Holt for Frontend Masters 5 |

6 | 7 |

8 | 📝 Course Website: Complete Front-End Project - Build a Game 9 |

10 | 11 | Fly through code faster than you thought possible using VIM! You’ll learn the basics of editing and even know how to exit VIM. Go deeper with navigation, macros, registers, find, and replaces. Then edit your vimrc plugins along with quickfix lists. Lastly, see ThePrimeagen demonstrate his ideal VIM workflow. 12 | 13 | ## License 14 | 15 | The **code** is this repo is licensed under the Apache 2.0 license. 16 | 17 | The **content** is this repo is licensed under the CC-BY-NC-4.0 license. 18 | 19 | # Project Fox Game 20 | 21 | This is the site behind the course for Brian Holt's Let's-Build-a-Game for Frontend Masters. 22 | 23 | - You can see [the course website here][website]. 24 | - You can see [the finished version of the game here][game]. 25 | - You can see [the project files here][projects]. 26 | - You can see [Complete Front-End Project: Build a Game course videos here][course]. 27 | 28 | Please file issues here. PRs are welcome for content, grammar, and spelling. 29 | 30 | All example code is licensed under Apache 2.0. All content is licensed under CC-BY-NC-4.0. 31 | 32 | [course]: https://frontendmasters.com/courses/front-end-game/ 33 | [website]: https://btholt.github.io/project-fox-game-site/ 34 | [game]: https://btholt.github.io/project-files-for-fox-game/ 35 | [projects]: https://github.com/btholt/project-files-for-fox-game 36 | [fem]: https://frontendmasters.com/ 37 | -------------------------------------------------------------------------------- /csv.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs").promises; 2 | const path = require("path"); 3 | const fm = require("front-matter"); 4 | const isUrl = require("is-url-superb"); 5 | const parseLinks = require("parse-markdown-links"); 6 | const { sorter } = require("./src/util/helpers"); 7 | const mdDir = process.env.MARKDOWN_DIR || path.join(__dirname, "lessons/"); 8 | const outputPath = 9 | process.env.OUTPUT_CSV_PATH || path.join(__dirname, "public/lessons.csv"); 10 | const linksOutputPath = 11 | process.env.LINKS_CSV_PATH || path.join(__dirname, "public/links.csv"); 12 | 13 | async function createCsv() { 14 | console.log(`making the markdown files into a CSV from ${mdDir}`); 15 | 16 | // get paths 17 | const allFiles = await fs.readdir(mdDir); 18 | const files = allFiles.filter(filePath => filePath.endsWith(".md")); 19 | 20 | // read paths, get buffers 21 | const buffers = await Promise.all( 22 | files.map(filePath => fs.readFile(path.join(mdDir, filePath))) 23 | ); 24 | 25 | // make buffers strings 26 | const contents = buffers.map(content => content.toString()); 27 | 28 | // make strings objects 29 | let frontmatters = contents.map(fm); 30 | 31 | // find all attribute keys 32 | const seenAttributes = new Set(); 33 | frontmatters.forEach(item => { 34 | Object.keys(item.attributes).forEach(attr => seenAttributes.add(attr)); 35 | }); 36 | const attributes = Array.from(seenAttributes.values()); 37 | 38 | if (attributes.includes("order")) { 39 | frontmatters = frontmatters.sort(sorter); 40 | } 41 | 42 | // get all data into an array 43 | let rows = frontmatters.map(item => { 44 | const row = attributes.map(attr => 45 | item.attributes[attr] ? JSON.stringify(item.attributes[attr]) : "" 46 | ); 47 | return row; 48 | }); 49 | 50 | // header row must be first row 51 | rows.unshift(attributes); 52 | 53 | // join into CSV string 54 | const csv = rows.map(row => row.join(",")).join("\n"); 55 | 56 | // write file out 57 | await fs.writeFile(outputPath, csv); 58 | 59 | console.log(`Wrote ${rows.length} rows to ${outputPath}`); 60 | 61 | // make links csv 62 | let longestLength = 0; 63 | let linksArray = frontmatters.map(row => { 64 | const links = parseLinks(row.body).filter(isUrl); 65 | longestLength = longestLength > links.length ? longestLength : links.length; 66 | const newRow = [row.attributes.order, row.attributes.title, ...links]; 67 | return newRow; 68 | }); 69 | 70 | if (longestLength) { 71 | // add title row 72 | linksArray = linksArray.map(array => { 73 | const lengthToFill = longestLength + 2 - array.length; 74 | return array.concat(Array.from({ length: lengthToFill }).fill("")); 75 | }); 76 | 77 | linksArray.unshift( 78 | ["order", "title"].concat( 79 | Array.from({ length: longestLength }).map((_, index) => `link${index}`) 80 | ) 81 | ); 82 | 83 | // join into CSV string 84 | const linksCsv = linksArray.map(row => row.join(",")).join("\n"); 85 | 86 | // write file out 87 | await fs.writeFile(linksOutputPath, linksCsv); 88 | 89 | console.log(`Wrote ${linksArray.length} rows to ${linksOutputPath}`); 90 | } 91 | } 92 | 93 | createCsv(); 94 | -------------------------------------------------------------------------------- /gatsby-config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | siteMetadata: { 3 | title: "Project Fox Game", 4 | subtitle: "Making a game together", 5 | description: 6 | "A brief course where we use JavaScript, HTML, and CSS to make a digital pet staring our little fox friend.", 7 | keywords: [ 8 | "javascript", 9 | "digital pet", 10 | "typescript", 11 | "frontend", 12 | "css", 13 | "html", 14 | "project", 15 | "pair coding" 16 | ] 17 | }, 18 | pathPrefix: "/project-fox-game-site", 19 | plugins: [ 20 | `gatsby-plugin-sharp`, 21 | `gatsby-plugin-layout`, 22 | { 23 | resolve: `gatsby-source-filesystem`, 24 | options: { 25 | path: `${__dirname}/lessons`, 26 | name: "markdown-pages" 27 | } 28 | }, 29 | `gatsby-plugin-react-helmet`, 30 | { 31 | resolve: `gatsby-transformer-remark`, 32 | options: { 33 | plugins: [ 34 | `gatsby-remark-autolink-headers`, 35 | `gatsby-remark-copy-linked-files`, 36 | `gatsby-remark-prismjs`, 37 | { 38 | resolve: `gatsby-remark-images`, 39 | options: { 40 | maxWidth: 800, 41 | linkImagesToOriginal: true, 42 | sizeByPixelDensity: false 43 | } 44 | } 45 | ] 46 | } 47 | } 48 | ] 49 | }; 50 | -------------------------------------------------------------------------------- /gatsby-node.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | 3 | exports.createPages = ({ actions, graphql }) => { 4 | const { createPage } = actions; 5 | 6 | const lessonTemplate = path.resolve(`src/templates/lessonTemplate.js`); 7 | 8 | return graphql(` 9 | { 10 | allMarkdownRemark( 11 | sort: { order: DESC, fields: [frontmatter___order] } 12 | limit: 1000 13 | ) { 14 | edges { 15 | node { 16 | excerpt(pruneLength: 250) 17 | html 18 | id 19 | frontmatter { 20 | order 21 | path 22 | title 23 | } 24 | } 25 | } 26 | } 27 | } 28 | `).then(result => { 29 | if (result.errors) { 30 | return Promise.reject(result.errors); 31 | } 32 | 33 | result.data.allMarkdownRemark.edges.forEach(({ node }) => { 34 | createPage({ 35 | path: node.frontmatter.path, 36 | component: lessonTemplate 37 | }); 38 | }); 39 | }); 40 | }; 41 | -------------------------------------------------------------------------------- /lessons/build-process.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/build-process" 3 | title: "Build Process" 4 | order: "2B" 5 | description: "The Project" 6 | section: "Frontend Infra" 7 | --- 8 | 9 | We need to first decide how we're going to structure the project. The whole game could conceivably all fit in one file and that wouldn't be the end of the world. Not recommended, but not the worst. 10 | 11 | We then need to split up the game into multiple files. In order to do that, we need some sort of strategy to bundle our app. Until quite recently, browsers didn't know how to eloquently handle multiple files being downloaded for a project. We could have made multiple JS files and put multiple `` in there. This will let Parcel know that this is the entry to your JS app. You won't have to do this again. 44 | 45 | If you try to run your code right now, it's very likely you'll get a gross error saying `regeneratorRuntime is not defined`. We need to tell Babel (which Parcel uses under the hood) to not transpile our `async` call and to leave it as async since modern Edge/Firefox/Safari/Chrome can understand async/await. So head to your package.json and add this: 46 | 47 | ```json 48 | { 49 | […] 50 | "browserslist": [ 51 | "last 2 Firefox versions" 52 | ] 53 | } 54 | ``` 55 | 56 | This lets Babel know to just make this project work for the last two versions of Firefox and to not transpile things that would work in Firefox. You can use Chrome too. Go ahead and run `rm -rf .cache dist` in your project. When you change configurations, Parcel doesn't always grasp it. Just do it to be safe; your project will take an extra second to compile but it should work now. 57 | 58 | Now you should see it ticking every three seconds! This give us a nice frame to work with! 59 | -------------------------------------------------------------------------------- /lessons/interacting-with-the-ui.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/interacting-with-the-ui" 3 | title: "Interacting with the UI" 4 | order: "4B" 5 | description: "The Project" 6 | section: "The Game" 7 | --- 8 | 9 | We have two distinct sorts of logic that we want to keep separated from each other: UI logic (button clicks, hover events, DOM stuff, etc.) and business logic (the clock, the state machine, all the actual logic behind the game.) In this part, we're going to do the UI logic and then we'll add a way for the UI to call into the business logic. 10 | 11 | Add a new file called button.js. 12 | 13 | ```javascript 14 | import { ICONS } from "./constants"; 15 | 16 | const toggleHighlighted = (icon, show) => 17 | document 18 | .querySelector(`.${ICONS[icon]}-icon`) 19 | .classList.toggle("highlighted", show); 20 | 21 | export default function initButtons(handleUserAction) { 22 | let selectedIcon = 0; 23 | function buttonClick({ target }) { 24 | if (target.classList.contains("left-btn")) { 25 | toggleHighlighted(selectedIcon, false); 26 | selectedIcon = (2 + selectedIcon) % ICONS.length; 27 | toggleHighlighted(selectedIcon, true); 28 | } else if (target.classList.contains("right-btn")) { 29 | toggleHighlighted(selectedIcon, false); 30 | selectedIcon = (1 + selectedIcon) % ICONS.length; 31 | toggleHighlighted(selectedIcon, true); 32 | } else { 33 | handleUserAction(ICONS[selectedIcon]); 34 | document.querySelector(".buttons").addEventListener("click", buttonClick); 35 | } 36 | ``` 37 | 38 | Pretty dumb UI plumbing here. We're being a bit clever with the toggleHighlighted by using a ternary but I'm fine with this. It's a one liner function that I don't think is too much served by being any more verbose than this. However I wouldn't put this in the middle of a function. 39 | 40 | This is using the modulo (`%`) operator to wrap the button pushes. If some one clicks left on the first button, it wraps to the last button. I use the +2 and +1 because that fits my brain better but you could use subtraction as well. 41 | 42 | Let's go make that very brief constants.js file. 43 | 44 | ```javascript 45 | export const ICONS = ["fish", "poop", "weather"]; 46 | export const TICK_RATE = 3000; 47 | ``` 48 | 49 | Now we can have one source of truth for our constants. We're also moving `TICK_RATE` here so it's easy to modify later if we choose to. 50 | 51 | Let's go init our buttons. 52 | 53 | ```javascript 54 | // at top 55 | import initButtons from "./buttons"; 56 | 57 | // replace TICK_RATE 58 | import { TICK_RATE } from "./constants"; 59 | 60 | // first line of init() 61 | initButtons(game.handleUserAction); 62 | ``` 63 | 64 | And lastly, let's put in a placeholder for the `handleUserAction` in gameState.js 65 | 66 | ```javascript 67 | // last function in gameState 68 | handleUserAction(icon) { 69 | console.log(icon); 70 | }, 71 | ``` 72 | 73 | This should be all plumbed up now. Head over to your game and try playing around with the buttons! It should log out when you click the middle button and the button highlights should work correctly. 74 | 75 | [We've reached the ui-interaction milestone][ui]. 76 | 77 | [ui]: https://github.com/btholt/project-files-for-fox-game/tree/master/ui-interaction 78 | -------------------------------------------------------------------------------- /lessons/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/intro" 3 | title: "Introduction" 4 | order: "1A" 5 | section: "Welcome" 6 | description: "Brian Holt lays out the course objectives, his background, and where to file issues with the course as well as why he created this course: he believes that containers are going to be important to every developer going forward." 7 | --- 8 | 9 | ## Course Objective 10 | 11 | Hello! And welcome to the Fox Game Project course! The objective of this course is to give you a peak into how I solve problems. I've been a professional developer for over a decade and coding much longer than that. I'm not saying I'm the best dev or even necessarily one you want model your own thinking after, but I do believe I'm an efficient developer who regularly ships good code. Hopefully along the way you can pick up some different ways of approaching problems and that can help you sharpen your own way of thinking about writing code. 12 | 13 | This course isn't intended to teach you anything new. That is to say, the objective of this course is take code skills you have and apply them to building a project, one that we'll build together along the way. I'm sure some of the things I show you along the way will be helpful and I'll be sure to explain things along the way, but the purpose here is for you and me to pair code a new project along the way. 14 | 15 | Let's have fun! 16 | 17 | ## Who Are You? 18 | 19 | You are a frontend developer. 20 | 21 | This course isn't intended to teach how to become a frontend developer, there two courses on Frontend Masters I'd recommend you look at for that: [the Bootcamp][bootcamp] and [Intro to Web Dev v2][web-dev], both courses with me as a teacher (the Bootcamp has the amazing Jen Kramer, too.) 22 | 23 | So you should have a beginner level grasp at least of HTML, JavaScript, and CSS. If you don't feel comfortable yet with any or all of those, please take one of the above courses first; you'll get more out of this course then. If you've used Node.js to use tools (like Webpack or TypeScript) before, that'll help too. We'll only lightly dabble with those tools, so it's okay if this will be your first time with them. 24 | 25 | ## Set Up Instructions 26 | 27 | Before we get off to the races, I have a few things I would love for you to set up. 28 | 29 | 1. [Install Node.js][nodejs]. This lists many ways of installing Node.js and it's up to you which one to choose. I use [nvm][nvm]. 30 | 1. [Install Visual Studio Code][vscode]! This is optional, obviously, but I'll be sharing a lot about VSCode as we go, and who knows, if you're not using it already you might like it! 31 | 32 | ## Font, Theme, and Prompt 33 | 34 | I use [Dank Mono][dank] with [ligatures enabled][ligatures] and the default Dark+ theme for VSCode. For my shell, I use zsh with the [Spaceship ZSH][spaceship] prompt. I did pay for the Dank font (years ago, still use it and love it so totally worth it) but I know not everyone wants to pay for a font. [Cascadia Code][cascadia] from Microsoft is a great free code font with ligatures and what I use in the terminal. 35 | 36 | ## Where to File Issues 37 | 38 | I write these courses and take care to not make mistakes. However when teaching hours of material, mistakes are inevitable, both here in the grammar and in the course with the material. However I (and the wonderful team at Frontend Masters) are constantly correcting the mistakes so that those of you that come later get the best product possible. If you find a mistake we'd love to fix it. The best way to do this is to open a pull request or [file an issue][issue] on the GitHub repo. While I'm always happy to chat and give advice on social media, I can't be tech support for everyone. And if you file it on GitHub, those who come later can Google the same answer you got. 39 | 40 | ## Who Am I? 41 | 42 | ![Brian drinking a beer](images/brian.jpg) 43 | 44 | My name is Brian Holt. I'm presently (as of writing) a senior program manager over [Visual Studio Code][vscode] and JavaScript on Azure at Microsoft. That means I'm trying to make Azure a place you want to deploy your code and VSCode the best tool to write code with. I've taught a lot of lessons on [Frontend Masters][frontend-masters] and used to be on the frontend development podcast [Front End Happy Hour][fehh]. Previous to that, I was a cloud advocate for Microsoft and a staff JavaScript / Node.js engineer at LinkedIn, Netflix, Reddit, Needle, KSL.com, and NuSkin. I'm also stoked to be a board member of the amazing organization [Vets Who Code][vwc]. 45 | 46 | My biggest passions in life are people and experiences. I hope by going through this course that it can improve your life in some meaningful way and that you in turn can improve someone else's life. My beautiful wife and I live in Seattle, Washington in the United States of America with our cute little Havanese dog Luna. I'd almost always rather be traveling and have been fortunate to see over forty countries in the past six years. 47 | 48 | Please catch up with me on social media, would love to chat: 49 | 50 | - [Twitter][twitter] 51 | - [GitHub][github] 52 | - [LinkedIn][linkedin] 53 | 54 | ## Why was this course created? 55 | 56 | ![Frontend Masters Logo](images/FrontendMastersLogo.png) 57 | 58 | I love to teach. It's a challenging task that forces you to peel back all the knowledge you've gained so you can approach someone who lacks the same experience and terminology you have. It forces you to take amorphous concepts floating in your brain and crystalize them into solid concepts that you can describe. It forces you to acknowledge your gaps in knowledge because you'll begin to question things you know others will question. For me to ever master a concept, I have to teach it to someone else. 59 | 60 | Unfortunately life gets in the way. These courses take dozens of hours to prepare and to get right. While I'd love to just create content all day, I have a (awesome) day job at Microsoft that demands and deserves my full attention. However I'm grateful to the team at [Frontend Masters][fem] for giving me deadlines and incentive to create these courses and then allowing and encouraging me to open source the materials. Not everyone has the money to pay for these courses which is why these materials are and will be forever open source for you to reference and share. I think the video content is pretty good too and so I'd encourage you to [take a look at the videos on Frontend Masters][course] too if that's in the cards for you. 61 | 62 | And hey, if you could take a second and [star the repo on GitHub][gh] I'd be super appreciative. It helps me reach more people. 63 | 64 | [gh]: https://github.com/btholt/project-fox-game-site 65 | [frontend-masters]: https://frontendmasters.com/teachers/brian-holt/ 66 | [fehh]: http://frontendhappyhour.com/ 67 | [fem]: https://frontendmasters.com/ 68 | [twitter]: https://twitter.com/holtbt 69 | [github]: https://github.com/btholt 70 | [linkedin]: https://www.linkedin.com/in/btholt/ 71 | [course]: https://frontendmasters.com/courses/complete-intro-containers/ 72 | [vwc]: https://vetswhocode.io/ 73 | [issue]: https://github.com/btholt/project-fox-game-site/issues 74 | [bootcamp]: https://frontendmasters.com/bootcamp/ 75 | [web-dev]: https://frontendmasters.com/courses/web-development-v2/ 76 | [vscode]: https://code.visualstudio.com/ 77 | [nodejs]: https://nodejs.dev/how-to-install-nodejs 78 | [nvm]: https://github.com/nvm-sh/nvm#installing-and-updating 79 | [dank]: https://dank.sh/ 80 | [ligatures]: https://jareddev.com/blog/post/vs-code-upgrade-your-font-ligatures 81 | [spaceship]: https://denysdovhan.com/spaceship-prompt/ 82 | [cascadia]: https://github.com/microsoft/cascadia-code#installation 83 | -------------------------------------------------------------------------------- /lessons/linting.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/linting" 3 | title: "Linting" 4 | order: "2F" 5 | description: "The Project" 6 | section: "Frontend Infra" 7 | --- 8 | 9 | We're moving on now from _code formatting_ to _code style_. This often confusing as to what we're talking about here because it's a fine hair to split. People often ask me what's the difference between Prettier and ESLint. It's confusing because there's a lot of overlap. ESLint can do some of what Prettier does. 10 | 11 | Code formatting is very mechanical: how much indenting, how files end, where and when line breaks happen, single or double quotes. Prettier doesn't care what the code does; it just cares what the code looks like. 12 | 13 | Code linting cares, on the other hand, what the code does. Should you use an arrow function here? Do we allow nested callbacks? Is this variable being defined before it's used? Those sorts of questions are what ESLint answers. ESLint can also handle _some_ of what Prettier does: it can do code indentation and a few other things but what we'll do is tell ESLint to not worry about those mechanical things because Prettier will pick up the slack for it. 14 | 15 | Some people like to go hog-wild with ESLint rules and lock down the code style super hardcore. Some of you may have heard the term "the code should look like it was written by one person." I think that's bull. Like we alluded to previously, we want to minimize friction. To that end, I implore you to carefully consider each rule you choose. Don't choose rules because they look nice or because of vain personal preference. Choose rules that legitimately make developers more productive and assist them in writing code that will be definitely be easier to maintain later. Err on the side of more loose than more strict. 16 | 17 | To this end, I do not recommend the [Airbnb][airbnb] JS rules: I find them strict for the sake of being strict. I'll show you what I recommend: a loose set of rules that help devs find mistakes faster. 18 | 19 | ## Set Up ESLint 20 | 21 | Run this: 22 | 23 | ```bash 24 | npm install -D eslint eslint-plugin-import eslint-config-prettier 25 | ``` 26 | 27 | Add a new file to the root of your project called `.eslintrc.json` and put this into it: 28 | 29 | ```json 30 | { 31 | "extends": ["eslint:recommended", "plugin:import/errors", "prettier"], 32 | "rules": { 33 | "no-console": 1 34 | }, 35 | "plugins": ["import"], 36 | "parserOptions": { 37 | "ecmaVersion": 2018, 38 | "sourceType": "module" 39 | }, 40 | "env": { 41 | "es6": true, 42 | "browser": true, 43 | "node": true 44 | } 45 | } 46 | ``` 47 | 48 | Add these to your scripts in `package.json`: 49 | 50 | ```json 51 | { 52 | […] 53 | "scripts": { 54 | […] 55 | "lint": "eslint --ignore-path ./.gitignore --fix \"./**/*.{js,ts}\"", 56 | "lint:check": "eslint --ignore-path ./.gitignore --quiet \"./**/*.{js,ts}\"", 57 | } 58 | } 59 | ``` 60 | 61 | Okay, now you should be able to run `npm run format:check` and currently it will give you an error because we have no JavaScript files in our project yet but it will work momentarily. For `format` we added the `--fix` flag so it will automatically fix problems it knows how to (it can fix some, not others.) 62 | 63 | We have a fairly permissive config here that's really looking only for errors. I prefer it this way: let devs write code the way they know how and try and make ESLint _help_ them, not _hinder_ them. The `import` plugin will help them with gotchas around ES6 Modules. As for the `console.log` rule, I like to let people use them when necessary but still warn to make sure they know they're leaving them in. 64 | 65 | ## VSCode 66 | 67 | Of course there is a great ESLint extension for VSCode. Let's add that now. [Install this extension][vscode]. No additional config necessary, it should just work! 68 | 69 | [airbnb]: https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb 70 | [vscode]: https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint 71 | -------------------------------------------------------------------------------- /lessons/organization.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/organization" 3 | title: "Organizing Your Code" 4 | order: "3A" 5 | description: "The Project" 6 | section: "Architecture" 7 | --- 8 | 9 | There is an endless ocean of ways you can organize your code, all with some trade-offs versus others. Some favor searchability, some favor being understandable from a file explorer, and most just end up being a junk drawer smattering of files. So what do you optimize for when you write code? 10 | 11 | ## Deleteability 12 | 13 | When I write code I try to optimize for "deleteability". When I say deleteability, I mean that when a file / module is no longer useful, you can easily remove it from your code base. Why is that? When you write code to be easily extractable from your code base, it forces you into some habitys by default. Your code _has to be_ modular in order to extract it. If everything is tangled together like spare extension cords, good luck trying to remove anything; any extraction of dead code requires invasive surgery. 14 | 15 | Another good reason is that living code is constantly in flux. Imagine a team of twenty engineers working on a single code base for ten years. At the end of ten years, what percentage code remains from the original commit? There's a good chance that number is 0%. As such, it means that your code base has churned through a lot of code base and a lot of dead code is floating around. If you're not diligent, your code base will end up with 10% active lines of the code and the rest mere flotsam of code wreckages of years past. 16 | 17 | For a C++ project, this band from a maintainability point of view, but often the additional binary size is a rounding error. For a JavaScript application, including dead code can add KBs or even MBs to a page's weight and that's just acceptable. Every byte counts to a web dev. 18 | 19 | Another difficult problem for in particular frontend development is that when we delete one JavaScript file, it can be more than just a `.js` file that has to go: that file will have accompanying tests, CSS, and HTML that needs to be jettisoned along with it. If your code base doesn't have an architecture that allows for it, you'll frequently end up with lots of useless tests and overwhelming CSS messes to detangle. I'm sure many of you have experienced CSS files that are enormous because there's a ton of dead CSS in it. So let's try to figure that out! 20 | 21 | ## Folder Organization 22 | 23 | I try to put like-files together in a folder. I try to have a 1:1 mapping of CSS files to JS files (I use CSS modules for this.) I try to have tests live as close to the files they're testing as possible. That way when you delete something, you can always delete files and frequently delete whole directories. Some people find this to be a lot of folder nesting but I try to not go overboard with it. It's also about making sensible trade offs and being intentional with your actions. Don't make decisions because they're the default ones to make: be intentional and thoughtful. 24 | 25 | We'll in general have a folder be one "concept" or "module". That folder will have all the CSS, JS, tests and whatever else it needs for that module. When it comes time to delete it, the whole folder can go. 26 | -------------------------------------------------------------------------------- /lessons/pooping.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/pooping" 3 | title: "Pooping" 4 | order: "4E" 5 | description: "The Project" 6 | section: "The Game" 7 | --- 8 | 9 | I secretly may have made this section just so Frontend Masters has to list on their site that they have a section about pooping. 10 | 11 | Our little foxy friend will have to poop after whenever he eats. So let's go make that happen. 12 | 13 | In gameState.js 14 | 15 | ```javascript 16 | // with the rest of the state 17 | poopTime: -1, 18 | 19 | // inside tick 20 | else if (this.clock === this.poopTime) { 21 | this.poop(); 22 | } 23 | 24 | // add function to gameState 25 | poop() { 26 | this.current = "POOPING"; 27 | this.poopTime = -1; 28 | this.dieTime = getNextDieTime(this.clock); 29 | modFox("pooping"); 30 | }, 31 | ``` 32 | 33 | Pretty straight forward here. Similar to what we've done before. 34 | 35 | Let's go add clean up poop! 36 | 37 | ```javascript 38 | // replace cleanUpPoop 39 | cleanUpPoop() { 40 | if (this.current === "POOPING") { 41 | this.dieTime = -1; 42 | togglePoopBag(true); 43 | this.startCelebrating(); 44 | this.hungryTime = getNextHungerTime(this.clock); 45 | } 46 | }, 47 | 48 | // add to endCelebrate as last line 49 | togglePoopBag(false); 50 | ``` 51 | 52 | That's it! Everything else we're piggy-backing on code we already wrote. We can safely toggle off the poop bag in every endCelebrate because if it's not there, we can still turn it off. 53 | -------------------------------------------------------------------------------- /lessons/some-ui.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/some-ui" 3 | title: "Some UI" 4 | order: "4A" 5 | description: "The Project" 6 | section: "The Game" 7 | --- 8 | 9 | First, I'm going to give some basic CSS and images to work with. We _could_ go through how I wrote these but I think we're best served by just getting some base CSS and all the images together. 10 | 11 | [Download these files][files]. Unzip them in your source directory. 12 | 13 | Mostly it's just setting the backgrounds and setting up all the CSS animations. Frankly you don't want to learn animations from me. [There are phenomenal teachers on Frontend Masters][css] who can do a much better job here. I used basic sprites and [CSS step animations][step] to get it up and running. Feel free to look at that CSS Tricks article to see how to do it. 14 | 15 | Let's keep going. Add a blank file called "style.css". Change your index.html to be: 16 | 17 | ```html 18 | 19 | 20 | 21 | 22 | 23 | 24 | Fox Pet 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 | 34 | 35 |
36 |
37 | 42 |
43 | 44 | 45 | 46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | 55 | 56 | 57 | 58 | ``` 59 | 60 | You should a random assortment of buttons and UI with a nice spotted background. 61 | 62 | Let's get the frame showing. 63 | 64 | In style.css, add 65 | 66 | ```css 67 | /* general */ 68 | 69 | * { 70 | box-sizing: border-box; 71 | } 72 | 73 | body { 74 | margin: 0; 75 | padding: 0; 76 | font-family: Arial, Helvetica, sans-serif; 77 | } 78 | ``` 79 | 80 | This is basically how I start any project. The `box-sizing` part let's us have more predictable measuring of our elements. The margin and paddin part let eliminate the default styles and this font-family is a good one for us to get started with. (I don't like web fonts in general.) 81 | 82 | Append this to style.css 83 | 84 | ```css 85 | /* frame and background */ 86 | 87 | .container { 88 | display: flex; 89 | align-items: center; 90 | justify-content: center; 91 | position: absolute; 92 | top: 0; 93 | left: 0; 94 | right: 0; 95 | bottom: 0; 96 | } 97 | ``` 98 | 99 | We're going to use flexbox to center everything. Then we're going to use the position absolute trick to have it take up 100% of its parent's space. 100 | 101 | Append this again: 102 | 103 | ```css 104 | .frame { 105 | height: 762px; 106 | width: 762px; 107 | position: relative; 108 | } 109 | 110 | .inner { 111 | position: relative; 112 | } 113 | 114 | .game { 115 | width: 628px; 116 | height: 577px; 117 | position: absolute; 118 | top: 62px; 119 | left: 67px; 120 | } 121 | 122 | .game.night { 123 | width: 716px; 124 | top: 62px; 125 | left: -19px; 126 | } 127 | 128 | .hidden { 129 | display: none; 130 | } 131 | ``` 132 | 133 | The frame should be showing up. Again, we're doing this with a fixed width so this is fine. This will also have the game lining up inside of the frame (buttons are still off.) 134 | 135 | You can also change the `day` class on the `game` div in the HTML to see night as well since we swap out the background. 136 | 137 | Append again: 138 | 139 | ```css 140 | /* buttons */ 141 | 142 | .buttons { 143 | position: absolute; 144 | top: 674px; 145 | left: 266px; 146 | height: 71px; 147 | width: 228px; 148 | display: flex; 149 | align-items: center; 150 | justify-content: space-between; 151 | } 152 | 153 | .icons { 154 | position: absolute; 155 | top: 572px; 156 | left: 194px; 157 | height: 67px; 158 | width: 374px; 159 | display: flex; 160 | align-items: center; 161 | justify-content: space-between; 162 | } 163 | ``` 164 | 165 | Let's quickly do the poop bag 166 | 167 | ```css 168 | /* lol poop */ 169 | 170 | .poop-bag { 171 | position: absolute; 172 | top: 300px; 173 | left: 160px; 174 | } 175 | ``` 176 | 177 | You can remove the `hidden` on the poop bag in the HTML to make sure it works. 178 | 179 | You'll see there's still the black text beneath the game. This is supposed to be the modal letting the players know how to start. Let's style that. 180 | 181 | ```css 182 | /* modal */ 183 | 184 | .modal { 185 | position: absolute; 186 | top: 0; 187 | left: 0; 188 | right: 0; 189 | background-color: blueviolet; 190 | color: white; 191 | } 192 | 193 | .modal:empty { 194 | display: none; 195 | } 196 | 197 | .modal-inner:empty { 198 | display: none; 199 | } 200 | ``` 201 | 202 | We now should see a banner telling the player to start. Another fun part of this is we made it so if the modal doesn't have any text in it, it'll hide itself. Handy for showing and hiding this modal. 203 | 204 | Lastly, we need the CSS for the fox. Since we're doing fixed width, absolute positions are fine. (I just guessed and checked with these.) 205 | 206 | ```css 207 | .fox { 208 | position: absolute; 209 | top: 336px; 210 | left: 285px; 211 | overflow: hidden; 212 | } 213 | 214 | .fox-pooping { 215 | top: 319px; 216 | left: 159px; 217 | } 218 | 219 | .fox-celebrate { 220 | top: 290px; 221 | left: 290px; 222 | } 223 | 224 | .fox-rain { 225 | top: 362px; 226 | } 227 | 228 | .fox-hungry { 229 | top: 362px; 230 | } 231 | 232 | .fox-eating { 233 | top: 362px; 234 | } 235 | 236 | .fox-egg { 237 | top: 289px; 238 | left: 248px; 239 | } 240 | 241 | .fox-sleep { 242 | top: 351px; 243 | left: 445px; 244 | } 245 | 246 | .fox-dead { 247 | top: 380px; 248 | left: 243px; 249 | } 250 | ``` 251 | 252 | That's it for the UI! We now have all the toops we need to get started with writing the JS for the game! 253 | 254 | [We've reached the css-completed milestone][css] 255 | 256 | [files]: https://btholt.github.io/project-fox-game-site/files.zip 257 | [css]: https://frontendmasters.com/learn/css/ 258 | [step]: https://css-tricks.com/using-multi-step-animations-transitions/ 259 | [box-sizing]: https://css-tricks.com/almanac/properties/b/box-sizing/ 260 | [css]: https://github.com/btholt/project-files-for-fox-game/tree/master/css-completed 261 | -------------------------------------------------------------------------------- /lessons/state-machine.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/state-machine" 3 | title: "State Machine" 4 | order: "3C" 5 | description: "The Project" 6 | section: "Architecture" 7 | --- 8 | 9 | The requirements we set out for this game read very much like what a [finite state machine][fsm] is. I swear this is the only computer sciencey thing we're going to chat about, but luckily this one isn't as complicated as many of the others. 10 | 11 | I'll borrow the example from the [XState][fsm] docs (great library that helps you do finite state machines.) You, as a human, are always either asleep or awake. You are never both awake and asleep, and you never neither awake nor alseep: you are always in exactly one of those states. (Let's not have a medical discussion here, lol, you get my point.) 12 | 13 | This is what a finite state machine is: it let's you define various states of what you expect your app to look like and then all "derivative" state is … derived from that chief state. For example, if you were in a `asleep` state, you might have a derived state that is `areEyesClosed` that would always be true in `asleep`. This is instead of the problematic way of having a million `is` booleans in your code which always fall out of sync. 14 | 15 | So that's what we're going to do is model a basic finite state machine that represents our game. Based on the requirements, I can see the following overarching states of the game: 16 | 17 | ```json 18 | [ 19 | "INIT", 20 | "HATCHING", 21 | "IDLING", 22 | "SLEEPING", 23 | "EATING", 24 | "POOPING", 25 | "HUNGRY", 26 | "CELEBRATING", 27 | "DEAD" 28 | ] 29 | ``` 30 | 31 | At any given time, our game is in one of those states. Furthermore, there are definited transitions. Your game can't go from `HATCHING` to `DEAD` or else you'd have a pretty morbid and unfun game. Instead, `HATCHING` can _only_ go to `IDLING`. We can take advantage of these to make assumptions and reduce our surface area for bugs. 32 | 33 | Something like `XState` could help a lot with a game like this, and I implore to you take [David Khourshid's][david] upcoming [Frontend Masters workshop][fem] because he'll get into more depth in it. Instead, we're just going to take the base level concepts and apply them ourselves. 34 | 35 | Let's make a new file and call it gameState.js inside of `src`. 36 | 37 | ```javascript 38 | const gameState = { 39 | current: "INIT", 40 | clock: 1, 41 | tick() { 42 | this.clock++; 43 | console.log(this.clock); 44 | return this.clock; 45 | } 46 | }; 47 | 48 | module.exports = gameState; 49 | ``` 50 | 51 | Back in init, change the the init.js, 52 | 53 | ```javascript 54 | // add at top 55 | import game from "./gameState"; 56 | 57 | // delete tick function 58 | 59 | // change tick() 60 | game.tick(); 61 | ``` 62 | 63 | Now we've accomplished a few things. We have an in-game clock that ticks. We can tie our state machine to these ticks of the clock. But also what's great is we decoupled our state machine from an actual clock, so it'll work in game but we can also pull out the game state and test it outside of real time. 64 | 65 | From here, we're going to be all getting from one state to another. 66 | 67 | I guess it bears mentioning here that I like to write the logic first and then I write the manifestation of the HTML and CSS afterwards. If you think about it, our UI is just a manifest of our state machine. It's a side effect of this ever-moving machine. 68 | 69 | [fsm]: https://xstate.js.org/docs/about/concepts.html#finite-state-machines 70 | [david]: https://twitter.com/davidkpiano 71 | [fem]: https://frontendmasters.com/teachers/david-khourshid/ 72 | -------------------------------------------------------------------------------- /lessons/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/testing" 3 | title: "Testing" 4 | order: "2G" 5 | description: "The Project" 6 | section: "Frontend Infra" 7 | --- 8 | 9 | Testing is always important. I tend to err on the side of less tests. The only thing worse than having no tests is having bad tests. They could be bad because they're stale, testing the wrong things, or the worst of all: finnicky and tempermental. The worst test is the one that you don't trust the results, whether that's tests that will fail when they should pass or the test that passes what it should fail. Any test like that I tend to delete. 10 | 11 | This will not be a class on testing. We're only going to do some light unit testing. There are other Frontend Masters courses that go into much better depth than I do. 12 | 13 | My general rule of thumb is to test important modules thoroughly, test the cases you expect to hit with less important modules (maybe a few error cases), and lightly smatter tests around the rest. When you hit a production bug, a good method to debug is to write a test that would have caught the bug you hit in production, and then fix it. With this strategy you should end up with a healthy battery of dependable tests. 14 | 15 | ## Framework 16 | 17 | I'm fine any testing framework. I've used them all professionally: Jest, Jasmine, Mocha, AVA, etc. We're going to stick to [Jest][jest]. It's the one I know the best and they have a bunch of nice convenience features. Beyond that, like Parcel, it tends to just work out of the box. 18 | 19 | In your project, run 20 | 21 | ```bash 22 | npm install -D jest 23 | ``` 24 | 25 | Add to npm scripts 26 | 27 | ```json 28 | { 29 | […] 30 | "scripts": { 31 | […] 32 | "test": "jest" 33 | } 34 | } 35 | ``` 36 | 37 | That's it! Jest is very intelligent and opinionated on how it finds your tests. As long as we name our tests `*.test.js` it'll fine them by default! How cool is that? 38 | 39 | [jest]: https://jestjs.io/ 40 | -------------------------------------------------------------------------------- /lessons/the-project.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/the-project" 3 | title: "The Project" 4 | order: "1B" 5 | description: "The Project" 6 | section: "Welcome" 7 | --- 8 | 9 | Do you remember [those virtual][virtual-pet] [pet toys][virtual-pet-2] from the 90s? They were the bane of every poor teacher and parent's existance. They're essentially needy little virutal pets that need you to feed and clean up their poops every few hours. We're going to build our own! 10 | 11 | Luckily, [Ms Alice Brereton][alice] has created some more beautiful assets for us to use for the game. 12 | 13 | [Here is my version of the game][fox]. 14 | 15 | The code for this game isn't too simple and that'll make for a fun exercise. And there are _many_ correct ways to program it. I'll share with you some tips and tricks and how I did it but feel free to explore and learn! 16 | 17 | ## Requirements 18 | 19 | - The game starts in an initialized state. The user must press the center game to get started. 20 | - Users can switch between the three icons on the bottom using the left and right button. To press one of the icons, they will click the middle button. Users cannot directly click the icons. 21 | - If they reach the end of the icons and try to go further (click the right button when the right-most icon is selected) it should loop around. 22 | - When the user starts, the fox will hatch after showing the hatch animation. 23 | - Once the fox is hatched, show the fox in an idle animation in the day time. 24 | - The user can switch the weather from day to rain using the weather icon. 25 | - After some amount of time the fox will become hungry. This should be on some sort of variable schedule to add some unpredictability to the game. 26 | - The fox can only be fed when hungry. 27 | - After a fox is a fed, after another random interval, the fox will poop. 28 | - The fox cannot have the poop cleaned up unless there is poop to be cleaned up 29 | - When a user cleans up poop, it should add another random interval until the fox is hungry again. 30 | - The fox cannot be hungry and have pooped at the same time. 31 | - If the user hasn't fed a hungry fox or clean up a fox's poop after a random interval, it should cause the fox to die and go to the game over screen. 32 | - After a longer random interval of day/rain, it should become night. It stays night for a fixed interval. The fox does not get hungry, poop, or die in its sleep. Once it wakes up, it starts with a new random interval of hunger and poop. You cannot change the weather, clean up poop or feed a sleeping fox. 33 | - Once the game hits nighttime, reset the timers. The fox will wake up and the first thing that will happen is it will become hungry. 34 | - Once a fox dies, the landscape goes into the death scene, the fox becomes the tombstone, and the game is over. If the user presses the middle button again, it restarts the game with a new hatch. 35 | - Using a modal, you should tell the user to restart the game by pressing the middle button. 36 | - The fox should not be able to die, get hungry, poop, be fed, have the poop cleaned up, or fall asleep when it is being fed, sleeping, hatching, or dead. 37 | - While in general I'm a huge advocate for responsive designs and making things work on any viewport size, this one time I'm absolving you of that responsiblity and you can just assume a fixed desktop browser size. 38 | 39 | Phew. That's a lot of requirements! 40 | 41 | ## Technical Requirements 42 | 43 | There are none, lol. 44 | 45 | You can implement this however you see fit. 46 | 47 | I will be writing this in straight, vanilla JavaScript. This is for several reasons: 48 | 49 | - It should be the common denominator between all students. All the concepts we'll be talking about could equally be applied to React, Angular, Svelte, Vue or even jQuery. The state management could be done in Redux, ngrx, or xstate. It's a universal language for all of us. 50 | - This is a really simple project with simple requirements. If this project was made in a vacuum, there's a high chance I would do it this way. While tools like React help make large projects more manageable, we don't need the weight here. 51 | - It's a useful exercise to pull away from your tried-and-true tools to stretch your brain in interesting ways to make sure you're not overly reliant on tools that come-and-go. 52 | 53 | A fun exercise could be to reimplement this game in different frameworks and technologies to see how they fit your thinking and how you think changes in different technical constraints and machinations. 54 | 55 | Beyond that, I'll make some just personal preference choices. You're free to do it with me or you're free to deviate. Let's get started! 56 | 57 | [virtual-pet]: https://en.wikipedia.org/wiki/Tamagotchi 58 | [virtual-pet-2]: https://en.wikipedia.org/wiki/Giga_Pet 59 | [alice]: https://www.pickledalice.com/ 60 | [fox]: https://btholt.github.io/project-files-for-fox-game/ 61 | -------------------------------------------------------------------------------- /lessons/the-states.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/the-states" 3 | title: "The States" 4 | order: "4C" 5 | description: "The Project" 6 | section: "The Game" 7 | --- 8 | 9 | So now we have a game and a running clock. Let's make it run through the motions then! 10 | 11 | Let's define the actions, the edges, the transformations of the game. How we do go from one state like `HUNGRY` to `FEEDING`? It'd be some sort of action, right? You'd feed it, right? Then go ahead name that function `feed()`. 12 | 13 | But let's not get ahead of ourselves. Let's go from `INIT` (where the game is waiting) to a starting state, which we're calling `HATCHING`. 14 | 15 | I'd just call this `startGame()` since that's the gesture we're going through. Make `gameState` say this: 16 | 17 | ```javascript 18 | const gameState = { 19 | current: "INIT", 20 | clock: 1, 21 | wakeTime: -1, 22 | tick() { 23 | this.clock++; 24 | 25 | if (this.clock === this.wakeTime) { 26 | this.wake(); 27 | } 28 | 29 | return this.clock; 30 | }, 31 | startGame() { 32 | console.log("hatching"); 33 | this.current = "HATCHING"; 34 | this.wakeTime = this.clock + 3; 35 | }, 36 | wake() { 37 | console.log("hatched"); 38 | this.current = "IDLING"; 39 | this.wakeTime = -1; 40 | }, 41 | handleUserAction(icon) { 42 | console.log(icon); 43 | } 44 | }; 45 | 46 | export default gameState; 47 | ``` 48 | 49 | This will get the game going but we have no way to start it. So let's detour a second to get some basic UI working with it. Let's fill out `handleUserAction`. 50 | 51 | ```javascript 52 | handleUserAction(icon) { 53 | // can't do actions while in these states 54 | if ( 55 | ["SLEEP", "FEEDING", "CELEBRATING", "HATCHING"].includes( 56 | this.current 57 | ) 58 | ) { 59 | // do nothing 60 | return; 61 | } 62 | 63 | if (this.current === "INIT" || this.current === "DEAD") { 64 | this.startGame(); 65 | return; 66 | } 67 | 68 | // execute the currently selected action 69 | switch (icon) { 70 | case "weather": 71 | this.changeWeather(); 72 | break; 73 | case "poop": 74 | this.cleanUpPoop(); 75 | break; 76 | case "fish": 77 | this.feed(); 78 | break; 79 | } 80 | }, 81 | changeWeather() { 82 | console.log('changeWeather') 83 | }, 84 | cleanUpPoop() { 85 | console.log('cleanUpPoop') 86 | }, 87 | feed() { 88 | console.log('feed') 89 | }, 90 | ``` 91 | 92 | So this is the logic of how we're going to handle user clicks but if you try to click it doesn't work, you'll get a dreaded context error. Why? We're using gameState's handleUserAction without context because it's being called by the browser. Let's make it work. 93 | 94 | In gameState.js 95 | 96 | ```javascript 97 | // at bottom 98 | export const handleUserAction = gameState.handleUserAction.bind(gameState); 99 | ``` 100 | 101 | In init.js 102 | 103 | ```javascript 104 | // at top 105 | import game, { handleUserAction } from "./gameState"; 106 | 107 | // replace initButtons 108 | initButtons(handleUserAction); 109 | ``` 110 | 111 | Now it'll have proper context. So try clicking the button. You should now see the console.logs. 112 | 113 | Let's make those actually display the fox. Make a new file called ui.js. Put this in there. 114 | 115 | ```javascript 116 | export const modFox = function modFox(state) { 117 | document.querySelector(".fox").className = `fox fox-${state}`; 118 | }; 119 | export const modScene = function modScene(state) { 120 | document.querySelector(".game").className = `game ${state}`; 121 | }; 122 | export const togglePoopBag = function togglePoopBag(show) { 123 | document.querySelector(".poop-bag").classList.toggle("hidden", !show); 124 | }; 125 | ``` 126 | 127 | Nothing too surpising here. Now we can write out our state the DOM easily using these helpers. 128 | 129 | Back to our gameState.js 130 | 131 | ```javascript 132 | import { SCENES, RAIN_CHANCE } from "./constants"; 133 | 134 | startGame() { 135 | this.current = "HATCHING"; 136 | this.wakeTime = this.clock + 3; 137 | modFox("egg"); 138 | modScene("day"); 139 | }, 140 | wake() { 141 | this.current = "IDLING"; 142 | this.wakeTime = -1; 143 | modFox("idling"); 144 | this.scene = Math.random() > RAIN_CHANCE ? 0 : 1; 145 | modScene(SCENES[this.scene]); 146 | }, 147 | ``` 148 | 149 | Add to constants.js 150 | 151 | ```javascript 152 | export const SCENES = ["day", "rain"]; 153 | export const RAIN_CHANCE = 0.2; 154 | ``` 155 | 156 | Now we can see our fox friend! Hooray! He should hatch now and start idling. 157 | 158 | We are modding the scene here because now we can re-use these functions to restart the game after death for startGame and to wake up after night. Just for fun, we're making it randomly rain sometimes. Currently, it'll rain ~20% of the time. Feel free to play with that number. 159 | 160 | Okay! So now the game is off and running. Let's go to the next section where we'll flesh out the rest of the states! 161 | 162 | [We've reached the game-started milestone][game-started]. 163 | 164 | [game-started]: https://github.com/btholt/project-files-for-fox-game/tree/master/game-started 165 | -------------------------------------------------------------------------------- /lessons/transitioning-between-states.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/transitioning-between-states" 3 | title: "Transitioning Between States" 4 | order: "4D" 5 | description: "The Project" 6 | section: "The Game" 7 | --- 8 | 9 | I've found in my career that most of the bugs in my cause arise from states transition incorrectly. Either I forgot to set a flag or I didn't add some number together or something like that. This is where the most danger is. This what your tests should cover. This is what you should focus on getting right. 10 | 11 | Let's focus first on transitioning between day and night. The game should X ticks in day and then transition into a brief nighttime period and then come back. 12 | 13 | ```javascript 14 | // add at top 15 | import { SCENES, RAIN_CHANCE, DAY_LENGTH, NIGHT_LENGTH } from "./constants"; 16 | 17 | // add in state 18 | sleepTime: -1, 19 | 20 | // add else if to tick() 21 | else if (this.clock === this.sleepTime) { 22 | this.sleep(); 23 | } 24 | 25 | // add last line to wake() 26 | this.sleepTime = this.clock + DAY_LENGTH; 27 | 28 | // add function to gameState 29 | sleep() { 30 | this.state = "SLEEP"; 31 | modFox("sleep"); 32 | modScene("night"); 33 | this.wakeTime = this.clock + NIGHT_LENGTH; 34 | }, 35 | ``` 36 | 37 | Add to constants.js 38 | 39 | ```javascript 40 | export const DAY_LENGTH = 60; 41 | export const NIGHT_LENGTH = 3; 42 | ``` 43 | 44 | Alright! Now we have a cycle of day & night! (If you need to debug, just make the numbers shorter temporarily.) We cleverily piggybacked on our wakeTime setup since it's actually the same logic. 45 | 46 | Great, let's make our fox get hungry now. 47 | 48 | ```javascript 49 | // at top 50 | import { 51 | SCENES, 52 | RAIN_CHANCE, 53 | DAY_LENGTH, 54 | NIGHT_LENGTH, 55 | getNextHungerTime, 56 | getNextDieTime, 57 | } from "./constants"; 58 | 59 | // add to state 60 | hungryTime: -1, 61 | dieTime: -1, 62 | 63 | // add to tick if statements 64 | else if (this.clock === this.hungryTime) { 65 | this.getHungry(); 66 | } else if (this.clock === this.dieTime) { 67 | this.die(); 68 | } 69 | 70 | // last line of wake 71 | this.sleepTime = this.clock + DAY_LENGTH; 72 | this.hungryTime = getNextHungerTime(this.clock); 73 | 74 | // last functions of gameSTate 75 | getHungry() { 76 | this.current = "HUNGRY"; 77 | this.dieTime = getNextDieTime(this.clock); 78 | this.hungryTime = -1; 79 | modFox("hungry"); 80 | }, 81 | die() { 82 | console.log("die"); 83 | }, 84 | ``` 85 | 86 | In constants.js 87 | 88 | ```javascript 89 | export const getNextHungerTime = clock => 90 | Math.floor(Math.random() * 3) + 5 + clock; 91 | export const getNextDieTime = clock => 92 | Math.floor(Math.random() * 2) + 3 + clock; 93 | ``` 94 | 95 | The stakes have risen! Now our fox friend can perish if our owner doesn't feed them in time! Oh no! What's worse, we haven't implemented a way to feed them, but to be fair, a `console.log` of `die` isn't a bad death either. 96 | 97 | Now we're starting to rely on the clock a bit more to track our game. We're also adding a touch of randomness. We want the game to play different each time so we're adding a bit of variance to how long it takes for the fox to get hungry as well as how long the fox has before it dies of hunger. 98 | 99 | From here, let's make it possible for our fox to eat. In gameState.js 100 | 101 | ```javascript 102 | //change feed() 103 | feed() { 104 | // can only feed when hungry 105 | if (this.current !== "HUNGRY") { 106 | return; 107 | } 108 | 109 | this.current = "FEEDING"; 110 | this.dieTime = -1; 111 | this.poopTime = getNextPoopTime(this.clock); 112 | modFox("eating"); 113 | this.timeToStartCelebrating = this.clock + 2; 114 | }, 115 | ``` 116 | 117 | To constants.js 118 | 119 | ```javascript 120 | export const getNextPoopTime = clock => 121 | Math.floor(Math.random() * 3) + 4 + clock; 122 | ``` 123 | 124 | This will allow us to feed the fox before he dies! Yay! We added timers to get the fox to start celebrating as well for when it poops (you poop after you eat, right?) Now we want the fox to celebrate after he dines, so let's go implement that. 125 | 126 | ```javascript 127 | // two variables to track 128 | timeToStartCelebrating: -1, 129 | timeToEndCelebrating: -1, 130 | 131 | // add two new ifs to tick 132 | else if (this.clock === this.timeToStartCelebrating) { 133 | this.startCelebrating(); 134 | } else if (this.clock === this.timeToEndCelebrating) { 135 | this.endCelebrating(); 136 | } 137 | 138 | // two new functions in game state 139 | startCelebrating() { 140 | this.current = "CELEBRATING"; 141 | modFox("celebrate"); 142 | this.timeToStartCelebrating = -1; 143 | this.timeToEndCelebrating = this.clock + 2; 144 | }, 145 | endCelebrating() { 146 | this.timeToEndCelebrating = -1; 147 | this.current = "IDLING"; 148 | this.determineFoxState(); 149 | }, 150 | determineFoxState() { 151 | if (this.current === 'IDLING') { 152 | if (SCENES[this.scene] === "rain") { 153 | modFox("rain"); 154 | } else { 155 | modFox("idling"); 156 | } 157 | } 158 | }, 159 | ``` 160 | 161 | We need the determineFoxState because if it's raining, the fox should go back to facing away. Let's go make our `wake` use that as well. And we can go ahead and implement change weather since this is the last feature we need to do that 162 | 163 | ```javascript 164 | // add to wake, right after modScene 165 | this.determineFoxState(); 166 | 167 | // replace changeWeather 168 | changeWeather() { 169 | this.scene = (1 + this.scene) % SCENES.length; 170 | modScene(SCENES[this.scene]); 171 | this.determineFoxState(); 172 | }, 173 | ``` 174 | 175 | [We've reached the transitioning-states milestone][states]. 176 | 177 | [states]: https://github.com/btholt/project-files-for-fox-game/tree/master/transitioning-states 178 | -------------------------------------------------------------------------------- /lessons/type-checking.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/type-checking" 3 | title: "Type Checking" 4 | order: "2H" 5 | description: "The Project" 6 | section: "Frontend Infra" 7 | --- 8 | 9 | Here is where I'd tell you to set up [TypeScript][ts] because I typically would for myself. What I tell folks is that any project that is destined to be worked on any longer than two weeks will be best served with having typings associated with the code. 10 | 11 | Why? I believe that types serve several purposed. 12 | 13 | TypeScript forces you, the original implementor of the code, to think through your types. This is helpful because it shakes out of some of the loosey-goosey habits that we as JavaScript developers get ourselves into. It forces to you to think that a String is going in here and a Number is coming out the other side. It forces you to reconsider letting `undefined`s and `null`s float through your code. It forces you to be intentional with the flow of your code and I think that is a large benefit. 14 | 15 | TypeScript also helps future you and co-workers reading your code. If you can see that a parameter coming into a function is a String, you don't have to either throw in a `console.log` and execute it or go back to the caller to see what's being passed in. In other words, it allows future readers of your code to take shortcuts in making assumptions about the code they're looking at, and again I believe that's a large benefit. 16 | 17 | To some lesser degree, it will help you prevent runtime errors due to `undefined is not a function` and other things like that. This is not the biggest reason to use TypeScript because good code discipline is more important in preventing those bugs anyway, but nonetheless it certainly helps inform those disciplines. 18 | 19 | Lastly, TypeScript allows you to drag your documentation of your code around your codebase, particularly if you have a modular architecture. If I import a module in another part of my codebase and I type `module.`, it start autopopulating call signatures and properties for me to remind myself what's available. It's immediately available information that I find super helpful. 20 | 21 | ## So why not 22 | 23 | Again, I love TypeScript. But it is not for every project. For quick and dirty proofs-of-concept, command-line scripts, and other such ephemeral scripts I tend not to use TypeScript. TypeScript is a long term play, not as much for the short term. 24 | 25 | And as many of you have probably found, you do inevitably spend some time fighting the compiler. This can get frustrating when your code _would_ work but TypeScript is picking on you for not casting the right way or some other annoyance. You should definitely factor that cost in when you're considering if your team should use TypeScript. 26 | 27 | So why aren't we using it for this course then? While I personally would use TypeScript here, I recognize that many people landing here wouldn't. I recognize many of you either don't know TypeScript yet or don't want to ever know TypeScript so I have made the decision to remove the barrier to the knowledge here. For the rest of you who would want TypeScript, I am sorry and you can definitely check out [Intermediate React v2][react] where I teach some TypeScript. And for the rest of you who do want to learn [Frontend Masters has a wonderful course from my old colleague Mike North.][fem]. 28 | 29 | [We've reached the frontend-infra milestone][infra]. 30 | 31 | [ts]: https://www.typescriptlang.org/ 32 | [fem]: https://frontendmasters.com/courses/typescript-v2/ 33 | [infra]: https://github.com/btholt/project-files-for-fox-game/tree/master/frontend-infra 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "project-fox-game-site", 3 | "description": "The site for the Project Fox Game for Frontend Masters", 4 | "version": "1.0.0", 5 | "author": "Brian Holt ", 6 | "dependencies": { 7 | "bootstrap": "^5.1.3", 8 | "code-mirror-themes": "^1.0.0", 9 | "front-matter": "^4.0.2", 10 | "gatsby": "^4.7.1", 11 | "gatsby-cli": "^4.7.0", 12 | "gatsby-link": "^4.7.1", 13 | "gatsby-plugin-layout": "^3.7.0", 14 | "gatsby-plugin-react-helmet": "^5.7.0", 15 | "gatsby-plugin-sharp": "^4.7.0", 16 | "gatsby-remark-autolink-headers": "^5.7.0", 17 | "gatsby-remark-copy-linked-files": "^5.7.0", 18 | "gatsby-remark-images": "^6.7.0", 19 | "gatsby-remark-prismjs": "^6.7.0", 20 | "gatsby-source-filesystem": "^4.7.0", 21 | "gatsby-transformer-remark": "^5.7.0", 22 | "is-url-superb": "^6.1.0", 23 | "parse-markdown-links": "^1.0.4", 24 | "prismjs": "^1.26.0", 25 | "react": "^17.0.2", 26 | "react-dom": "^17.0.2", 27 | "react-helmet": "^6.1.0" 28 | }, 29 | "keywords": [ 30 | "gatsby", 31 | "gatsby-starter", 32 | "course", 33 | "education" 34 | ], 35 | "license": "(CC-BY-NC-4.0 OR Apache-2.0)", 36 | "main": "n/a", 37 | "scripts": { 38 | "build": "gatsby build --prefix-paths", 39 | "csv": "node csv.js", 40 | "dev": "gatsby develop", 41 | "format": "prettier --write \"src/**/*.{js,jsx,md,css}\"", 42 | "lint": "eslint \"src/**/*.{js,jsx}\"" 43 | }, 44 | "devDependencies": { 45 | "@babel/polyfill": "^7.4.4", 46 | "babel-eslint": "^10.0.2", 47 | "core-js": "^3.21.0", 48 | "eslint": "^8.8.0", 49 | "eslint-config-prettier": "^8.3.0", 50 | "eslint-plugin-import": "^2.25.4", 51 | "eslint-plugin-jsx-a11y": "^6.5.1", 52 | "eslint-plugin-react": "^7.28.0", 53 | "prettier": "^2.5.1" 54 | } 55 | } -------------------------------------------------------------------------------- /src/components/TOCCard.css: -------------------------------------------------------------------------------- 1 | .main-card { 2 | border: 1px solid #ccc; 3 | border-radius: 8px; 4 | width: 100%; 5 | margin: 0; 6 | overflow: hidden; 7 | background-color: white; 8 | } 9 | 10 | .lesson-title { 11 | font-size: 20px; 12 | padding: 15px 30px; 13 | } 14 | 15 | .lesson-content { 16 | padding: 0 15px 15px 15px; 17 | line-height: 1.5; 18 | } 19 | 20 | .sections-name { 21 | list-style: none; 22 | } 23 | 24 | .lesson-section-title { 25 | margin-top: 25px; 26 | } 27 | -------------------------------------------------------------------------------- /src/components/TOCCard.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import * as helpers from "../util/helpers"; 4 | import "./TOCCard.css"; 5 | 6 | const sortFn = helpers.sorter; 7 | 8 | const LessonCard = ({ content, title }) => { 9 | console.log(sortFn); 10 | 11 | const sections = content 12 | .map(lesson => lesson.node.frontmatter) 13 | .sort(sortFn) 14 | .reduce((acc, lesson) => { 15 | if (!acc.length) { 16 | acc.push([lesson]); 17 | return acc; 18 | } 19 | 20 | const lastSection = acc[acc.length - 1][0].section.split(",")[0]; 21 | if (lastSection === lesson.section.split(",")[0]) { 22 | acc[acc.length - 1].push(lesson); 23 | } else { 24 | acc.push([lesson]); 25 | } 26 | 27 | return acc; 28 | }, []); 29 | 30 | return ( 31 |
32 |

{title}

33 |
34 |
    35 | {sections.map(section => ( 36 |
  1. 37 |

    {section[0].section}

    38 |
      39 | {section.map(lesson => ( 40 |
    1. 41 | {lesson.title} 42 |
    2. 43 | ))} 44 |
    45 |
  2. 46 | ))} 47 |
48 |
49 |
50 | ); 51 | }; 52 | 53 | export default LessonCard; 54 | -------------------------------------------------------------------------------- /src/layouts/index.css: -------------------------------------------------------------------------------- 1 | .gradient { 2 | background: rgb(96, 108, 136); 3 | background: linear-gradient( 4 | to bottom, 5 | rgb(96, 108, 136) 0%, 6 | rgb(63, 76, 107) 100% 7 | ); 8 | } 9 | 10 | .navbar { 11 | border-bottom: 1px solid #ccc; 12 | position: sticky; 13 | width: 100%; 14 | top: 0; 15 | z-index: 10; 16 | display: flex; 17 | justify-content: space-between; 18 | align-items: center; 19 | padding: 10px; 20 | } 21 | 22 | .navbar h1 { 23 | font-size: 20px; 24 | margin: inherit; 25 | padding: inherit; 26 | font-weight: bold; 27 | } 28 | 29 | .navbar h2, 30 | .navbar h3{ 31 | font-size: 14px; 32 | margin: inherit; 33 | padding: inherit; 34 | text-transform: uppercase; 35 | color: white; 36 | } 37 | 38 | .button { 39 | border-radius: 10px; 40 | padding: 0; 41 | background: #0066cc; 42 | color: white; 43 | display: flex; 44 | justify-content: center; 45 | align-items: center; 46 | text-decoration: none; 47 | } 48 | 49 | .button .icon { 50 | padding-left: 5px; 51 | display: inline-block; 52 | } 53 | 54 | .button a { 55 | padding: 3px 8px; 56 | color: white; 57 | text-decoration: none; 58 | } 59 | 60 | @media (max-width: 1450px) { 61 | .mobile-hidden { 62 | display: none; 63 | } 64 | .lesson-container { 65 | padding-top: 65px; 66 | } 67 | } 68 | 69 | .button:hover { 70 | background: #0d6efd; 71 | } 72 | 73 | .jumbotron { 74 | padding: 2rem 1rem; 75 | margin-bottom: 2rem; 76 | background-color: #e9ecef; 77 | border-radius: .3rem; 78 | } 79 | 80 | @media (min-width: 576px) { 81 | .jumbotron { 82 | padding: 4rem 2rem; 83 | } 84 | } 85 | 86 | .jumbotron.gradient { 87 | color: white; 88 | text-transform: uppercase; 89 | font-weight: bold; 90 | } 91 | 92 | .navbar-brand.navbar-brand { 93 | text-transform: uppercase; 94 | color: white; 95 | font-weight: bold; 96 | } 97 | 98 | .navbar-brand.navbar-brand:hover { 99 | color: #777; 100 | } 101 | 102 | .navbar-brand.navbar-brand:focus { 103 | color: white; 104 | } 105 | 106 | .lesson { 107 | margin: 15px; 108 | padding: 15px; 109 | background-color: #fff; 110 | border-radius: 8px; 111 | overflow: scroll; 112 | } 113 | 114 | .lesson p { 115 | clear: both; 116 | } 117 | 118 | .lesson-links { 119 | font-size: 18px; 120 | padding: 15px 0; 121 | } 122 | 123 | .next { 124 | float: right; 125 | } 126 | 127 | .prev { 128 | float: left; 129 | } 130 | 131 | .lesson-title { 132 | color: white; 133 | text-transform: uppercase; 134 | font-weight: bold; 135 | } 136 | 137 | .klipse-result { 138 | border: 1px solid #90b4fe; 139 | padding-top: 8px; 140 | position: relative; 141 | width: 100%; 142 | } 143 | 144 | .klipse-result .CodeMirror-wrap { 145 | width: 100%; 146 | border-color: transparent; 147 | } 148 | 149 | .klipse-result::before { 150 | content: "result"; 151 | background-color: white; 152 | position: absolute; 153 | top: -13px; 154 | height: 13px; 155 | } 156 | 157 | .language-htm, 158 | .language-css, 159 | .language-js, 160 | .language-json { 161 | width: 100%; 162 | } 163 | 164 | .gatsby-highlight { 165 | /* border: 1px solid black; */ 166 | padding: 4px; 167 | border-radius: 4px; 168 | display: flex; 169 | justify-content: space-between; 170 | flex-direction: column; 171 | align-items: stretch; 172 | } 173 | 174 | .CodeMirror-wrap { 175 | width: 100%; 176 | font-size: 12px; 177 | height: inherit; 178 | margin-bottom: 12px; 179 | } 180 | 181 | .CodeMirror-gutters { 182 | height: inherit !important; 183 | } 184 | 185 | .klipse-snippet > .CodeMirror { 186 | border: none; 187 | width: 100%; 188 | } 189 | 190 | .gatsby-highlight > .klipse-snippet { 191 | border: 1px solid #90b4fe; 192 | width: 100%; 193 | border-right: none; 194 | position: relative; 195 | margin-bottom: 15px; 196 | } 197 | 198 | .doggos { 199 | width: 100%; 200 | border: 1px solid #666; 201 | border-radius: 5px; 202 | } 203 | -------------------------------------------------------------------------------- /src/layouts/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import Helmet from "react-helmet"; 4 | import { graphql, StaticQuery } from "gatsby"; 5 | 6 | import "bootstrap/dist/css/bootstrap.css"; 7 | import "prismjs/themes/prism-solarizedlight.css"; 8 | import "code-mirror-themes/themes/monokai.css"; 9 | import "./index.css"; 10 | 11 | // import jpg from "../../static/posterframe.jpg"; 12 | 13 | const TemplateWrapper = props => { 14 | return ( 15 | { 17 | const frontmatter = 18 | props.data && props.data.markdownRemark 19 | ? props.data.markdownRemark.frontmatter 20 | : null; 21 | 22 | return ( 23 |
24 | 70 |
71 | 72 |

{data.site.siteMetadata.title}

73 | 74 | {!frontmatter ? null : ( 75 |

{`${frontmatter.section} – ${frontmatter.title}`}

76 | )} 77 |

78 | 79 | Complete Front-End Game Project Videos 80 |  ▶️  81 | 82 |

83 |
84 |
{props.children}
85 |
86 | ); 87 | }} 88 | query={graphql` 89 | query HomePage($path: String!) { 90 | markdownRemark(frontmatter: { path: { eq: $path } }) { 91 | html 92 | frontmatter { 93 | path 94 | title 95 | order 96 | section 97 | description 98 | } 99 | } 100 | site { 101 | pathPrefix 102 | siteMetadata { 103 | title 104 | subtitle 105 | description 106 | keywords 107 | } 108 | } 109 | } 110 | `} 111 | /> 112 | ); 113 | }; 114 | 115 | export default TemplateWrapper; 116 | -------------------------------------------------------------------------------- /src/pages/404.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NotFoundPage = () => ( 4 |
5 |

NOT FOUND

6 |

You just hit a route that doesn't exist... the sadness.

7 |
8 | ); 9 | 10 | export default NotFoundPage; 11 | -------------------------------------------------------------------------------- /src/pages/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #eee; 3 | } 4 | 5 | .index { 6 | width: 97%; 7 | max-width: 750px; 8 | margin: 0 auto; 9 | margin-top: 20px; 10 | } 11 | 12 | .main { 13 | margin-top: 80px; 14 | } 15 | 16 | .lesson-container { 17 | max-width: 850px; 18 | margin: 0 auto 60px; 19 | } 20 | 21 | .lesson { 22 | margin: 20px; 23 | } 24 | 25 | .lesson-content { 26 | padding: 20px; 27 | } 28 | 29 | .lesson h1 { 30 | margin: 0; 31 | padding: 20px; 32 | } 33 | 34 | .example-table { 35 | border-collapse: separate; 36 | } 37 | 38 | .example-table td { 39 | border: 1px solid black; 40 | width: 20px; 41 | height: 20px; 42 | } 43 | 44 | .example-table .current { 45 | background-color: #fcc; 46 | } 47 | 48 | .example-table .n { 49 | border-top-color: transparent; 50 | } 51 | 52 | .example-table .s { 53 | border-bottom-color: transparent; 54 | } 55 | 56 | .example-table .e { 57 | border-right-color: transparent; 58 | } 59 | 60 | .example-table .w { 61 | border-left-color: transparent; 62 | } 63 | 64 | .lesson-content table { 65 | } 66 | 67 | .lesson-content td { 68 | border: 1px solid black; 69 | padding: 8px; 70 | } 71 | 72 | .lesson-content td input { 73 | min-width: 300px; 74 | } 75 | 76 | .lesson-flex { 77 | display: flex; 78 | flex-direction: column; 79 | justify-content: center; 80 | align-items: center; 81 | } 82 | 83 | .random-tweet { 84 | width: 100%; 85 | margin-top: 100px; 86 | } 87 | 88 | .fem-link { 89 | text-align: center; 90 | } 91 | -------------------------------------------------------------------------------- /src/pages/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { StaticQuery, graphql } from "gatsby"; 3 | import Card from "../components/TOCCard"; 4 | 5 | import "./index.css"; 6 | 7 | const IndexPage = () => ( 8 | ( 36 |
37 |
38 |

{props.site.siteMetadata.title}

39 |

{props.site.siteMetadata.subtitle}

40 |
41 | 42 | 46 |
47 | )} 48 | /> 49 | ); 50 | 51 | export default IndexPage; 52 | -------------------------------------------------------------------------------- /src/templates/lessonTemplate.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import { graphql } from "gatsby"; 4 | import * as helpers from "../util/helpers"; 5 | 6 | const sortFn = helpers.sorter; 7 | 8 | export default function Template(props) { 9 | let { markdownRemark, allMarkdownRemark } = props.data; // data.markdownRemark holds our post data 10 | 11 | const sections = allMarkdownRemark.edges 12 | .map(lesson => lesson.node.frontmatter) 13 | .sort(sortFn); 14 | 15 | const { frontmatter, html } = markdownRemark; 16 | 17 | const index = sections.findIndex(el => el.path === frontmatter.path); 18 | 19 | const prevLink = 20 | index > 0 ? ( 21 | 22 | {"← " + sections[index - 1].title} 23 | 24 | ) : null; 25 | const nextLink = 26 | index < sections.length - 1 ? ( 27 | 28 | {sections[index + 1].title + " →"} 29 | 30 | ) : null; 31 | return ( 32 |
33 |
34 |

{frontmatter.title}

35 |

{frontmatter.date}

36 |
40 |
41 | {prevLink} 42 | {nextLink} 43 |
44 |
45 |
46 | ); 47 | } 48 | 49 | export const pageQuery = graphql` 50 | query LessonByPath($path: String!) { 51 | markdownRemark(frontmatter: { path: { eq: $path } }) { 52 | html 53 | frontmatter { 54 | path 55 | title 56 | order 57 | section 58 | description 59 | } 60 | } 61 | allMarkdownRemark(limit: 1000) { 62 | edges { 63 | node { 64 | frontmatter { 65 | order 66 | path 67 | title 68 | } 69 | } 70 | } 71 | } 72 | } 73 | `; 74 | -------------------------------------------------------------------------------- /src/util/helpers.js: -------------------------------------------------------------------------------- 1 | function splitSections(str) { 2 | const validSectionTest = /^\d+[A-Z]+$/; 3 | const numbersRegex = /^\d+/; 4 | const lettersRegex = /[A-Z]+$/; 5 | if (!validSectionTest.test(str)) { 6 | throw new Error( 7 | `${str} does not match the section format. It must be , like 16A or 5F (case sensitive)` 8 | ); 9 | } 10 | 11 | return [numbersRegex.exec(str)[0], lettersRegex.exec(str)[0]]; 12 | } 13 | 14 | const getCharScore = str => 15 | str 16 | .split("") 17 | .map((char, index) => char.charCodeAt(0) * 10 ** index) 18 | .reduce((acc, score) => acc + score); 19 | 20 | function sorter(a, b) { 21 | let aOrder, bOrder; 22 | 23 | if (a.attributes && a.attributes.order) { 24 | aOrder = a.attributes.order; 25 | bOrder = b.attributes.order; 26 | } else { 27 | aOrder = a.order; 28 | bOrder = b.order; 29 | } 30 | 31 | const [aSec, aSub] = splitSections(aOrder); 32 | const [bSec, bSub] = splitSections(bOrder); 33 | 34 | // sections first 35 | if (aSec !== bSec) { 36 | return aSec - bSec; 37 | } 38 | 39 | // subsections next 40 | return getCharScore(aSub) - getCharScore(bSub); 41 | } 42 | 43 | module.exports.splitSections = splitSections; 44 | module.exports.sorter = sorter; 45 | --------------------------------------------------------------------------------