投稿時間:2023-08-28 07:05:10 RSSフィード2023-08-28 07:00 分まとめ(6件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 最低賃金、国の「目安」に大幅上乗せ相次ぐ 山形7円、秋田5円 https://www.itmedia.co.jp/business/articles/2308/28/news068.html itmedia 2023-08-28 06:30:00
海外TECH DEV Community 🎲🎲 Build a simple web game in 10 steps 🚀 https://dev.to/dumebii/build-a-simple-web-game-in-10-steps-1jb8 Build a simple web game in steps Hello and welcome When you journey into web development there are tiers of challenges and conquering javascript is one of them In my experience learning javascript is best done through practice it is possible to watch a ton of tutorial videos you d think you ve got it nailed only to end up with very faulty code In this article we will be building a straightforward javascript game This challenge will have you practicing some beginner and core principles of javascript programming As a bonus you even get a bit of an HTML and CSS lesson Let s kick right into what we d be building Table of Contents       Step        Step        Step        Step        Step        Step        Step        Step        Step        Step Today we d be building the popular British game called The Simon gameI have learned through experience that the secret to solving coding challenges is to first of all understand what s required of you To achieve this we will have to understand how the Simon game works Find a youtube tutorial video here Let me try my best to explain This is primarily a pattern remembrance game This game is in such a way that there are four boxes Each box is a different color The game starts with a Press any key to play heading Once you ve done this a box with a particular color is highlighted and the highlight fades after a millisecond This represents the first pattern You are to click on the box that was highlighted You have successfully remembered the first pattern The game highlights another color But remember it s all about patterns If you click on the following highlighted pattern you fail I learned this the hard way Because this is a game of patterns you have to remember the first color box that was highlighted and start from there Example The patterns show up in this order Blue st highlight play blue Red nd highlight play blue red Green rd highlight play blue red green Blue th highlight play blue red green blue The game keeps going on in a continuous loop until you miss a pattern and then it restarts Get a feel of playing the game hereBecause this is neither an HTML or CSS tutorial I d be dropping a link to the HTML and CSS codes You can grab those get them running in your preferred code editor open up a javascript file and let s get started Step The first thing we have to think about is that we need to define the colors of the buttons In my HTML file you can see that we have four divs with ids of different colors red blue green and yellow to identify each box separately We can do this in our javascript by first of all creating an arrayvar buttonColors red blue green yellow Step We need a way to store the patterns the game is going to come up with and also the pattern that our user is going to be creating by playing the game so that we can keep track of it var gamePattern var userClickedPattern Step We need to create a function that enables the game to choose which of the buttons it wants to add in the sequence We recall from the explanation of the game that this isn t a rigid structure such that the computer spins off random patterns To achieve this let us create our function and get a randomized variable function nextSequence var randomNumber Math floor Math random We are multiplying our random number by so that we can have values between o and Using a Math floor method to remove any floating point from our number Step We need to make use of our randomized variable to help us pick a random index from our buttonColors array We will also need to find a way to add the value of the chosen index the first sequence in the game to our game pattern array var randomChosenColor buttonColors randomNumber gamePattern push randomChosenColor Step Now we are going to add a bit of animation as a visual cue to indicate what color box was chosen by the computer document querySelector randomChosenColor fadeIn fadeOut fadeIn We used the document querySelector to target the HTML element we want What we need is identified with an id hence why we had to use the id selector Furthermore because we are not hardcoding any particular value but letting the computer choose randomly we had to write our code so that the selection is fed from our chosenRandomColor variable Our nextSequence function should look like this function nextSequence userClickedPattern var randomNumber Math floor Math random var randomChosenColor buttonColors randomNumber gamePattern push randomChosenColor document querySelector randomChosenColor fadeIn fadeOut fadeIn Step In addition to the visual aid introduced in our earlier function we can also add some sound cues We will be doing this in our playSound function You can find the sound used for this project at this github repo We will be using the default audio class in javascript function playSound audioName var audio new Audio sounds audioName mp audio play Our function takes a parameter of audioName such that we use this parameter to pass in the value of the name of the audio we want to use After getting hold of the default audio class in javascript we went ahead to get a hold of the different sounds by giving it a filer with our audioName parameter We will see the implementation of this in coming functions Step We need to build a function that helps the track be aware of what button they clicked This is by adding some sort of visual aid clue as to which button was pressed by the user function animatePress currentColor document querySelector currentColor addClass pressed setTimeout function document querySelector currentColor removeClass pressed In our styles css there is a class name pressed What we did here is use javascript to toggle off and on our class pressed Toggling on this class simply increases and decreases opacity Note also that we used the setTimeout function to set the duration for the toggle off and on Step Our game is looking fine so far but there is no way to actually track if the user is following the pattern set by the computer and that is exactly what this next function is for We write our first if statement if gamePattern currentLevel userClickedPattern currentLevel if userClickedPattern length gamePattern length setTimeout function nextSequence In this if statement the conditions we are checking for the concurrency of the index of our game s pattern with the index of our user s pattern This will enable us to know when a user has overshot the sequence or underused It also checks that the length of each of the arrays is the same If both cases prove to be true our earlier function nextSequence is triggered We of course need to close this off with an else statement that checks for when the user doesn t get the sequence correctly else playSound wrong document querySelector body addClass game over setTimeout function document querySelector body removeClass game over document querySelector h text Game over Press Any Key To Restart startOver In this else statement we are triggering another CSS class game over and toggling it off and on There is a commented out function here You will understand it later as it will be explained shortly Our final function should look like this function checkAnswer currentLevel if gamePattern currentLevel userClickedPattern currentLevel if userClickedPattern length gamePattern length setTimeout function nextSequence else playSound wrong document querySelector body addClass game over setTimeout function document querySelector body removeClass game over document querySelector h text Game over Press Any Key To Restart startOver Step We need a way for the user to play the game That is we have to add functionality to our buttons We will be using the click method In the function that is to be included in this method we need to specify a list of things that we want to happen by the functions we have so far document querySelector btn click function var userChosenColour document querySelector this attr id userClickedPattern push userChosenColour playSound userChosenColour animatePress userChosenColour checkAnswer userClickedPattern length When we press this button a bunch of things are going to happen The first thing we are doing is to capture the id of the clicked button and store it in our userChosenColor of our clicked button This is achieved using the this keyword Then we populate our userClickedPattern array of course with whatever color button the user chooses We bring in some of our already defined functions which take in our userChosenColor as arguments Step Finally We need a way to make sure that the user is able to restart the game whenever they miss a sequence We will achieve this with our startOver function We first need to create a variable at the beginning of our file that keeps track of when the game has started or not var started false Then our function becomesfunction startOver gamePattern started false We can see here that in our function we are merely restarting everything and making sure that everything begins on a new slate Please go back to your check answer function and uncomment our startOver We are almost at the end of the road guys The final thing we need is a way to keep track of when our game begins document querySelector document keypress function if started document querySelector h text Level level nextSequence started true Yasssss We are done with our first javascript project Writing this has been an exciting experience I hope you feel the same excitement when you build this game and show it off to your friends Thank you for stopping by Cover photo 2023-08-27 21:47:11
海外TECH DEV Community React TS- How to Use React Contexts for State Management https://dev.to/brdnicolas/react-ts-how-to-use-react-contexts-for-state-management-4mh3 React TS How to Use React Contexts for State ManagementContexts play a pivotal role in React development They enable efficient management of shared state and data across components facilitating seamless communication between different parts of your application Understanding how to harness the power of contexts is paramount for building robust and maintainable React applications What is Contexts  Contexts in React are a mechanism for efficiently passing data through the component tree without manually passing props at each level Think of them like a global chest for your application s data To illustrate this with an everyday example imagine you re planning a family trip Your family members represent different components of your application Instead of calling each family member individually to provide them with the trip details you can use a whiteboard context in your living room where everyone can see the plans Now if you update the departure time on the whiteboard everyone immediately knows about the change In React this is similar to updating data in a context and any component that subscribes to that context will automatically receive the updated information without the need for direct communication between the components It streamlines data sharing and ensures consistency throughout your application much like that handy whiteboard for your family trip planning AdvantagesContexts offer a multitude of advantages in React development making them an indispensable tool for building scalable and maintainable applications Some key benefits include Simplified Data Sharing Contexts eliminate the need for prop drilling making it easy to share data between components at different levels of the component tree Cleaner Code They encourage clean modular code by separating data concerns from presentation concerns resulting in more maintainable and understandable codebases Global State Management Contexts excel at managing global state ensuring that critical application data remains consistent and accessible throughout your entire app Improved Performance By intelligently updating only the components that rely on changed data contexts help optimize performance reducing unnecessary re renders Code Readability Using contexts for state management enhances code readability making it easier to grasp the structure and flow of your application Incorporating contexts into your React projects empowers you to build more efficient maintainable and scalable applications ultimately leading to a better development experience and improved user satisfaction Pratical Case The ChallengeImagine we are building a weather application that displays the current weather conditions for different cities Each city s weather data consists of its name temperature and weather description This is the structure of our app  Now If we want to fetch data in SearchBar tsx and display it in CurrentWeather container tx amp WeekWeather container tsx without context we need to make a state at the top of our App tsx  App tsxexport type WeatherWeekData temperature number export type WeatherData town string current WeatherWeekData week WeatherWeekData function App const weatherData setWeatherData useState lt WeatherData null gt null return lt div className App gt lt Header gt lt SearchBar setWeatherData setWeatherData gt weatherData amp amp lt CurrentWeather town weatherData town temperature weatherData current temperature gt weatherData amp amp lt WeekWeather town weatherData town week weatherData week gt lt Footer gt lt div gt export default App SearchBar tsxtype SearchBarProps setWeatherData weatherData WeatherData gt void export const SearchBar setWeatherData SearchBarProps gt const searchTerm setSearchTerm useState lt string gt const handleOnInputChange event ChangeEvent lt HTMLInputElement gt gt wait s delay before set the term and fetch data setTimeout gt setSearchTerm event target value const fetchData term string gt fetch term then response gt response json then data gt setWeatherData data useEffect gt fetchData searchTerm searchTerm return lt div gt lt input placeholder Find your town value searchTerm onChange handleOnInputChange gt lt div gt CurrentWeather container tsxtype CurrentWeatherProps town string temperature number export const CurrentWeather town temperature CurrentWeatherProps gt return lt div gt lt h gt Current Weather lt h gt lt div gt lt h gt town lt h gt lt p gt temperature °F lt p gt lt div gt lt div gt WeekWeather container tsxtype WeekWeatherProps town string week WeatherWeekData export const WeekWeather town week WeekWeatherProps gt const days Monday Tuesday Wednesday Thursday Friday Saturday Sunday return lt div gt lt h gt WeekWeather Weather lt h gt lt div gt lt h gt town lt h gt lt div gt week map day index gt lt div gt lt h gt Day days index lt h gt lt p gt day temperature °F lt p gt lt div gt lt div gt lt div gt lt div gt As we can see we need to share the state and the setState to make sure that other sister components have the data Unfortunately this solution is not maintainable There are props all over the place and the data is not really centralized SolutionIn order to get a cleaner code we re going to create a context The purpose of this is to store data so that it can be accessed by all components Structure  Create a folder src contexts and create files in the context s folder like this  ExplainationsWeather actions  the list of our actions except GET  setWeather setFavoriteTown and more…Weather provider  This will surround the part of your application that requires access to data It also manages the state itself Weather reducer  He manages the various actions so if you want to modify or add data it s up to him Create all files  Actions weather actions tsimport WeatherData from weather reducer export enum EWeatherActions SET WEATHER SET WEATHER type SetWeather type EWeatherActions SET WEATHER payload WeatherData export const setWeather args WeatherData SetWeather gt type EWeatherActions SET WEATHER payload args export type WeatherActions SetWeatherGood to know setWeather is the action we should call if we want to add the data to our context We export the type to type our reducer Reducer weather reducer tsimport Reducer from react import EWeatherActions WeatherActions from weather actions export type WeatherWeekData temperature number export type WeatherData town string current WeatherWeekData null week WeatherWeekData export type WeatherState weather WeatherData null export const initialState WeatherState weather null export const weatherReducer Reducer lt WeatherState WeatherActions gt state initialState action gt switch action type case EWeatherActions SET WEATHER return state action payload default return state Good to know There is a lot of type but the important thinks are initialState and weatherReducer  initialState  As the name is the initial state of our context We juste put a weather object with our data weatherReducer  It s a simple switch case by action type Provider weather provider tsimport createContext Dispatch ReactNode useContext useMemo useReducer from react import initialState weatherReducer WeatherState from weather reducer import WeatherActions from weather actions type WeatherContext WeatherState amp dispatch Dispatch lt WeatherActions gt const weatherContext createContext lt WeatherContext gt initialState dispatch gt export const useWeatherContext gt useContext weatherContext type WeatherProviderProps children ReactNode export const WeatherProvider children WeatherProviderProps gt const state dispatch useReducer weatherReducer initialState const value WeatherContext useMemo gt state dispatch state return lt weatherContext Provider value value gt children lt weatherContext Provider gt Good to know weathercontext  Not important variable it s juste to make the WeatherProvider useWeatherContext  It s a nickname a shortcut to call our useContext WeatherProvider  Our state we need to surround the part of our app that requires data to limit access and increase performance Use our context Our new App tsx App tsxfunction App return lt div className App gt lt Header gt lt WeatherProvider gt lt SearchBar gt lt CurrentWeather gt lt WeekWeather gt lt WeatherProvider gt lt Footer gt lt div gt export default AppWe have removed all props and enclose the Weather part with WeatherProvider to share data with To set data SearchBar tsxexport const SearchBar gt const dispatch dispatchWeather useWeatherContext const searchTerm setSearchTerm useState lt string gt const handleOnInputChange event ChangeEvent lt HTMLInputElement gt gt wait s delay before set the term and fetch data setTimeout gt setSearchTerm event target value const fetchData term string gt fetch term then response gt response json then data gt dispatchWeather setWeather data useEffect gt fetchData searchTerm searchTerm return lt div gt lt input placeholder Find your town value searchTerm onChange handleOnInputChange gt lt div gt In this file we take dispatch from useWeatherContext Dispatch is a function that allows you to use one of our defined actions Here we take dispatch and rename it dispatchWeather Renaming the dispatch makes it easier to debug when we have lots of contexts and dispatches To use data CurrentWeather container tsxexport const CurrentWeather gt const weather useWeatherContext if weather return lt div gt Please select a town lt div gt return lt div gt lt h gt Current Weather lt h gt lt div gt lt h gt weather town lt h gt lt p gt weather current temperature °F lt p gt lt div gt lt div gt WeekWeather container tsxexport const WeekWeather gt const weather useWeatherContext const days Monday Tuesday Wednesday Thursday Friday Saturday Sunday if weather return lt div gt Please select a town lt div gt return lt div gt lt h gt WeekWeather Weather lt h gt lt div gt lt h gt weather town lt h gt lt div gt weather week map day index gt lt div gt lt h gt Day days index lt h gt lt p gt day temperature °F lt p gt lt div gt lt div gt lt div gt lt div gt And that s it  We have created and used our own clean context Congratulations Going furtherOnce you ve grasped the basics of React contexts you can take your application development to the next level by exploring advanced topics  localStorage with Contexts Combine the power of contexts with localStorage to persist application state This is particularly useful for maintaining user preferences such as theme choices user settings or even the last state of a user s shopping cart By linking contexts with localStorage you ensure that user specific data is retained between sessions This enhances the user experience by providing continuity and personalization Integration with Redux While React contexts are excellent for managing local component level state Redux is a robust state management library that excels at managing global state across your entire application You can leverage both by using Redux for overarching application state and contexts for more specific component level state management This hybrid approach provides the best of both worlds allowing you to efficiently manage and share data between components while keeping a global state store for complex application level data Testing and Debugging Explore tools and techniques for testing and debugging applications that utilize contexts Libraries like React Testing Library and Redux DevTools can be incredibly valuable in ensuring the reliability and performance of your code ConclusionIn summary React contexts are crucial for efficient data sharing in your applications They simplify code manage global state effectively and boost performance In a practical example we saw how using contexts can drastically clean up your code By mastering contexts you ll build more efficient maintainable apps without losing your readers interest If you enjoyed this tutorial please consider following me for more helpful content Your support is greatly appreciated Thank you X brdnicolas 2023-08-27 21:30:38
海外TECH DEV Community Java: "Pass-by-Value" vs "Pass-by-Reference" - Unraveling the Confusion https://dev.to/iamcymentho/java-pass-by-value-vs-pass-by-reference-unraveling-the-confusion-3gmh Java quot Pass by Value quot vs quot Pass by Reference quot Unraveling the ConfusionUnderstanding how Java handles parameter passing is a common source of confusion among developers In this comprehensive guide we ll dive into the debate of whether Java is pass by value or pass by reference clarifying the concepts with clear code examples and shedding light on the intricacies of Java s parameter passing mechanism The Truth Java is Pass by Value Contrary to the misconception Java is strictly pass by value But the key to understanding this lies in how references are passed Passing Primitive Types Passing Objects References Explaining the Behavior In Java when you pass a primitive type a copy of its value is passed to the method leaving the original variable unchanged When you pass an object reference the reference s value memory address is copied not the object itself This means you can modify the object s properties inside the method but you can t change the reference itself Best Practices Clear Terminology Understand the difference between passing by value and passing by reference to communicate accurately Immutable Objects When passing objects consider making them immutable to prevent unintended modifications Conclusion Java s parameter passing behavior is often debated but it s essential to grasp the nuances By recognizing that Java is pass by value you can confidently navigate how primitive types and object references are handled in different scenarios LinkedIn Account LinkedInTwitter Account TwitterCredit Graphics sourced from amazon 2023-08-27 21:04:29
海外科学 NYT > Science Japan Will Launch XRISM Telescope and SLIM Moon Lander: How to Watch https://www.nytimes.com/2023/08/27/science/japan-space-launch-xrism-slim.html Japan Will Launch XRISM Telescope and SLIM Moon Lander How to WatchThe telescope will help astronomers study some of the most energetic places in the cosmos while the lunar mission will aid the development of Japanese landing technologies 2023-08-27 21:36:47
ニュース BBC News - Home Liverpool flood deaths: Two dead after driving car into floodwater https://www.bbc.co.uk/news/uk-england-merseyside-66635952?at_medium=RSS&at_campaign=KARANGA liverpool 2023-08-27 21:16:18

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)