docs(14): lessons learned in rock-paper-scissors

This commit is contained in:
efim 2023-07-07 05:01:41 +00:00
parent e4a18da5c2
commit 084035fdcb
6 changed files with 170 additions and 232 deletions

View File

@ -70,6 +70,10 @@ This way unfortunately the tag marked with "th:fragement" (and it is getting ren
And I'd really like a way that allows for having a fully displayed static template, which doesn't interfere with rendering.
Also - had to remember to not have space in
content: ["./src/**/*.{html,scala}"],
so that TailwindCSS would also monitor classes in the code
**** first attempt to use partial gragments as replies to htmx requests
I've added logic for transposing the 2x1 card into 1x2 and vice-versa (as an exercise in using htmx).

View File

@ -1,113 +0,0 @@
# Frontend Mentor - Rock, Paper, Scissors solution
This is a solution to the [Rock, Paper, Scissors challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/rock-paper-scissors-game-pTgwgvgH). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [What I learned](#what-i-learned)
- [Continued development](#continued-development)
- [Useful resources](#useful-resources)
- [Author](#author)
- [Acknowledgments](#acknowledgments)
**Note: Delete this note and update the table of contents based on what sections you keep.**
## Overview
### The challenge
Users should be able to:
- View the optimal layout for the game depending on their device's screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser _(optional)_
- **Bonus**: Play Rock, Paper, Scissors, Lizard, Spock against the computer _(optional)_
### Screenshot
![](./screenshot.jpg)
Add a screenshot of your solution. The easiest way to do this is to use Firefox to view your project, right-click the page and select "Take a Screenshot". You can choose either a full-height screenshot or a cropped one based on how long the page is. If it's very long, it might be best to crop it.
Alternatively, you can use a tool like [FireShot](https://getfireshot.com/) to take the screenshot. FireShot has a free option, so you don't need to purchase it.
Then crop/optimize/edit your image however you like, add it to your project, and update the file path in the image above.
**Note: Delete this note and the paragraphs above when you add your screenshot. If you prefer not to add a screenshot, feel free to remove this entire section.**
### Links
- Solution URL: [Add solution URL here](https://your-solution-url.com)
- Live Site URL: [Add live site URL here](https://your-live-site-url.com)
## My process
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- Mobile-first workflow
- [React](https://reactjs.org/) - JS library
- [Next.js](https://nextjs.org/) - React framework
- [Styled Components](https://styled-components.com/) - For styles
**Note: These are just examples. Delete this note and replace the list above with your own choices**
### What I learned
Use this section to recap over some of your major learnings while working through this project. Writing these out and providing code samples of areas you want to highlight is a great way to reinforce your own knowledge.
To see how you can add code snippets, see below:
```html
<h1>Some HTML code I'm proud of</h1>
```
```css
.proud-of-this-css {
color: papayawhip;
}
```
```js
const proudOfThisFunc = () => {
console.log('🎉')
}
```
If you want more help with writing markdown, we'd recommend checking out [The Markdown Guide](https://www.markdownguide.org/) to learn more.
**Note: Delete this note and the content within this section and replace with your own learnings.**
### Continued development
Use this section to outline areas that you want to continue focusing on in future projects. These could be concepts you're still not completely comfortable with or techniques you found useful that you want to refine and perfect.
**Note: Delete this note and the content within this section and replace with your own plans for continued development.**
### Useful resources
- [Example resource 1](https://www.example.com) - This helped me for XYZ reason. I really liked this pattern and will use it going forward.
- [Example resource 2](https://www.example.com) - This is an amazing article which helped me finally understand XYZ. I'd recommend it to anyone still learning this concept.
**Note: Delete this note and replace the list above with resources that helped you during the challenge. These could come in handy for anyone viewing your solution or for yourself when you look back on this project in the future.**
## Author
- Website - [Add your name here](https://www.your-site.com)
- Frontend Mentor - [@yourusername](https://www.frontendmentor.io/profile/yourusername)
- Twitter - [@yourusername](https://www.twitter.com/yourusername)
**Note: Delete this note and add/remove/edit lines above based on what links you'd like to share.**
## Acknowledgments
This is where you can give a hat tip to anyone who helped you out on this project. Perhaps you worked in a team or got some inspiration from someone else's solution. This is the perfect place to give them some credit.
**Note: Delete this note and edit this section's content as necessary. If you completed this challenge by yourself, feel free to delete this section entirely.**

View File

@ -1,119 +0,0 @@
# Frontend Mentor - Rock, Paper, Scissors
![Design preview for the Rock, Paper, Scissors coding challenge](./design/desktop-preview.jpg)
## Welcome! 👋
Thanks for checking out this front-end coding challenge.
[Frontend Mentor](https://www.frontendmentor.io) challenges help you improve your coding skills by building realistic projects.
**To do this challenge, you need a basic understanding of HTML, CSS and JavaScript.**
## The challenge
Your challenge is to build out this Rock, Paper, Scissors game and get it looking as close to the design as possible.
You can use any tools you like to help you complete the challenge. So if you've got something you'd like to practice, feel free to give it a go.
Your users should be able to:
- View the optimal layout for the game depending on their device's screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser _(optional)_
- **Bonus**: Play Rock, Paper, Scissors, Lizard, Spock against the computer _(optional)_
### Rules
If the player wins, they gain 1 point. If the computer wins, the player loses one point.
#### Original
- Paper beats Rock
- Rock beats Scissors
- Scissors beats Paper
#### Bonus
- Scissors beats Paper
- Paper beats Rock
- Rock beats Lizard
- Lizard beats Spock
- Spock beats Scissors
- Scissors beats Lizard
- Paper beats Spock
- Rock beats Scissors
- Lizard beats Paper
- Spock beats Rock
Not sure what Rock, Paper, Scissors, Lizard, Spock is? [Check out this clip from The Big Bang Theory](https://www.youtube.com/watch?v=iSHPVCBsnLw).
Want some support on the challenge? [Join our Slack community](https://www.frontendmentor.io/slack) and ask questions in the **#help** channel.
## Where to find everything
Your task is to build out the project to the designs inside the `/design` folder. You can either choose the `original` designs for the simpler version or the `bonus` designs for the harder version. You will find both mobile and desktop versions of the design to work to. Each file is also named depending on which step in the game the design is for.
The designs are in JPG static format. Using JPGs will mean that you'll need to use your best judgment for styles such as `font-size`, `padding` and `margin`.
If you would like the design files (we provide Sketch & Figma versions) to inspect the design in more detail, you can [subscribe as a PRO member](https://www.frontendmentor.io/pro).
You will find all the required assets in the `/images` folder. The assets are already optimized.
There is also a `style-guide.md` file containing the information you'll need, such as color palette and fonts.
## Building your project
Feel free to use any workflow that you feel comfortable with. Below is a suggested process, but do not feel like you need to follow these steps:
1. Initialize your project as a public repository on [GitHub](https://github.com/). Creating a repo will make it easier to share your code with the community if you need help. If you're not sure how to do this, [have a read-through of this Try Git resource](https://try.github.io/).
2. Configure your repository to publish your code to a web address. This will also be useful if you need some help during a challenge as you can share the URL for your project with your repo URL. There are a number of ways to do this, and we provide some recommendations below.
3. Look through the designs to start planning out how you'll tackle the project. This step is crucial to help you think ahead for CSS classes to create reusable styles.
4. Before adding any styles, structure your content with HTML. Writing your HTML first can help focus your attention on creating well-structured content.
5. Write out the base styles for your project, including general content styles, such as `font-family` and `font-size`.
6. Start adding styles to the top of the page and work down. Only move on to the next section once you're happy you've completed the area you're working on.
## Deploying your project
As mentioned above, there are many ways to host your project for free. Our recommend hosts are:
- [GitHub Pages](https://pages.github.com/)
- [Vercel](https://vercel.com/)
- [Netlify](https://www.netlify.com/)
You can host your site using one of these solutions or any of our other trusted providers. [Read more about our recommended and trusted hosts](https://medium.com/frontend-mentor/frontend-mentor-trusted-hosting-providers-bf000dfebe).
## Create a custom `README.md`
We strongly recommend overwriting this `README.md` with a custom one. We've provided a template inside the [`README-template.md`](./README-template.md) file in this starter code.
The template provides a guide for what to add. A custom `README` will help you explain your project and reflect on your learnings. Please feel free to edit our template as much as you like.
Once you've added your information to the template, delete this file and rename the `README-template.md` file to `README.md`. That will make it show up as your repository's README file.
## Submitting your solution
Submit your solution on the platform for the rest of the community to see. Follow our ["Complete guide to submitting solutions"](https://medium.com/frontend-mentor/a-complete-guide-to-submitting-solutions-on-frontend-mentor-ac6384162248) for tips on how to do this.
Remember, if you're looking for feedback on your solution, be sure to ask questions when submitting it. The more specific and detailed you are with your questions, the higher the chance you'll get valuable feedback from the community.
## Sharing your solution
There are multiple places you can share your solution:
1. Share your solution page in the **#finished-projects** channel of the [Slack community](https://www.frontendmentor.io/slack).
2. Tweet [@frontendmentor](https://twitter.com/frontendmentor) and mention **@frontendmentor**, including the repo and live URLs in the tweet. We'd love to take a look at what you've built and help share it around.
3. Share your solution on other social channels like LinkedIn.
4. Blog about your experience building your project. Writing about your workflow, technical choices, and talking through your code is a brilliant way to reinforce what you've learned. Great platforms to write on are [dev.to](https://dev.to/), [Hashnode](https://hashnode.com/), and [CodeNewbie](https://community.codenewbie.org/).
We provide templates to help you share your solution once you've submitted it on the platform. Please do edit them and include specific questions when you're looking for feedback.
The more specific you are with your questions the more likely it is that another member of the community will give you feedback.
## Got feedback for us?
We love receiving feedback! We're always looking to improve our challenges and our platform. So if you have anything you'd like to mention, please email hi[at]frontendmentor[dot]io.
This challenge is completely free. Please share it with anyone who will find it useful for practice.
**Have fun building!** 🚀

View File

@ -0,0 +1,166 @@
* Frontend Mentor - Rock, Paper, Scissors solution
:PROPERTIES:
:CUSTOM_ID: frontend-mentor---rock-paper-scissors-solution
:END:
This is a solution to the
[[https://www.frontendmentor.io/challenges/rock-paper-scissors-game-pTgwgvgH][Rock,
Paper, Scissors challenge on Frontend Mentor]]. Frontend Mentor
challenges help you improve your coding skills by building realistic
projects.
** Overview
:PROPERTIES:
:CUSTOM_ID: overview
:END:
*** The challenge
:PROPERTIES:
:CUSTOM_ID: the-challenge
:END:
Users should be able to:
- View the optimal layout for the game depending on their device's
screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser
/(optional)/
- *Bonus*: Play Rock, Paper, Scissors, Lizard, Spock against the
computer /(optional)/
*** Screenshot
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[screenshot-desktop.png]]
[[screenshot-mobile.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- Solution URL
- [[https://efim-frontendmentor-rock-paper-scissors.onrender.com/][Live Site URL]]
** My process
:PROPERTIES:
:CUSTOM_ID: my-process
:END:
*** Built with
:PROPERTIES:
:CUSTOM_ID: built-with
:END:
- Semantic HTML5 markup
- TailwindCSS, css animations
- Flexbox & CSS Grid
- Mobile-first workflow
- SSR on Scala with Cask
- Thymeleaf templates
- htmx for partial page updates and interactivity
*** What I learned
:PROPERTIES:
:CUSTOM_ID: what-i-learned
:END:
**** for template fragement styling - using CSS vars in <style> tag
Allows for "initial" fragment specification to have static styling for viewing the page directly.
This is useful for fragments that should have different stylings, like hand selection badges - should have different colors, so colors are specified in the code and passed as css var values via "th:style".
Ordinary "style" attribute allows the tag which is marked by "th:fragment" to be viewed with some default styles. This is needed because for the "static" view of the page, browser ignores "th:fragment" attribute and just renders what it knows, as well as 'paper' and 'rock' badges, which are marked by "th:remove='all'" tag, which means they are only present in the "mockup static view"
But! Syling sizes this way seems to be an error, i don't want to specify 8rem in my code for the fragments, and that also makes styling of responsive design complicated. I guess I'll want the fragment itself occupy "all parent" and control the size of parent from html where the fragment is inserted.
**** different htmx controls:
***** the hx-get on the click
substitutes the hand selection part of the page to the initial "showdown" - with selected hand and animated wait on the "house choice".
***** on load + delay:3s hx-get
on "wait for house choice" fragemnt
means the "get house choice" rest method executed automatically, and generates random choice.
I'm substituting both hands \ whole 'showdown table' so i'm passing also a players choice into '/house-choice' rest endpoint.
I could only substitue the house choice badge and the message, that would have been a simpler design.
***** i wanted for message to show up with delay
so initially i though I'll do another timed on load request to fetch message, but figured that i could use css animation to fade the message in.
***** handling state of the fragment
Creating a scala object "ShowdownState" allows for setting single variable into context, and then at least "having all attributes of state" is enforced by scala compiler.
In documentaion i found that there's a shorthand for referencing attributes of single object:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expressions-on-selections-asterisk-syntax
So i could set "th:object="${showdownState}"
and then reference directly it's attributes by "*{playersChoice}"
This can mitigate untyped nature of template variables.
***** I got more experience with laying out template fragments.
Putting 'showdown table' into separate file definitely helped, styling in the opened static file is nice.
I'm not sure how much separate files are necessary. Maybe state of "player hand is present, house hand is not present" separate of "showdown and both hands are present" would be easier for styling. Because fragments could be shown at the page.
Negative side of that - all other "not for render" parts of the page would have to be styled and kept in sync with the parts of pages for styling.
Maybe I'll do put some bigger fragments into separate files, but not recrete the outer page for them, just keep them in center of blank page.
***** Triggering client events from HTMX
https://htmx.org/headers/hx-trigger/
Adding header to REST response will trigger js event in the page.
#+begin_src scala
cask.Response(
result,
headers = Seq(
"Content-Type" -> "text/html;charset=UTF-8",
"HX-Trigger-After-Settle" -> s"""{"updateScore": ${showdownState.scoreChange}}"""
)
)
#+end_src
This is a way to pass data from server into js code, executing on client.
For exmaple +1 \ +0 \ -1 for the score change.
***** Using small js scripts for browser functions
I.e updating score, saving it into local storage and loading.
Two simple scripts directly near the html markup which contains the score:
#+begin_src html
<script type="text/javascript">
document.body.addEventListener("updateScore", function (evt) {
let scoreElement = document.querySelector("#the-score-number");
let newScore =
parseInt(scoreElement.textContent) + evt.detail.value;
console.log(
`the score will update by ${evt.detail.value} to ${newScore}`
);
localStorage.setItem("score", newScore);
scoreElement.textContent = newScore;
});
</script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", (event) => {
let scoreElement = document.querySelector("#the-score-number");
let storedScore = localStorage.getItem("score");
if (storedScore !== null) {
scoreElement.textContent = storedScore;
} else {
scoreElement.textContent = 0;
localStorage.setItem("score", 0);
}
});
</script>
#+end_src
And debugging directly in the static preview.
We can create event in the console and fire it from any element:
#+begin_src js
var myEvent2 = new CustomEvent('updateScore', {detail : {value: -1}});
document.body.dispatchEvent(myEvent2)
#+end_src
*** Continued development
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
I could remake the html, to take into account the desktop layout. Which i didn't plan out and just didn't do - right now desktop only shows mobile layout increased in size.
Overall in the future I'd want to practice more with features available in htmx, to know how to make websites with interactivity expected my modern users.
And also - practice integration with js libraries - htmx examples show integration with sortable via events, and many others can be possible.

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB