Popular New Releases in Video Game
Proton
Proton 7.0-2
ArchiSteamFarm
ArchiSteamFarm V5.2.5.3
byte-buddy
Byte Buddy 1.12.8
baritone
v1.8.1
pokemon-showdown
pokemon-showdown v0.11.7
Popular Libraries in Video Game
by ValveSoftware c++
16918 NOASSERTION
Compatibility tool for Steam Play based on Wine and additional components
by JustArchiNET csharp
7766 Apache-2.0
C# application with primary purpose of farming Steam cards from multiple accounts simultaneously.
by MinecraftForge java
5407 NOASSERTION
Modifications to the Minecraft base files to assist in compatibility between mods.
by raphw java
4838 Apache-2.0
Runtime code generation for the Java virtual machine.
by fogleman go
4772 MIT
NES emulator written in Go.
by fogleman python
4622 MIT
Simple Minecraft-inspired program using Python and Pyglet
by cabaletta java
4053 NOASSERTION
google maps for block game
by PokemonGoF python
3677 MIT
The Pokemon Go Bot, baking with community.
by microsoft java
3672 MIT
Project Malmo is a platform for Artificial Intelligence experimentation and research built on top of Minecraft. We aim to inspire a new generation of research into challenging new problems presented by this unique environment. --- For installation instructions, scroll down to *Getting Started* below, or visit the project page for more information:
Trending New libraries in Video Game
by CaffeineMC java
3168 LGPL-3.0
A Fabric mod designed to improve frame rates and reduce micro-stutter
by IrisShaders java
2036 LGPL-3.0
(WIP) A modern shaders mod for Minecraft intended to be compatible with existing OptiFine shader packs
by XIU2 javascript
1898 GPL-3.0
🐵 自用的一些乱七八糟 油猴脚本~
by doctorray117 typescript
1234 Apache-2.0
Templates to deploy a serverless Minecraft Server on demand in AWS
by sm64pc c
1078
Fork of https://github.com/sm64-port/sm64-port with additional features.
by PorkStudios java
1065 NOASSERTION
Level-of-Detail renderer in Minecraft. Allows for render distances of millions of blocks. (Cubic Chunks-compatible) (WIP)
by FiYHer c
1024 MIT
热门网络游戏辅助开发教程
by EricJMarti python
972 MIT
⚡️ Get notified as soon as your next CPU, GPU, or game console is in stock
by AOF-Dev java
923 NOASSERTION
MCinaBox - A Minecraft: Java Edition Launcher for Android. An Encapsulation of [CosineMath's BoatApp](https://github.com/AOF-Dev/BoatApp).
Top Authors in Video Game
1
31 Libraries
214
2
20 Libraries
721
3
19 Libraries
278
4
17 Libraries
141
5
14 Libraries
236
6
14 Libraries
206
7
13 Libraries
717
8
13 Libraries
105
9
13 Libraries
88
10
13 Libraries
1207
1
31 Libraries
214
2
20 Libraries
721
3
19 Libraries
278
4
17 Libraries
141
5
14 Libraries
236
6
14 Libraries
206
7
13 Libraries
717
8
13 Libraries
105
9
13 Libraries
88
10
13 Libraries
1207
Trending Kits in Video Game
The market size of Global Game Development Software was around USD 957.27 Million in 2020, and research suggests that it would be worth over USD 1,691.82 Million by 2026. The growing game development industry is giving rise to an increase in open-source software in the gaming domain. With the growing competition and the increasing cost of development in the fields of computer games and mobile application development, it is no wonder that open source software is gaining so much popularity. The open-source software is the one in which the source code is available for the public. Instead of paying the license fee to the developers, you can use the open-source software for free. This, in turn, means that the users can modify the system and release the updated version of the software. Open-source software also runs faster and more efficiently, making it a viable alternative for those who can't afford the proprietary alternatives. It is also less likely to cause problems when it's hosted on multiple platforms, which is something to think about if you're going to provide your users with several options for accessing your software. One of the main reasons developers use open-source while game development is that development costs are significantly reduced. In the year 2018, it was found that as many as 96% of applications have an open source component in them. When it comes to game development, where the ideas are plenty, and many people are consuming it, open-source is a boon. It saves the developer a significant amount of time, and they can focus on the idea rather than the coding part of the game. There are some other important aspects that open-source brings to the table, like the stability of the code, knowledge sharing, to name a few. The developers usually ensure that codes are updated and stable in nature so that when other developers choose to build on this, they have a stable code in place. Knowledge sharing is also a key aspect of the open-source gaming industry.
Trending Discussions on Video Game
Python: implement a "software-wide" setting that does not change often without running an if statement in every loop
Is there a better way to write this incredibly long regex, or perform this error check?
Showing highlighted silhouette of mesh ONLY when it is occluded
Extract story plots from Wikipedia
How to return an object property from an array of objects in react
How can you create an empty circle using exclusively CSS?
My images are not being displayed in a row
Deny movement in pygame when player would collide with a wall
How to calculate rotation needed to face an object
Updating A Json in a more efficient way
QUESTION
Python: implement a "software-wide" setting that does not change often without running an if statement in every loop
Asked 2022-Apr-07 at 16:09I want Python to kind of ignore a statement that is unlikely to be called in a function that is often called.
I do not have a formal education in programming, so please excuse my lackluster ability to desribe things. I will try to explain the concept by example.
Say I am writing a video game, first-person shooter, drawing 60 frames per second.
In the settings menu, the user can select whether or not to display the name of other players above their head. If they disable this, I store this value as showplayernames = False
.
Then in my drawing function that outputs the graphics I have:
1def draw():
2 #code that draws the graphics on screen
3 if showplayernames:
4 #code that draws the name of players on screen
5
I call this function 60 times a second, but there is absolutely no point for checking if showplayernames is True 60 times a second. It will not change that often, in fact I could make this a kind of "constant" during play by preventing it to change. If showplayernames is False, then the third and fourth lines of the code are completely redundant, but they are executed nevertheless. The computer isn't smart enough to know it can ignore it, and there is a performance difference: reading a value and then checking if it is false takes time.
I could write two copies of the game (or at least the draw() function), one with only the first two lines when the user selects not to show names in the settings, and another without the if statement, and then run the appropriate one.
1def draw():
2 #code that draws the graphics on screen
3 if showplayernames:
4 #code that draws the name of players on screen
5def draw_with_names():
6 #code that draws the graphics on screen
7 #code that draws the name of players on screen
8
9def draw_without_names():
10 #code that draws the graphics on screen
11
Although looping through either of these 60 times a second is more efficient than running draw()
,this is obviously not the way to go. There are dozens of settings like this.
So how do software and game designers implement these kind of "software-wide" settings efficiently?
ANSWER
Answered 2022-Apr-07 at 15:38not an game designer, but here is my voice. You could store settings inside json file next to you python, but then you need to cover reading, getting right values etc.
You could use Environment variables to store value but that would end up using still "if" in the code.
Game designers use triggers and events to get things done, and on the lowest level I would assume those things also use if's.
system-wide-settings will in the end be used with if's
You could use overwrites based on event/trigger and use "same" draw function in both times but that only complicates code, and we all know to "keep it simple".
Sorry if this is not the answer you were looking for.
QUESTION
Is there a better way to write this incredibly long regex, or perform this error check?
Asked 2022-Mar-19 at 14:12I was trying to find a way to error/style correct a non-standard custom menu file from a decade old video game that I was working on in Notepad++ and this was the best I could come up with.
The below returns any curly brackets that aren't followed by an EOL character or are preceded by anything other than line start and 1-4 tabs, it works fine but seems like it could be a lot more elegant. Any returned brackets are incorrect unless they're the first or last in the file. More tabs are technically okay highly unlikely.
1 (?<!^\t)(?<!^\t\t)(?<!^\t\t\t)(?<!^\t\t\t\t)[{}]|[{}](?!\R)
2
Properly formatted:
1 (?<!^\t)(?<!^\t\t)(?<!^\t\t\t)(?<!^\t\t\t\t)[{}]|[{}](?!\R)
2 Menu "MenuName"
3 {
4 Menu "SubMenuName"
5 {
6 Option "OptionName" "Command"
7 Option "OptionName" "Command"
8 }
9 }
10// This is a comment line
11// [ curly brackets in comment lines are made square so they don't get counted as balancing
12
All curly brackets should be on a separate line by themselves with nothing but preceding tabs. They should also be paired but I've got a plugin handling that.
Improperly formatted:
1 (?<!^\t)(?<!^\t\t)(?<!^\t\t\t)(?<!^\t\t\t\t)[{}]|[{}](?!\R)
2 Menu "MenuName"
3 {
4 Menu "SubMenuName"
5 {
6 Option "OptionName" "Command"
7 Option "OptionName" "Command"
8 }
9 }
10// This is a comment line
11// [ curly brackets in comment lines are made square so they don't get counted as balancing
12 Menu "MenuName"{
13 Menu "SubMenuName"
14 {
15 Option "OptionName" "Command"
16 Option "OptionName" "Command" }
17 }Menu "That bracket would be wrong since the line should end afterwards.
18 { //this would also be wrong
19// Nothing should ever follow a bracket except a End Of Line character.
20
Is there some better way to implement this search/check, considering Notepad++ uses Boost regex and doesn't allow variable-length lookbehinds? Also perhaps keeping in mind that I learned everything I know about regex last night.
The expression also returns the first (no preceding tab) and last (no EOL character) but I'm okay with that particular behavior.
The full content of a file I use as a template:
It loads from a loose file in the data folder, completely as is.
1 (?<!^\t)(?<!^\t\t)(?<!^\t\t\t)(?<!^\t\t\t\t)[{}]|[{}](?!\R)
2 Menu "MenuName"
3 {
4 Menu "SubMenuName"
5 {
6 Option "OptionName" "Command"
7 Option "OptionName" "Command"
8 }
9 }
10// This is a comment line
11// [ curly brackets in comment lines are made square so they don't get counted as balancing
12 Menu "MenuName"{
13 Menu "SubMenuName"
14 {
15 Option "OptionName" "Command"
16 Option "OptionName" "Command" }
17 }Menu "That bracket would be wrong since the line should end afterwards.
18 { //this would also be wrong
19// Nothing should ever follow a bracket except a End Of Line character.
20//DO NOT DELETE, needs a line here for some reason.
21Menu "MenuNameTEMPLATE"
22{
23 Title "TitleName"
24 Option "OptionName" "Command"
25 Divider
26 LockedOption
27 {
28 DisplayName "OptionName"
29 Command "Command"
30 Icon "IconName"
31 PowerReady "PowerIdentifiers"
32 }
33 LockedOption
34 {
35 DisplayName "OptionName"
36 Command "Command"
37 Icon "IconName"
38 Badge "BadgeIdentifiers"
39 }
40 LockedOption
41 {
42 DisplayName "OptionName"
43 Command "Command"
44 Icon "IconName"
45 }
46 Menu "SubMenuName"
47 {
48 Title "TitleName"
49 Option "OptionName" "Command"
50 Option "OptionName" "Command"
51 }
52}
53
ANSWER
Answered 2022-Mar-18 at 16:55I want to start by saying that regex is 100% the wrong tool for this, you want a custom parser to handle both validating your file and parsing it into a model you can then use.
However, with the limitations imposed by your question, the following should do it:
1 (?<!^\t)(?<!^\t\t)(?<!^\t\t\t)(?<!^\t\t\t\t)[{}]|[{}](?!\R)
2 Menu "MenuName"
3 {
4 Menu "SubMenuName"
5 {
6 Option "OptionName" "Command"
7 Option "OptionName" "Command"
8 }
9 }
10// This is a comment line
11// [ curly brackets in comment lines are made square so they don't get counted as balancing
12 Menu "MenuName"{
13 Menu "SubMenuName"
14 {
15 Option "OptionName" "Command"
16 Option "OptionName" "Command" }
17 }Menu "That bracket would be wrong since the line should end afterwards.
18 { //this would also be wrong
19// Nothing should ever follow a bracket except a End Of Line character.
20//DO NOT DELETE, needs a line here for some reason.
21Menu "MenuNameTEMPLATE"
22{
23 Title "TitleName"
24 Option "OptionName" "Command"
25 Divider
26 LockedOption
27 {
28 DisplayName "OptionName"
29 Command "Command"
30 Icon "IconName"
31 PowerReady "PowerIdentifiers"
32 }
33 LockedOption
34 {
35 DisplayName "OptionName"
36 Command "Command"
37 Icon "IconName"
38 Badge "BadgeIdentifiers"
39 }
40 LockedOption
41 {
42 DisplayName "OptionName"
43 Command "Command"
44 Icon "IconName"
45 }
46 Menu "SubMenuName"
47 {
48 Title "TitleName"
49 Option "OptionName" "Command"
50 Option "OptionName" "Command"
51 }
52}
53^(?:[^{}]*|\t{1,4}[{}])$
54
Rather than worry about look-arounds, simply match what you expect to find. See it in action here: https://regex101.com/r/nYNqHw/1
QUESTION
Showing highlighted silhouette of mesh ONLY when it is occluded
Asked 2022-Feb-22 at 09:36so I'm trying to create an online game using Babylon.js but have run into a problem thats got me a little stumped so hoping someone here would be willing to help me out. Please bear with me on this one, i'm a complete newbie with babylon as i've only every worked with THREE.js. Right now my game consists of a scene compromising of multiple meshes with multiple users represented as avatars (created from basic circle geometry for the moment) loaded into an environment. What I want to do is highlight the outline of these avatars ONLY when they are occluded by any other object, meaning that when they are not occluded they look normal with no highlight but when behind an object their highlighted silhouette can be seen by others (including yourself as you can see your own avatar). This is very akin to effects used in many other video games (see example below).
Thus far, based on some googling and forum browsing (Babylonjs outline through walls & https://forum.babylonjs.com/t/highlight-through-objects/8002/4) I've figured out how to highlight the outline of objects using Babylon.HighlighLayer and I know that i can render objects above others via RenderingGroups but I can't seem to figure out how to use them in conjunction to create the effect I want. The best i've managed to do is get the highlighted avatar render above everything but I need just the silhouette not the entire mesh. I'm also constrained by the fact that my scene has many meshes in it that are loaded dynamically and i'm also trying to keep things as optimal as possible. Can't afford to use very computationally expensive procedures.
Anybody know of the best way to approach this? Would greatly appreciate any advice or assistance you can provide.Thanks!
ANSWER
Answered 2022-Feb-22 at 09:36So I asked the same question on the babylon forums which helped me to find a solution. All credit goes to the guy's that helped me out over there but just in case someone else comes across this question seeking an answer, here is a link to that forum question https://forum.babylonjs.com/t/showing-highlighted-silhouette-of-mesh-only-when-it-is-occluded/27783/7
Edit: Ok thought i'd include the two possible solutions here properly as well as their babylon playgrounds. All credit goes to roland & evgeni_popov who came up with these solutions on the forum linked above.
The first solution is easier to implement but slightly less performant than the second solution.
Clone Solution: https://playground.babylonjs.com/#JXYGLT%235
1// roland@babylonjs.xyz, 2022
2
3const createScene = function () {
4const scene = new BABYLON.Scene(engine);
5
6const camera = new BABYLON.ArcRotateCamera('camera', -Math.PI / 2, Math.PI / 2, 20, new BABYLON.Vector3(0, 0, 0), scene)
7camera.attachControl(canvas, true);
8
9const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
10light.intensity = 0.7;
11
12const wall = BABYLON.MeshBuilder.CreateBox('wall', { width: 5, height: 5, depth: 0.5 }, scene)
13wall.position.y = 1
14wall.position.z = -2
15
16const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 2, segments: 32 }, scene)
17sphere.position.y = 1
18
19const sphereClone = sphere.clone('sphereClone')
20sphereClone.setEnabled(false)
21
22const matc = new BABYLON.StandardMaterial("matc", scene);
23matc.depthFunction = BABYLON.Constants.ALWAYS;
24matc.disableColorWrite = true;
25matc.disableDepthWrite = true;
26
27sphereClone.material = matc;
28
29sphere.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE
30sphere.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_STRICT
31
32const hl = new BABYLON.HighlightLayer('hl1', scene, { camera: camera })
33hl.addMesh(sphereClone, BABYLON.Color3.Green())
34hl.addExcludedMesh(wall);
35
36let t = 0;
37
38scene.onBeforeRenderObservable.add(() => {
39 sphere.position.x = 10 * Math.cos(t);
40 sphere.position.z = 100 + 104 * Math.sin(t);
41
42 if (sphere.isOccluded) {
43 sphereClone.setEnabled(true)
44 sphereClone.position.copyFrom(sphere.position);
45 } else {
46 sphereClone.setEnabled(false)
47 }
48
49 t += 0.03;
50})
51
52return scene;
53};
54
This second solution is slightly more performant than above as you don't need a clone but involves overriding the AbstactMesh._checkOcclusionQuery function which is the function that updates the isOccluded property for meshes such that the mesh is always rendered even when occluded. There’s no overhead if you are using the occlusion queries only for the purpose of drawing silhouettes however If you are also using them to avoid drawing occluded meshes then there’s an overhead because the meshes will be drawn even if they are occluded. In which case your probably best of going with the first solution
Non-Clone solution: https://playground.babylonjs.com/#JXYGLT#14
1// roland@babylonjs.xyz, 2022
2
3const createScene = function () {
4const scene = new BABYLON.Scene(engine);
5
6const camera = new BABYLON.ArcRotateCamera('camera', -Math.PI / 2, Math.PI / 2, 20, new BABYLON.Vector3(0, 0, 0), scene)
7camera.attachControl(canvas, true);
8
9const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
10light.intensity = 0.7;
11
12const wall = BABYLON.MeshBuilder.CreateBox('wall', { width: 5, height: 5, depth: 0.5 }, scene)
13wall.position.y = 1
14wall.position.z = -2
15
16const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 2, segments: 32 }, scene)
17sphere.position.y = 1
18
19const sphereClone = sphere.clone('sphereClone')
20sphereClone.setEnabled(false)
21
22const matc = new BABYLON.StandardMaterial("matc", scene);
23matc.depthFunction = BABYLON.Constants.ALWAYS;
24matc.disableColorWrite = true;
25matc.disableDepthWrite = true;
26
27sphereClone.material = matc;
28
29sphere.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE
30sphere.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_STRICT
31
32const hl = new BABYLON.HighlightLayer('hl1', scene, { camera: camera })
33hl.addMesh(sphereClone, BABYLON.Color3.Green())
34hl.addExcludedMesh(wall);
35
36let t = 0;
37
38scene.onBeforeRenderObservable.add(() => {
39 sphere.position.x = 10 * Math.cos(t);
40 sphere.position.z = 100 + 104 * Math.sin(t);
41
42 if (sphere.isOccluded) {
43 sphereClone.setEnabled(true)
44 sphereClone.position.copyFrom(sphere.position);
45 } else {
46 sphereClone.setEnabled(false)
47 }
48
49 t += 0.03;
50})
51
52return scene;
53};
54// roland@babylonjs.xyz, 2022
55
56const createScene = function () {
57const scene = new BABYLON.Scene(engine);
58
59const camera = new BABYLON.ArcRotateCamera('camera', -Math.PI / 2, Math.PI / 2, 20, new BABYLON.Vector3(0, 0, 0), scene)
60camera.attachControl(canvas, true);
61
62const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
63light.intensity = 0.7;
64
65const wall = BABYLON.MeshBuilder.CreateBox('wall', { width: 5, height: 5, depth: 0.5 }, scene)
66wall.position.y = 1
67wall.position.z = -2
68
69const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 2, segments: 32 }, scene)
70sphere.position.y = 1
71
72sphere.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE
73sphere.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_STRICT
74
75const mats = new BABYLON.StandardMaterial("mats", scene);
76sphere.material = mats;
77
78const hl = new BABYLON.HighlightLayer('hl1', scene, { camera: camera })
79hl.addExcludedMesh(wall);
80
81let t = 0;
82
83const cur = BABYLON.AbstractMesh.prototype._checkOcclusionQuery;
84
85scene.onDisposeObservable.add(() => {
86 BABYLON.AbstractMesh.prototype._checkOcclusionQuery = cur;
87});
88
89BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function() {
90 cur.apply(this);
91 return false;
92}
93
94scene.onBeforeRenderObservable.add(() => {
95 sphere.position.x = 10 * Math.cos(t);
96 sphere.position.z = 100 + 104 * Math.sin(t);
97
98 if (sphere.isOccluded) {
99 hl.addMesh(sphere, BABYLON.Color3.Green())
100 mats.depthFunction = BABYLON.Constants.ALWAYS;
101 mats.disableColorWrite = true;
102 } else {
103 hl.removeMesh(sphere);
104 mats.depthFunction = BABYLON.Constants.LESS;
105 mats.disableColorWrite = false;
106 }
107
108 t += 0.03;
109})
110
111return scene;
112};
113
QUESTION
Extract story plots from Wikipedia
Asked 2022-Feb-18 at 21:32I want to extract story plots from the English Wikipedia. I'm only looking for a few (~100) and the source of the plots doesn't matter, e.g. novels, video games, etc.
I briefly tried a few things that didn't work, and need some clarification on what I'm missing and where to direct my efforts. It would be nice if I could avoid manual parsing and could get just issue a single query.
Things I tried 1. markriedl/WikiPlotsThis repo downloads the pages-articles
dump, expands it using wikiextractor, then scans each article and saves the contents of each section whose title contains "plot". This is a heavy-handed method of achieving what I want, but I gave it a try and failed. I had to run wikiextractor inside Docker because there are known issues with Windows, and then wikiextractor failed because there is a problem with the --html flag.
I could probably get this working but it would take a lot of effort and there seemed like better ways.
2. WikidataI used the Wikidata SPARQL service and was able to get some queries working, but it seems like Wikidata only deals with metadata and relationships. Specifically, I was able to get novel titles but unable to get novel summaries.
3. DBpediaIn theory, DBpedia should be exactly what I want because it's "Wikipedia but structured", but they don't have nice tutorials and examples like Wikidata so I couldn't figure out how to use their SPARQL endpoint. Google wasn't much help either and seemed to imply that it's common to setup your own graph DB to query, which is beyond my scope.
4. QuarryThis is a new query service that lets you query several Wikimedia databases. Sounds promising but I was again unable to grab content.
5. PetScan & title downloadThis SO answer says I can query PetScan to get Wikipedia titles, download HTML from Wikipedia.org, then parse that HTML. This sounds like it would work, but PetScan looks intimidating and this involves HTML parsing that I want to avoid if possible.
ANSWER
Answered 2022-Feb-18 at 21:32There's no straightforward way to do this as Wikipedia content isn't structured as you would like it to be. I'd use petscan to get a list of articles based on the category, feed them in to e.g. https://en.wikipedia.org/w/api.php?action=parse&page=The%20Hobbit&format=json&prop=sections iterate through the sections and if the 'line' attribute == 'Plot' then call e.g. https://en.wikipedia.org/w/api.php?action=parse&page=The%20Hobbit&format=json&prop=text§ion=2 where 'section' = 'number' of the section titled plot. That gives you html and I can't figure out how to just get the plain text, but you might be able to make sense of https://www.mediawiki.org/w/api.php?action=help&modules=parse
QUESTION
How to return an object property from an array of objects in react
Asked 2022-Feb-18 at 14:46I have an array of object and I need to get a single property, but it's returning undefined and have no idea why. Does anyone know how to solve?
1 const [questions, setQuestions] = useState({});
2 const [index, setIndex] = useState(0);
3
4 async function handleQuestions() {
5 const fetchQuestions = await fetchTriviaApi();
6 setQuestions(fetchQuestions.results);
7 }
8
9 useEffect(() => {
10 handleQuestions();
11 }, []);
12
Return of questions:
1 const [questions, setQuestions] = useState({});
2 const [index, setIndex] = useState(0);
3
4 async function handleQuestions() {
5 const fetchQuestions = await fetchTriviaApi();
6 setQuestions(fetchQuestions.results);
7 }
8
9 useEffect(() => {
10 handleQuestions();
11 }, []);
12 (5) [{…}, {…}, {…}, {…}, {…}]
130: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
141: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these &quot;Worms&quot; games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
152: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
163: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk&#039;s Pro Skater was released in 1999.', correct_answer: 'True', …}
174: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man&#039;s Tree.', correct_answer: 'True', …}
18length: 5
19
Return of questions[index]:
1 const [questions, setQuestions] = useState({});
2 const [index, setIndex] = useState(0);
3
4 async function handleQuestions() {
5 const fetchQuestions = await fetchTriviaApi();
6 setQuestions(fetchQuestions.results);
7 }
8
9 useEffect(() => {
10 handleQuestions();
11 }, []);
12 (5) [{…}, {…}, {…}, {…}, {…}]
130: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
141: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these &quot;Worms&quot; games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
152: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
163: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk&#039;s Pro Skater was released in 1999.', correct_answer: 'True', …}
174: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man&#039;s Tree.', correct_answer: 'True', …}
18length: 5
19{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
20
Return of questions[index].category: When I try to access any property it returns undefined.
ANSWER
Answered 2022-Feb-18 at 14:41You need to initialize the questions
state to an empty array.
1 const [questions, setQuestions] = useState({});
2 const [index, setIndex] = useState(0);
3
4 async function handleQuestions() {
5 const fetchQuestions = await fetchTriviaApi();
6 setQuestions(fetchQuestions.results);
7 }
8
9 useEffect(() => {
10 handleQuestions();
11 }, []);
12 (5) [{…}, {…}, {…}, {…}, {…}]
130: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
141: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these &quot;Worms&quot; games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
152: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
163: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk&#039;s Pro Skater was released in 1999.', correct_answer: 'True', …}
174: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man&#039;s Tree.', correct_answer: 'True', …}
18length: 5
19{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
20const [questions, setQuestions] = useState([]);
21
And when accessing the items you have to check whether the questions
is populated by the API call.
1 const [questions, setQuestions] = useState({});
2 const [index, setIndex] = useState(0);
3
4 async function handleQuestions() {
5 const fetchQuestions = await fetchTriviaApi();
6 setQuestions(fetchQuestions.results);
7 }
8
9 useEffect(() => {
10 handleQuestions();
11 }, []);
12 (5) [{…}, {…}, {…}, {…}, {…}]
130: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
141: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these &quot;Worms&quot; games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
152: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
163: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk&#039;s Pro Skater was released in 1999.', correct_answer: 'True', …}
174: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man&#039;s Tree.', correct_answer: 'True', …}
18length: 5
19{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg&#039;s real name is &#039;Cordozar Calvin Broadus, Jr.&#039;.', correct_answer: 'True', …}
20const [questions, setQuestions] = useState([]);
21{questions.length > 0 && questions[index].category}
22
QUESTION
How can you create an empty circle using exclusively CSS?
Asked 2022-Feb-16 at 12:49I would like to create an empty half circle in CSS/SASS, here's my code snippet for the half circle, here's the output:
1.half-circle{
2width: 60px;
3height: 120px;
4border-radius: 60px 0 0 60px;
5background: #15DEA5;
6}
1.half-circle{
2width: 60px;
3height: 120px;
4border-radius: 60px 0 0 60px;
5background: #15DEA5;
6}<body>
7
8<div class ="half-circle"></div>
9</body>
But I want to “empty” it from the inside, here's a screenshot of the result I want to achieve:
So is it possible to create an emptied half circles in CSS?
ANSWER
Answered 2022-Feb-16 at 12:191.half-circle{
2width: 60px;
3height: 120px;
4border-radius: 60px 0 0 60px;
5background: #15DEA5;
6}<body>
7
8<div class ="half-circle"></div>
9</body> .half-circle {
10 width: 60px;
11 height: 120px;
12 border-top-left-radius: 110px;
13 border-bottom-left-radius: 110px;
14 border: 10px solid gray;
15 border-right: 0;
16 }
17
HTML:
1.half-circle{
2width: 60px;
3height: 120px;
4border-radius: 60px 0 0 60px;
5background: #15DEA5;
6}<body>
7
8<div class ="half-circle"></div>
9</body> .half-circle {
10 width: 60px;
11 height: 120px;
12 border-top-left-radius: 110px;
13 border-bottom-left-radius: 110px;
14 border: 10px solid gray;
15 border-right: 0;
16 }
17 <body>
18 <div class ="half-circle"></div>
19 </body>
20
QUESTION
My images are not being displayed in a row
Asked 2022-Feb-04 at 08:32In a section of my code I made a row-grid for a part that displays images but when I went to insert and look at the website its not displaying in a row format but in a column and im not sure why. I thought the problem came from it being col-sm-6 but i changed it to col-sm-12 and its still not displaying it. Any reasons why?
1.site-main .project-area {
2 padding: 4rem 0;
3}
4
5.site-main .project-area .button-group button {
6 background: transparent;
7 border: none;
8 font: normal 500 16px/130px var(--lato);
9 text-transform: uppercase;
10}
11
12.site-main .project-area .button-group button+button {
13 padding-left: 3rem;
14}
15
16.site-main .project-area .grid .our-project>title h4 {
17 font: normal 700 25px/12px var(--lato);
18}
1.site-main .project-area {
2 padding: 4rem 0;
3}
4
5.site-main .project-area .button-group button {
6 background: transparent;
7 border: none;
8 font: normal 500 16px/130px var(--lato);
9 text-transform: uppercase;
10}
11
12.site-main .project-area .button-group button+button {
13 padding-left: 3rem;
14}
15
16.site-main .project-area .grid .our-project>title h4 {
17 font: normal 700 25px/12px var(--lato);
18}<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
19
20<section class="project-area">
21 <div class="container">
22 <div class="project title pb-5">
23 <h1 class="h1 text-uppercase title-h1"> Recent Projects</h1>
24 <h1 class="h1 text-uppercase title h1"> Quality Work</h1>
25 </div>
26 <div class="div button-group">
27 <button type="button" class="active">All</button>
28 <button type="button" data-filter=".cars">Cars</button>
29 <button type="button" data-filter=".character">Characters</button>
30 <button type="button">Food</button>
31 <button type="button">Activities</button>
32 </div>
33
34 <div class="row-grid">
35 <div class="col-lg-4 col-md-6 col-sm-6 element-item cars">
36 <div class="our-project">
37 <div class="img">
38 <img src="./img/portfolio/car.jpg" alt="car">
39 </div>
40 <div class="title py-4">
41 <h4 class="text-uppercase">minimul design</h4>
42 <span class="text-secondary">Latest, Popular</span>
43 </div>
44 </div>
45 </div>
46 <div class="col-lg-4 col-md-6 col-sm-12 element-item character">
47 <div class="our-project">
48 <div class="img">
49 <img src="./img/portfolio/images.jpg" alt="car">
50 </div>
51 <div class="title py-4">
52 <h4 class="text-uppercase">video game character</h4>
53 <span class="text-secondary">popular, Portfolio</span>
54 </div>
55 </div>
56 </div>
57 <div class="col-lg-4 col-md-6 col-sm-12 element-item popular">
58 <div class="our-project">
59 <div class="img">
60 <img src="./img/portfolio/ntfs-to-be-professional-gamer-image1.jpg" alt="car">
61 </div>
62 <div class="title py-4">
63 <h4 class="text-uppercase">minimul design</h4>
64 <span class="text-secondary">Latest, Popular</span>
65 </div>
66 </div>
67 </div>
68 <div class="col-lg-4 col-md-6 col-sm-12 element-item popular">
69 <div class="our-project">
70 <div class="img">
71 <img src="./img/portfolio/ntfs-to-be-professional-gamer-image1.jpg" alt="car">
72 </div>
73 <div class="title py-4">
74 <h4 class="text-uppercase">minimul design</h4>
75 <span class="text-secondary">Latest, Popular</span>
76 </div>
77 </div>
78 </div>
79 </div>
80 </div>
81</section>
ANSWER
Answered 2022-Feb-04 at 08:32Changing the class row-grid
to row
makes it work. I don't think Bootstrap has a class called row-grid.
If you are trying to fit all the div elements into one row, just replace the col-lg-4 col-md-6 col-sm-6
and the col-lg-4 col-md-6 col-sm-12
with col
QUESTION
Deny movement in pygame when player would collide with a wall
Asked 2022-Jan-09 at 19:46I've been having trouble with collisions in pygame. Specifically, I have a player and a list of walls, and if they collide, I'm supposed to prevent any more movement in that direction.
I've tried many guides but I can't seem to get this to work myself.
1import pygame
2pygame.init()
3
4win = pygame.display.set_mode((800,600))
5pygame.display.set_caption("Game")
6
7playerX = 380 #Player X coordinate
8playerY = 380 #Player Y coordinate
9playerXVel = 10 #Horizontal Velocity
10playerYVel = 10 #Vertical Velocity
11overworld = (248, 192, 117)
12
13run = True
14
15while run: #The game starts running
16 win.fill(overworld)
17 pygame.time.delay(30)
18
19 for event in pygame.event.get(): #You can stop the game now too
20 if event.type == pygame.QUIT:
21 run = False
22
23 class Player: #This is you
24 def __init__(self):
25 self.rect = pygame.Rect(playerX,playerY,50,50)
26 player = Player()
27
28 class Wall: #The walls
29 def __init__(self, pos):
30 walls.append(self)
31 self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
32 walls = []
33
34 keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
35 if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
36 playerY -= playerYVel
37 if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
38 playerX -= playerXVel
39 if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
40 playerY += playerYVel
41 if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
42 playerX += playerXVel
43
44 #I copied this section of code
45 #Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
46 level = [
47 "WWWWWWWWWWWWWWWW",
48 "W W",
49 "W W",
50 "W W",
51 "W W",
52 "W W",
53 "W W",
54 "W W",
55 "W W",
56 "W W",
57 "W W",
58 "WWWWWWWWWWWWWWWW",
59 ]
60 x = y = 0
61 for row in level:
62 for col in row:
63 if col == "W":
64 Wall((x, y))
65 x += 50
66 y += 50
67 x = 0
68
69 #Drawing every rectangle in :3
70 pygame.draw.rect(win, (0, 255, 0), player.rect)
71 for wall in walls:
72 pygame.draw.rect(win, (143, 41, 3), wall.rect)
73
74 pygame.display.update()
75pygame.quit()
76
So far so good. I have walls, I have a player, and that player can move. The player can, however, walk through the walls.
I want to put a piece of code in that prevents velocity being added or removed if the player collides with a wall. This what I've tried for walking upwards, but it just makes it so that I cannot walk upwards altogether
1import pygame
2pygame.init()
3
4win = pygame.display.set_mode((800,600))
5pygame.display.set_caption("Game")
6
7playerX = 380 #Player X coordinate
8playerY = 380 #Player Y coordinate
9playerXVel = 10 #Horizontal Velocity
10playerYVel = 10 #Vertical Velocity
11overworld = (248, 192, 117)
12
13run = True
14
15while run: #The game starts running
16 win.fill(overworld)
17 pygame.time.delay(30)
18
19 for event in pygame.event.get(): #You can stop the game now too
20 if event.type == pygame.QUIT:
21 run = False
22
23 class Player: #This is you
24 def __init__(self):
25 self.rect = pygame.Rect(playerX,playerY,50,50)
26 player = Player()
27
28 class Wall: #The walls
29 def __init__(self, pos):
30 walls.append(self)
31 self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
32 walls = []
33
34 keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
35 if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
36 playerY -= playerYVel
37 if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
38 playerX -= playerXVel
39 if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
40 playerY += playerYVel
41 if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
42 playerX += playerXVel
43
44 #I copied this section of code
45 #Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
46 level = [
47 "WWWWWWWWWWWWWWWW",
48 "W W",
49 "W W",
50 "W W",
51 "W W",
52 "W W",
53 "W W",
54 "W W",
55 "W W",
56 "W W",
57 "W W",
58 "WWWWWWWWWWWWWWWW",
59 ]
60 x = y = 0
61 for row in level:
62 for col in row:
63 if col == "W":
64 Wall((x, y))
65 x += 50
66 y += 50
67 x = 0
68
69 #Drawing every rectangle in :3
70 pygame.draw.rect(win, (0, 255, 0), player.rect)
71 for wall in walls:
72 pygame.draw.rect(win, (143, 41, 3), wall.rect)
73
74 pygame.display.update()
75pygame.quit()
76 for allwalls in walls:
77 if not player.rect.colliderect(allwalls):
78 playerY -= playerYVel
79
Could anyone tell me what I'm doing wrong/what I should be entering into the code instead to prevent a player from moving through a wall?
ANSWER
Answered 2022-Jan-09 at 19:46Create the objects once before the application loop. You don't need the variables playerX
and playerY
at all. Use player.rect.x
and player.rect.y
instead.
Store the position of the player before moving it. If a collision is detected, restore player position:
1import pygame
2pygame.init()
3
4win = pygame.display.set_mode((800,600))
5pygame.display.set_caption("Game")
6
7playerX = 380 #Player X coordinate
8playerY = 380 #Player Y coordinate
9playerXVel = 10 #Horizontal Velocity
10playerYVel = 10 #Vertical Velocity
11overworld = (248, 192, 117)
12
13run = True
14
15while run: #The game starts running
16 win.fill(overworld)
17 pygame.time.delay(30)
18
19 for event in pygame.event.get(): #You can stop the game now too
20 if event.type == pygame.QUIT:
21 run = False
22
23 class Player: #This is you
24 def __init__(self):
25 self.rect = pygame.Rect(playerX,playerY,50,50)
26 player = Player()
27
28 class Wall: #The walls
29 def __init__(self, pos):
30 walls.append(self)
31 self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
32 walls = []
33
34 keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
35 if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
36 playerY -= playerYVel
37 if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
38 playerX -= playerXVel
39 if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
40 playerY += playerYVel
41 if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
42 playerX += playerXVel
43
44 #I copied this section of code
45 #Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
46 level = [
47 "WWWWWWWWWWWWWWWW",
48 "W W",
49 "W W",
50 "W W",
51 "W W",
52 "W W",
53 "W W",
54 "W W",
55 "W W",
56 "W W",
57 "W W",
58 "WWWWWWWWWWWWWWWW",
59 ]
60 x = y = 0
61 for row in level:
62 for col in row:
63 if col == "W":
64 Wall((x, y))
65 x += 50
66 y += 50
67 x = 0
68
69 #Drawing every rectangle in :3
70 pygame.draw.rect(win, (0, 255, 0), player.rect)
71 for wall in walls:
72 pygame.draw.rect(win, (143, 41, 3), wall.rect)
73
74 pygame.display.update()
75pygame.quit()
76 for allwalls in walls:
77 if not player.rect.colliderect(allwalls):
78 playerY -= playerYVel
79oldPlyerX, oldPlyerY = player.rect.topleft # store player position
80
81keys = pygame.key.get_pressed()
82if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
83 player.rect.y -= playerYVel
84if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
85 player.rect.x -= playerXVel
86if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
87 player.rect.y += playerYVel
88if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
89 player.rect.x += playerXVel
90
91for allwalls in walls:
92 if player.rect.colliderect(allwalls):
93 player.rect.topleft = oldPlyerX, oldPlyerY # restore player position
94
Complete example:
1import pygame
2pygame.init()
3
4win = pygame.display.set_mode((800,600))
5pygame.display.set_caption("Game")
6
7playerX = 380 #Player X coordinate
8playerY = 380 #Player Y coordinate
9playerXVel = 10 #Horizontal Velocity
10playerYVel = 10 #Vertical Velocity
11overworld = (248, 192, 117)
12
13run = True
14
15while run: #The game starts running
16 win.fill(overworld)
17 pygame.time.delay(30)
18
19 for event in pygame.event.get(): #You can stop the game now too
20 if event.type == pygame.QUIT:
21 run = False
22
23 class Player: #This is you
24 def __init__(self):
25 self.rect = pygame.Rect(playerX,playerY,50,50)
26 player = Player()
27
28 class Wall: #The walls
29 def __init__(self, pos):
30 walls.append(self)
31 self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
32 walls = []
33
34 keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
35 if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
36 playerY -= playerYVel
37 if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
38 playerX -= playerXVel
39 if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
40 playerY += playerYVel
41 if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
42 playerX += playerXVel
43
44 #I copied this section of code
45 #Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
46 level = [
47 "WWWWWWWWWWWWWWWW",
48 "W W",
49 "W W",
50 "W W",
51 "W W",
52 "W W",
53 "W W",
54 "W W",
55 "W W",
56 "W W",
57 "W W",
58 "WWWWWWWWWWWWWWWW",
59 ]
60 x = y = 0
61 for row in level:
62 for col in row:
63 if col == "W":
64 Wall((x, y))
65 x += 50
66 y += 50
67 x = 0
68
69 #Drawing every rectangle in :3
70 pygame.draw.rect(win, (0, 255, 0), player.rect)
71 for wall in walls:
72 pygame.draw.rect(win, (143, 41, 3), wall.rect)
73
74 pygame.display.update()
75pygame.quit()
76 for allwalls in walls:
77 if not player.rect.colliderect(allwalls):
78 playerY -= playerYVel
79oldPlyerX, oldPlyerY = player.rect.topleft # store player position
80
81keys = pygame.key.get_pressed()
82if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
83 player.rect.y -= playerYVel
84if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
85 player.rect.x -= playerXVel
86if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
87 player.rect.y += playerYVel
88if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
89 player.rect.x += playerXVel
90
91for allwalls in walls:
92 if player.rect.colliderect(allwalls):
93 player.rect.topleft = oldPlyerX, oldPlyerY # restore player position
94import pygame
95pygame.init()
96
97win = pygame.display.set_mode((800,600))
98pygame.display.set_caption("Game")
99
100playerXVel = 10 #Horizontal Velocity
101playerYVel = 10 #Vertical Velocity
102overworld = (248, 192, 117)
103
104class Player: #This is you
105 def __init__(self):
106 self.rect = pygame.Rect(380,380,50,50)
107player = Player()
108
109class Wall: #The walls
110 def __init__(self, pos):
111 walls.append(self)
112 self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
113walls = []
114
115#I copied this section of code
116#Credit: https://www.pygame.org/project-Rect+Collision+Response-1061-.html
117level = [
118 "WWWWWWWWWWWWWWWW",
119 "W W",
120 "W W",
121 "W W",
122 "W W",
123 "W W",
124 "W W",
125 "W W",
126 "W W",
127 "W W",
128 "W W",
129 "WWWWWWWWWWWWWWWW",
130]
131x = y = 0
132for row in level:
133 for col in row:
134 if col == "W":
135 Wall((x, y))
136 x += 50
137 y += 50
138 x = 0
139
140run = True
141
142while run: #The game starts running
143 win.fill(overworld)
144 pygame.time.delay(30)
145
146 for event in pygame.event.get(): #You can stop the game now too
147 if event.type == pygame.QUIT:
148 run = False
149
150 oldPlyerX, oldPlyerY = player.rect.topleft
151 keys = pygame.key.get_pressed() #To retain the feel of retro video games, I have made it impossible to walk diagonally
152 if keys[pygame.K_w] and not keys[pygame.K_a] and not keys[pygame.K_d]:
153 player.rect.y -= playerYVel
154 if keys[pygame.K_a] and not keys[pygame.K_w] and not keys[pygame.K_s]:
155 player.rect.x -= playerXVel
156 if keys[pygame.K_s] and not keys[pygame.K_a] and not keys[pygame.K_d]:
157 player.rect.y += playerYVel
158 if keys[pygame.K_d] and not keys[pygame.K_s] and not keys[pygame.K_w]:
159 player.rect.x += playerXVel
160
161 for allwalls in walls:
162 if player.rect.colliderect(allwalls):
163 player.rect.topleft = oldPlyerX, oldPlyerY
164
165 #Drawing every rectangle in :3
166 pygame.draw.rect(win, (0, 255, 0), player.rect)
167 for wall in walls:
168 pygame.draw.rect(win, (143, 41, 3), wall.rect)
169
170 pygame.display.update()
171pygame.quit()
172
QUESTION
How to calculate rotation needed to face an object
Asked 2021-Dec-28 at 20:35In case of duplicate - i already readed other posts from stackoverflow. Most of them are asociated with Unity3D, and a lot of them are using keywords like theta/omega .. ect. I can't understand any of that stuff. Also, i have 0 knowledge of those formula symbols so i understand 0% of what i readed.
I experiment making a bot for a video game, the only thing im stuck with is how to get the needed rotation degree till i face the given cordinate. Here i made quick example of my question in programming.
Things that i know in the situation:
- Player1 position
- Player1 rotation
- Player2 position (i need to face this player)
2D map of the situation. Click here
And here is how it looks in c#
1using System;
2
3public class Program
4{
5 // Player 1 cordinates
6 public static float p1x = 2;
7 public static float p1y = 3;
8 public static float p1rotation = 0; // In degrees 0-360
9
10 // Player 2 cordinates
11 public static float p2x = 6;
12 public static float p2y = 4;
13
14 // Player 1 needed degree to face Player 2
15 public static float needed_distance;
16
17 public static void Main()
18 {
19 needed_distance = ??; // no clue how to get this value ...
20 Console.WriteLine("The needed distance is: "+needed_distance);
21
22 }
23}
Please don't mark this as a duplicate, my math skills are even below zero. I can understand better if someone tries to answer me using the example that i made.
ANSWER
Answered 2021-Dec-28 at 20:35You are looking for Math.Atan2 method:
1using System;
2
3public class Program
4{
5 // Player 1 cordinates
6 public static float p1x = 2;
7 public static float p1y = 3;
8 public static float p1rotation = 0; // In degrees 0-360
9
10 // Player 2 cordinates
11 public static float p2x = 6;
12 public static float p2y = 4;
13
14 // Player 1 needed degree to face Player 2
15 public static float needed_distance;
16
17 public static void Main()
18 {
19 needed_distance = ??; // no clue how to get this value ...
20 Console.WriteLine("The needed distance is: "+needed_distance);
21
22 }
23}private static float Rotation(float p1x, float p1y, float p2x, float p2y) =>
24 (float)(Math.Atan2(p1x - p2x, p2y - p1y) * 180.0 / Math.PI + 630) % 360.0f;
25
26private static float Distance(float p1x, float p1y, float p2x, float p2y) =>
27 (float)Math.Sqrt((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));
28
Demo:
1using System;
2
3public class Program
4{
5 // Player 1 cordinates
6 public static float p1x = 2;
7 public static float p1y = 3;
8 public static float p1rotation = 0; // In degrees 0-360
9
10 // Player 2 cordinates
11 public static float p2x = 6;
12 public static float p2y = 4;
13
14 // Player 1 needed degree to face Player 2
15 public static float needed_distance;
16
17 public static void Main()
18 {
19 needed_distance = ??; // no clue how to get this value ...
20 Console.WriteLine("The needed distance is: "+needed_distance);
21
22 }
23}private static float Rotation(float p1x, float p1y, float p2x, float p2y) =>
24 (float)(Math.Atan2(p1x - p2x, p2y - p1y) * 180.0 / Math.PI + 630) % 360.0f;
25
26private static float Distance(float p1x, float p1y, float p2x, float p2y) =>
27 (float)Math.Sqrt((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));
28Console.WriteLine(Rotation(2, 3, 6, 4));
29
Outcome:
1using System;
2
3public class Program
4{
5 // Player 1 cordinates
6 public static float p1x = 2;
7 public static float p1y = 3;
8 public static float p1rotation = 0; // In degrees 0-360
9
10 // Player 2 cordinates
11 public static float p2x = 6;
12 public static float p2y = 4;
13
14 // Player 1 needed degree to face Player 2
15 public static float needed_distance;
16
17 public static void Main()
18 {
19 needed_distance = ??; // no clue how to get this value ...
20 Console.WriteLine("The needed distance is: "+needed_distance);
21
22 }
23}private static float Rotation(float p1x, float p1y, float p2x, float p2y) =>
24 (float)(Math.Atan2(p1x - p2x, p2y - p1y) * 180.0 / Math.PI + 630) % 360.0f;
25
26private static float Distance(float p1x, float p1y, float p2x, float p2y) =>
27 (float)Math.Sqrt((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));
28Console.WriteLine(Rotation(2, 3, 6, 4));
29194.0362548828125
30
So, if player #1 initial rotation1 = 0
(s)he needs to turn at ~ 194
degree. In case of player #1 arbitrary initial rotation1
:
1using System;
2
3public class Program
4{
5 // Player 1 cordinates
6 public static float p1x = 2;
7 public static float p1y = 3;
8 public static float p1rotation = 0; // In degrees 0-360
9
10 // Player 2 cordinates
11 public static float p2x = 6;
12 public static float p2y = 4;
13
14 // Player 1 needed degree to face Player 2
15 public static float needed_distance;
16
17 public static void Main()
18 {
19 needed_distance = ??; // no clue how to get this value ...
20 Console.WriteLine("The needed distance is: "+needed_distance);
21
22 }
23}private static float Rotation(float p1x, float p1y, float p2x, float p2y) =>
24 (float)(Math.Atan2(p1x - p2x, p2y - p1y) * 180.0 / Math.PI + 630) % 360.0f;
25
26private static float Distance(float p1x, float p1y, float p2x, float p2y) =>
27 (float)Math.Sqrt((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));
28Console.WriteLine(Rotation(2, 3, 6, 4));
29194.0362548828125
30float rotation1 = ...;
31
32float requiredRotation = (Rotation(p1x, p1y, p2x, p2y) -
33 (rotation1 % 360f) + 360f) % 360f;
34
QUESTION
Updating A Json in a more efficient way
Asked 2021-Dec-25 at 19:231[
2{"923390702359048212": 5},
3{"462291477964259329": 1},
4{"803390252265242634": 3},
5{"824114065445486592": 2},
6{"832041337968263178": 4}
7]
8
This is a list of user ids that I just randomly made and some sample number that each id has. In this case lets call it a number of goals scored in a season in a video game. As I try to update the amount of goals scored at the end of the game, I have to go in a roundabout way which first gets all the member ids in the server, and then compares it to the data with the following code.
1[
2{"923390702359048212": 5},
3{"462291477964259329": 1},
4{"803390252265242634": 3},
5{"824114065445486592": 2},
6{"832041337968263178": 4}
7]
8amount = 0
9for member in server:
10 if member.id != server.member.id:
11 amount = amount + 1
12 else:
13 print(amount)
14 print(str(member.id), str(server.member.id))
15 print(jsondata[amount][str(server.member.id)])
16 break
17
18jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
19
Is there a better way to do what I am working on? I know I am going to run into problems eventually as I don't list members on the json until they score a goal and also I feel like I am wasting a ton of time with my program by having it check a lot of members (I edited out my real list and made this one to make it easier as nobody needs to see 50+ entries to get the idea). I am still a beginner when it comes to this so please respond in simple terms or leave links to places I can learn more complicated ideas. Thanks
1[
2{"923390702359048212": 5},
3{"462291477964259329": 1},
4{"803390252265242634": 3},
5{"824114065445486592": 2},
6{"832041337968263178": 4}
7]
8amount = 0
9for member in server:
10 if member.id != server.member.id:
11 amount = amount + 1
12 else:
13 print(amount)
14 print(str(member.id), str(server.member.id))
15 print(jsondata[amount][str(server.member.id)])
16 break
17
18jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
19 def goalscored():
20 amount = 0
21 for member in server:
22 if member.id != server.member.id:
23 amount = amount + 1
24 else:
25 print(amount)
26 break
27 with open('Goals.json','w') as f:
28 jsondata = json.load(f)
29 jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
30 json.dump(jsondata,f)
31
32 def firstgoal(server.member.id):
33 with open('Goals.json','w') as f:
34 jsondata = json.load(f)
35 amount = 0
36 goalscored = 1
37 totalmembers = server.members.amount
38 for member in server:
39 if membed.id !=server.member.id:
40 amount = amount + 1
41 if amount == totalmembers:
42 NewScore = {user.id:goalscored}
43 json.dump(NewScore,f)
44
Code that I'm using
ANSWER
Answered 2021-Dec-25 at 19:23Not sure why you couldn't get it work earlier, but storing it as dict would be much, much easier.
1[
2{"923390702359048212": 5},
3{"462291477964259329": 1},
4{"803390252265242634": 3},
5{"824114065445486592": 2},
6{"832041337968263178": 4}
7]
8amount = 0
9for member in server:
10 if member.id != server.member.id:
11 amount = amount + 1
12 else:
13 print(amount)
14 print(str(member.id), str(server.member.id))
15 print(jsondata[amount][str(server.member.id)])
16 break
17
18jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
19 def goalscored():
20 amount = 0
21 for member in server:
22 if member.id != server.member.id:
23 amount = amount + 1
24 else:
25 print(amount)
26 break
27 with open('Goals.json','w') as f:
28 jsondata = json.load(f)
29 jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
30 json.dump(jsondata,f)
31
32 def firstgoal(server.member.id):
33 with open('Goals.json','w') as f:
34 jsondata = json.load(f)
35 amount = 0
36 goalscored = 1
37 totalmembers = server.members.amount
38 for member in server:
39 if membed.id !=server.member.id:
40 amount = amount + 1
41 if amount == totalmembers:
42 NewScore = {user.id:goalscored}
43 json.dump(NewScore,f)
44# file.json
45{
46 "923390702359048212": 5,
47 "462291477964259329": 1,
48 "803390252265242634": 3,
49 "824114065445486592": 2,
50 "832041337968263178": 4
51}
52
53def goalscored():
54 with open("Goals.json", "r") as f:
55 jsondata = json.load(f)
56 # Make sure your id is not int but str
57 if server.member.id not in jsondata: # first goal case
58 jsondata[server.member.id] = 0
59 jsondata[server.member.id] += 1
60
61 with open("Goals.json", "w") as f:
62 json.dump(jsondata, f)
63
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Video Game
Tutorials and Learning Resources are not available at this moment for Video Game