00
Days
00
Hours
00
Mins
00
Secs
Tutorial Challenge / Ends November 5
🎁 First Prize $100 GC
🎁 Second Prize $50 GC
🎁 Third Prize $25 GC
Posts
Pinned
β–²
15
Guide to Asking Coding Questions
# **Guide to Asking Coding Questions** ## **Why?** Good questions help your question be solved faster, and people will want to answer your question Bad questions waste time, you will often not get answers that you asked for, and people will often ignore your questions ## **Quick Questions Guide** ### Do This - Always ask your questions in English - Explain what you want the code to do - Explain what the code does - Include error messages - Share the repl with the line numbers - When you figure out the answer, update your post ### Don't Do This - Don't post homework questions - Don't use caps in the title - Don't use words like 'HELP' or 'PLEASE' in the title - Don't post questions that have already been answered (Use search box) - Don't post feedback or bugs on Talk, use [repl.it/feedback](https://repl.it/feedback) for feedback, or [repl.it/bugs](https://repl.it/bugs) for bugs ## **Steps For Better Questions** 1. Understand the code - Read your code and figure out what each line does - If a concept is unfamiliar, Google it - You can also use a debugger to help you 2. Describe the problem - Explain what you want the code to do - Explain what the code does (error messages) 3. Provide the code - Share a repl that has your code - Share the line number(s) of your code issue - Make sure that the code you shared has the issue 4. Format code constantly - Make sure you code is easy to read 5. Check for typos - Make sure the code does not have any typos that would cause the problem 6. Explain what you did to troubleshoot the problem - Make a list of what you think the problem is and try to fix your problem by going through the list 7. Make a guess on what you think the problem might be - Use the list from the previous step 8. Proofread the question - Make sure you provided everything - Clear all confusions that you think there might be 9. Update people on the question - If you figured out the answer, edit the post to tell people - When you get an answer, fully understand it - Be nice to people who answer your question - Remember that the people wanted to answer your question, but didn't have to 10. Thing to NOT do - Don't post homework questions - Only post questions in English - Do not use caps in the title - Do not use "HELP" or "PLEASE" in the title - Don't post questions that have already been answered (Use search box) - Don't post feedback or bugs on Talk, use [repl.it/feedback](https://repl.it/feedback) for feedback, or [repl.it/bugs](https://repl.it/bugs) for bugs ## **Example:** ### **Question** We have some Python code with an error: [repl](https://repl.it/@Mosrod/Question-Tutorial) ```python rannumexe = int(input()) if rannumexe = 1: print('hi' + rannumexe) ``` ### Step 1 We show what each line does using comments. ```python rannumexe = int(input()) # Asks the user to input a rannumexe if rannumexe = 1: # If the rannumexe equals 1 print('hi' + rannumexe) # Print hi and the rannumexe ``` ### Step 2 We want the code to input a number, and if the number is one, print "hi" and the number. Our problem is that we have an invalid syntax error on line 2 in the main.py file. ``` File "main.py", line 2 if rannumexe = 1: ^ SyntaxError: invalid syntax ``` ### Step 3 Our repl with the issue is located [here](https://repl.it/@Mosrod/Question-Tutorial). We have an issue on line 2 ### Step 4 We can change "rannumexe" to "number" to clear confusion ```python number = int(input()) # Asks the user to input a number if number = 1: # If the number equals 1 print('hi' + number) # Print hi and the number ``` ### Step 5 We don't have any typos ### Step 6 Our problem could be that we improperly used the if statement ### Step 7 The problem could be about using the if statement incorrectly ### Step 8 Our final question: Title: Invalid syntax error about equal signs Content: I have an invalid syntax error on line 2 in the main.py file of this [repl](https://repl.it/@Mosrod/Question-Tutorial). The program should take a number as an input, check if the number is equal to one, and if so, print "hi" and the number. The error point to the equal signs and I think this issue is with the incorrect syntax of the if statement. Help is appreciated :). ```python number = int(input()) # Asks the user to input a number if number = 1: # If the number equals 1 print('hi' + number) # Print hi and the number ``` ``` File "main.py", line 2 if rannumexe = 1: ^ SyntaxError: invalid syntax ``` Steps based on Gordon Zhu's [post](https://medium.com/@gordon_zhu/how-to-be-great-at-asking-questions-e37be04d0603). If you have any suggestions or feedback, post it in the comments below.
10
posted to Ask by Mosrod (103) 12 days ago
Pinned
β–²
191
πŸ‘‹βœ¨Introduce yourself πŸŽ‰πŸ˜€
Hello everyone! Let's use this thread to get to know each other. Just say hi and a few words about who you are, maybe what are you building or learning with Repl.it. If you're not comfortable sharing anything then share something fun πŸ˜‰
625
posted to Announcements by amasad (554) 3 months ago
Pinned
Challenge Details: Tutorials!
The challenge has begun! Feel free to post your tutorials on the Challenge board! The competition will end on Monday, Nov 5th, 2018 at 12:01 EST. Requirements: * Your submission must be a tutorial. It can be a tutorial about anything - surprise us with your creativity. :) * It must use Repl.it. Attach the end result repl to the post. Prizes: * First Place: $100 Amazon Gift Card * Second Place: $50 Amazon Gift Card * Third Place: $25 Amazon Gift Card First, second, and third place prizes will be determined by the Repl.it team, who will take the following factors into consideration: * Quality of the submission * Number of upvotes it received * How many people engaged with it Additionally, the Repl.it Team will be awarding various prizes for quality submissions that went under the radar. We may even reach out to you for working with Repl.it further! Please remember that Repl Talk allows Markdown, so [style your tutorials](https://repl.it/talk/learn/A-Quick-Guide-to-Replit-Talk-Markdown/7448) for maximum readability!
73
posted to Challenge by timmy_i_chen (361) 15 days ago
Pinned
β–²
65
Rules for Posting - Read me!
Some rules and guidelines to keep in mind as you share your great work on our boards: 1 - Be kind and courteous to others 2 - Make sure that any feedback you provide is constructive. 3 - Outside links are allowed, but you must provide the source. Ideally, things that you post will have been created on Repl.it. 4 - Avoid posting overly promotional material - the focus is, and always will be, a programming, learning, and collaborative community. :) 5 - Don't spam / keep things SFW (Safe For Work). We may revoke your access to these boards if you are found to be in violation of any of these rules. Feel free to ask clarifying questions. Last updated 7/10/18 12:09 PST
32
posted to Share by timmy_i_chen (361) 4 months ago
Pinned
β–²
7
Weekly Repls #5
Welcome back to the 5th week of awesome repls! It seems like just yesterday we started this series. And do we have some repls for you! @Kaldisberzins [made an improved version of his pathfinder that marks dead ends in a different color - fascinating to watch!](https://repl.it/talk/share/Pathfinder-II/7416) @DrankArizonaIce [created a simple Shakespearean markov chain!](https://repl.it/talk/share/Shakespeare-Wrote-Plays-And-Hes-Dead-Simple-Markov-chain-implementation/7440) @amasad [Created this awesome load-balancer, showing off how you can split a website's load!](https://repl.it/talk/share/Round-robin-load-balancer-with-other-repls-as-backends/7435) @Fhillis [made Breakout using only vanilla JS, no libraries!](https://repl.it/talk/share/BREAKOUT/7386) @tristanbeedell [Really impressed us with this awesome 3D shape render-er. The amount of work put into this is awesome, I 100% wish for you to check it out!](https://repl.it/talk/share/3D-Renderer/7551)
3
posted to Announcements by 21natzil (144) 1 day ago
β–²
19
Making a Phaser Game with HTML5 and JavaScript
# Making a Phaser Game with HTML5 and JavaScript Hi guys! Everybody likes to make games, right? And everybody has their own way of doing it. In this tutorial I wanted to share a very simple, yet effective way to make games in your browser! It should be easy enough for most people with javascript knowledge to follow along and, if you want to investigate further, there are endless possibilities out there! ![image](https://storage.googleapis.com/replit/images/1539468462288_75406edb94f04ca097cc5b4705ccbc85.pn) ### Phaser As Phaser describes itself it is a fast, free and fun open source framework for Canvas and WebGL powered browser games. And it really is! It is super simple to use and is quite easy to set up. No super extensive javascript knowledge is necessary and the process of making games is fun and rewarding. It also comes with tons of extra features that you may need in some more complicated games so while it caters to starters as well, it also does not lack depth if you want to look further. Anything from image editing to complex game mechanic mathematics is possible. ##### Sites to use The official Phaser website is [here](https://phaser.io). Additionally, because we are going to use Phaser 3, the latest release, the examples on the site will most probably not work for v3. If you want some examples of v3 features the link is [here](https://labs.phaser.io/). You should not need the examples during this tutorial but if you want to learn further that is where you start. Google works as well but be careful about which version is being discussed. Version 3 is relatively new and v2 has loads more documentation and examples and tutorials on it. However, I would recommend learning v3 because it is generally better in many ways and the knowledge will last you longer and it will be more current. #### Prerequisites (what you need before doing this tutorial) The pre-requisites are: * A basic understanding of HTML, CSS and Javascript. * Knowledge in Javascript about the `this` keyword. * Some time and patience. * 3 rolls of duct tape. * Lots of cardboard * Creativity ### Let's Get Started! The repl.it project that I will be using for this tutorial is [here](https://repl.it/@kaldisberzins/Phaser-Tutorial) and the website for it if you just wanna play the game is [here](https://phaser-tutorial.kaldisberzins.repl.co/). If you ever get stumped on a step that I take in this tutorial just check the repl and see how the code looks in it. If all else fails a bit of copy-paste will solve your issues. Make a new HTML/CSS/JS repl and follow along... So, first of all we need to include the Phaser script into our website. The only piece of HTML in this tutorial will be the following:`<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>`Just paste this into your project's HTML file right above your script tag that links to `script.js`. The order is important and if you get it wrong nothing will work. If your project is not working you should definitely have a look at the order of your scripts. The Phaser script should be first. With that out of the way, let's get into making our game! The first bit of code is a standard template that is in most simple Phaser games (more advanced ones may use a slightly different structure but the idea is the same). The code looks like this: ```javascript let config = { type: Phaser.AUTO, width: 800, height: 500, physics: { default: 'arcade', arcade: { debug: false } }, scene: { preload: preload, create: create, update: update } }; const game = new Phaser.Game(config); function preload(){ } function create(){ } function update(){ } ``` While this may look alien to you, don't stress. To follow along this tutorial you don't need to understand what everything does exactly. The main things you should pay attention to are: * The three functions at the bottom `preload`, `create` and `update`. These we will fill in with the game's code. * The `width` and `height` properties. You can set these to anything you like, I did not make it `window.innerWidth` and `window.innerHeight` because scaling can quickly become messy. It is easier to make it a fixed width for everybody. So now if you run your repl you should see a black square in your browser window. Success! If you do not, make sure you have the Phaser script in the right place and that you have the code in your `script.js` exactly like above. You should also get a message in the console, something like: ```%c %c %c %c %c Phaser v3.14.0 (WebGL | Web Audio) %c https://phaser.io background: #ff0000 background: #ffff00 background: #00ff00 background: #00ffff color: #ffffff; background: #000000 background: #fff``` This may look awful in the repl.it console but if you open it in a new tab and check the console it should be a colorful banner. ### Loading Assets The `preload` function that we are going to use for this section is where you load your assets. If you want some images or audio (Phaser does that as well) in your game you first have to load it here. This way you are loading all the required assets immediately and you can use them throughout the game. I have made some assets for this tutorial so that you do not need to find or make some yourself. Go [here](https://drive.google.com/drive/folders/1TzRicUBL8V0T_9fPMaNCL6M0UEV51irQ?usp=sharing) and click download like so to get the files: ![image](https://storage.googleapis.com/replit/images/1539468612344_eeb16f0a94e74fa401749d11f7b89333.pn) If you get the files in a `.zip` folder just unzip them and drop them into your repl. Once you have them in your repl we have to load them into our game. The following code in the `preload` function will do the trick: ```javascript this.load.atlas("player", "spritesheet.png", "sprites.json"); this.load.image("platform", "platform.png"); this.load.image("spike", "spike.png"); this.load.image("coin", "coin.png"); ``` The first parameter in all of the functions is the "key" for the image. This key you would use when you need to add the image into the game. You can put it as whatever you want but make sure it is descriptive of the image in some way. I suggest you keep them the same as mine so that later code in my tutorial works for you. The second parameter is the path to the image. Because I put the assets in the same folder as the html and js files the path is just the name of the image. If you put your assets in another folder the file path string would look like `"folder_name/file_name.png"`. You may also have noticed that the first command is a bit different. It loads an __atlas__ and not an image. An atlas is a collection of images put together to make a larger image accompanied by a file that states where all the smaller images are. If you open the file `sprites.json` in the assets I gave you you should see that it contains a bunch of named objects that have x, y, width and height properties among others. Each object is an image inside the larger image. In this tutorial we will use the atlas for the player animations. All of the frames for the player (in our case only three) are in the `spritesheet.png` file. The third parameter for the atlas is the path to the `.json` file which we looked at already. If you now run the current code the screen should remain black and no errors should be in the console. If you see a web audio warning that is fine, it does not mean anything important. It's just chrome messing with you. ### Adding Objects to Our Game The `create` function is where the building of our game happens. It is run right after `preload` and is run only once. If you want to add an object to the game, this is where you do it. If you want to repeatedly create some object. Make a function (read below) that creates the object and run that as may times as you like. So we now have loaded some images but we need to have something happen on the screen. Let's add a function in the `create` function that will spawn our player in. Add this code to the `create`function: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); } this.spawnPlayer(); ``` I put this in a seperate function so that we can spawn the player multiple times. We are saving the player to __`this`__ which is the Phaser game object so that we can access it from anywhere. The function itself creates a sprite (image/object) that is in the Phaser physics system. The parameters are: 1. X position 2. Y position 3. Image key 4. (optional) If the image is an atlas, which frame in the atlas. There may be a few more parameters but those are not important for this tutorial. The way we find out which frame is which in the atlas is by looking at the `sprites.json` file. Find an object and look at its x and y properties. For example `sprite_2` has the following object: ```javascript "sprite_2":{"frame":{"x":0,"y":0,"w":48,"h":64}... ``` We can see that the x and y coordinates of the frame are `0, 0`. This means that it will be in the top left corner. If you look at the top left corner of the `spritesheet.png` image you will see which frame is `sprite_2`. Try changing the last parameter in the add function to be `sprite_2`. You will see that it has changed. ##### Adding a Background If the only background color we could have would be black Phaser would look really bad. Luckily enough, Phaser has an easy way to add a background to our game. Just add this code to the top of your `create` function above the `spawnPlayer` function: ```javascript this.cameras.main.setBackgroundColor('#ffffff'); ``` This sets the background color for our main camera to white. If you have not used hex color codes before don't worry about it, just know that `#ffffff` is white. The only problem with that is that now we can't see where our canvas windw starts and ends. We can fix this with a little CSS: ```css canvas{ border: 1px solid black; } ``` Now if you run your code it should look something like this: ![image](https://storage.googleapis.com/replit/images/1539468654218_bf2de4d9dc55069fde105a14f6c9818a.pn) You can see we have our little character in the middle of the screen. The background is now white. You may have noticed that the character is not offset to a side even though we put in the coordinates for the center of the screen. This is because Phaser draws images from their center. This makes it easier to center images. Another simple thing we can add to the game is a camera that follows the player. This is quite easy to do in Phaser: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); this.cameras.main.startFollow(this.player); }; this.spawnPlayer(); ``` The function should be quite self-explanatory and if you run it you should see no change for now. As long as you do not get any errors you are fine. ### Adding Platforms Before we start I wanted to show you the most basic way to add an image to the game. The method used above has a very specific use case (only for sprites). Here is a more general use way of doing it: ```javascript // This goes beneath the spawnPlayer function call this.platform = this.add.image(404, 302, "platform"); ``` This is good for some simple use cases like for example a logo image in your title screen. However it has its shortcomings. Imagine you want to create a map of these platforms. You would have to add `platform1` `platform2` and so on... It would be a nightmare. Let's not get started on collisions. So by now you can see why we are not going to use this to add our platforms. Instead we will have a group. Defining a new group is easy. Remove the above code and add this instead. ```javascript this.platforms = this.physics.add.staticGroup(); ``` Currently we are just defining a new static (non-moving) group and assigning it to the variable `this.platforms`. If you run this now the platform image will disappear. That is because we need to add some platforms to the group. This can be done simply like this: ```javascript //Below the spawnPlayer function this.platforms = this.physics.add.staticGroup(); this.platfroms.create(404, 302, "platform"); ``` There we go! Now we have our platform back! But what is the benefit? In a moment when we deal with collisions you will see why. For now we will leave the platforms and get back to them later. ### Keyboard Inputs As you have probably gathered by now, Phaser has made its own version of everything you may need when developing games. Keyboard inputs are no exception. Phaser even supports many ways to do keyboard inputs. We are going to do the shortest and simplest. We are going to have a bunch of variables, one for each key. And we will check each frame if any of the keys are pressed and set velocities accordingly. The code for the keyboard variables in the `create` function looks like this: ```javascript this.key_W = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W); this.key_A = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A); this.key_D = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D); ``` You do not need to understand this, just get the idea of what is happening. When a player presses a key the variable associated with that key will have `isDown` set to `true`. This makes adding keybinds really easy. Now for the rest of this section we are using the `update` function. `update` is your game loop. This function is run very fast repeatedly all throughout your game. This is where you would handle things like movement and other stuff you would want to check every frame. If you would be coding your own physics this would be where you do it. In the `update` function now let's check if the W key is pressed: ```javascript if(this.key_W.isDown){ this.player.setVelocityY(-50); }else{ this.player.setVelocityY(0); } ``` Instead of incrementing or decrementing the Y property of the player we set its velocity. We do this because it sets a velocity within Phaser which has some benefits. First of all Phaser object velocities take into account the frame rate. If every frame you increase the position X of a player, the higher the frame rate the faster the player moves. However, Phaser counteracts this. We do not need to know how, just that no matter the frame rate the player will always move at the same speed. The value we put into `setVelocityY` is the amount of pixels we want it to move in one second. If you run this now you will see that is you press the W key your character will move up. Success! Now let's add keybinds for A and D. This is only a few more lines of code: ```javascript if(this.key_A.isDown){ this.player.setVelocityX(-50); }else if(this.key_D.isDown){ this.player.setVelocityX(50); }else{ this.player.setVelocityX(0); } ``` We have this in a if/else if statement because we don't want to head left and right at the same time. We can only go in one direction or the other. And that's it! We now have linked up our keyboard keys to our Phaser game! Now it's time to deal with physics. ### Game Physics Phaser also has its own physics engine. In fact it has three but we will only use the most basic one for this tutorial. Just simple square and square collisions. Before we can do collisions, how about we add some gravity. We only need it on the player so it would look like this: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); this.player.body.setGravityY(800); this.cameras.main.startFollow(this.player); }; ``` Now if you run your game you will see that the player drops. But he is dropping very slowly. Why so? This is because each frame we are setting his velocity to 0 if the W key is not pressed. Previously that was needed so that he would not just fly away but now we need to remove that bit: ```javascript //In the update function if(this.key_W.isDown){ this.player.setVelocityY(-50); }/*else{ this.player.setVelocityY(0); } NO LONGER NEEDED*/ ``` Now if you run it the player falls a bit faster. You can still fly with W but we will change that in a second. #### Collisions Now that we have gotten gravity mostly out of the way let's make the player collide with the platform that we have. We can do this with one simple line of code. Add this to your `spawnPlayer` function: ```javascript this.physics.add.collider(this.player, this.platforms); ``` That's it. Just one line of code does everything. But if you run this now it will not work. The player will fall right through. And this is actually for a really stupid reason. We are running this code before we add the platforms. All you have to do is move the `spawnPlayer` function __call__ (not the function itself) below where we add the platforms. And Viola! We have the player not falling through the platform. There are some small problems that we should address before moving on. First of all, When we press W we can fly endlessly. That defeats the point of the game. To prevent this all we need to do is to only let us jump when we are on the ground. This is easy to do: ```javascript if(this.key_W.isDown && this.player.body.touching.down)... ``` When the key W is down and the player's body is touching a platform with its bottom it will jump. If you run this now you will see that the player now makes many little jumps if you press W. To make the jumps larger we have to increase the `setVelocitY`: ```javascript if(this.key_W.isDown && this.player.body.touching.down){ this.player.setVelocityY(-550); } ``` And also while we are at it we can make the left/right movement a bit faster: ```javascript if(this.key_A.isDown){ this.player.setVelocityX(-150); }else if(this.key_D.isDown){ this.player.setVelocityX(150); }else{ this.player.setVelocityX(0); } ``` So there we have it! A running and jumping player! Now let's give him a map to run around in. #### Map Building Phaser supports multiple ways to build a map (of course). However, I have decided that it would be better to cook up our own map builder that would work off of a string. Spaces would indicate that at that position there is no platform, 1 would mean that there is, 2 that this is a spawn point for the player and a dot(.) would mean that this is the end of a row. The map I designed looks something like this: ```javascript //At the top of your js file const map = '11111111111111111111111111.'+ '1 1.'+ '1 1.'+ '1 2 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '1 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '1 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '11111111111111111111111111'; ``` You can see that it is a box that is riddled with platforms. How do we turn this into a map? The parser for this that I made is only a few lines of code: ```javascript //Goes instead of the previous platform adding code this.platforms = this.physics.add.staticGroup(); let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } } drawX+=40; } drawY+=40; }); ``` First we split the string that we have into an array of rows using the . that says that a row ends at that point. Then we loop through each row and at each row we loop through each character in the row. If the character is a 1, we add a platform at that place. If the character is 2 we spawn the player. I have a bit more code there that checks if there is a platform to the left or right and that nudges the character to a side just so that the player does not spawn in a platform. Also, you may have noticed that we are calling `spawnPlayer` here with some parameters. These are just x and y coordinates of where to spawn. To make that work we just have to edit the `spawnPlayer` function like so: ```javascript this.spawnPlayer = (x, y)=>{ this.player = this.physics.add.sprite(x, y, "player", "sprite_0"); this.player.body.setGravityY(800); this.cameras.main.startFollow(this.player); }; ``` Now if you run this you should get a map inside of which the player can run around. You can mess around with the map string if you want and design your own map. I would love to see what you come up with in the comments! ### Player Animations A while ago, I mentioned that we would use the atlas for player animations. Now is the time! We have three frames in our atlas and we have only used one. It's time to use the other two. Phaser has its own animation manager (by now you get the idea - Phaser === everything) that makes it super simple to do animations. First we have to set up our animations: ```javascript // At the bottom of the create function this.anims.create({ key:"walk", frames:[{key:"player", frame:"sprite_2"}, {key:"player", frame:"sprite_1"}], frameRate:10, repeat:-1 }); this.anims.create({ key:"stand", frames:[{key:"player", frame:"sprite_0"}], frameRate:1 }); ``` This creates an animation for our player that we can play when we want. The array `frames` is what Phaser will loop though and play. `frameRate` is quite self explanatory - the amount of frames that are played each second. `repeat` with the value -1 will make the animation loop again and again. Not specifying `repeat` will just make it run once. The key is the string that we can use to reference to the animation later. Just the same way as with images. Now let's run the animations when we walk right or left: ```javascript //In the update function if(this.key_A.isDown){ this.player.setVelocityX(-200); this.player.anims.play("walk", true); }else if(this.key_D.isDown){ this.player.setVelocityX(200); this.player.anims.play("walk", true); }else{ this.player.anims.play("stand", true); this.player.setVelocityX(0); } ``` The `true` parameter is just whether if there is already an animation running, should Phaser continue it? If you set this to false you will see that it will just freeze on a frame. That is because every frame it is checking if a key is pressed and then playing the animation. It will start again every frame making it look like it is frozen. Now if you run this you will see that we have a running animation with the legs moving and the hat bobbing up and down. There is only one more problem with the sprite. The player does not flip when he runs to the left. This is an easy fix: ```javascript //In the update function if(this.key_A.isDown){ this.player.setVelocityX(-200); this.player.anims.play("walk", true); this.player.flipX = true; }else if(this.key_D.isDown){ this.player.setVelocityX(200); this.player.anims.play("walk", true); this.player.flipX = false; }else{ this.player.anims.play("stand", true); this.player.setVelocityX(0); } ``` There we go! Now we have a map, player animations, keybinds, physics and most of all - a weird blob of a character who has a hat that flaps in the breeze! ### The Final Step - Spikes and Coins Now let's add some spikes that the player has to dodge and some coins that the player can collect. First, let's add a score counter in the top of the screen that displays our score: ```javascript this.spawnPlayer = (x, y)=>{ this.player = this.physics.add.sprite(x, y, "player", "sprite_0"); this.player.body.setGravityY(800); this.physics.add.collider(this.player, this.platforms); this.cameras.main.startFollow(this.player); //====================================== this.player.score = 0; this.scoreText = this.add.text(0, 0, "Score: "+this.player.score, { fill:"#000000", fontSize:"20px", fontFamily:"Arial Black" }).setScrollFactor(0).setDepth(200); }; ``` `setScrollFactor(0)` will make sure that when our camera moves, the text does not. This way it will always be in the same position in the top-left of the screen. Text is drawn from its top-left (don't ask me why it is one way for one thing and another for another) so drawing it at `0, 0` will put in the top-left corner. `setDepth(200)` will make sure the text always appears on top. We also make a variable for the score of the player that can be increased when we collect a coin. #### Coins Time to make an incentive to run and jump around. Coins will be a `c` in our map string. So, the map would now look like this: ```javascript const map = '11111111111111111111111111.'+ '1 c 1.'+ '1 c c c 1.'+ '1 2 1 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c 1.'+ '1 c 1 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c 1.'+ '1 1 c 1 c 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c c 1.'+ '11111111111111111111111111'; ``` Now to make this work we have to add an option of what to do if the current character is a `c` in our map parser. I added something like this: ```javascript this.platforms = this.physics.add.staticGroup(); //================================== this.coins = this.physics.add.group(); //================================= let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } //================================= }else if(row.charAt(i)==='c'){ this.coins.create(drawX, drawY+10, "coin"); } //================================= drawX+=40; } drawY+=40; }); ``` If you run this you will see that a bunch of little coins appear. But we can't collect them! This is fairly easy to add: ```javascript // Add this after the map parsing code this.physics.add.overlap(this.player, this.coins, this.collectCoin, null, this); ``` This function will check if there is an overlap between two objects. The two objects are the first two parameters. If there is an overlap, it will run the function that is passed in with the third parameter. `null` is just there for reasons and `this` is just passing on the `this` value to the function. We now need to make a function `collectCoin` that will run if there is an overlap: ```javascript this.collectCoin = (player, coin)=>{ player.score+=10; this.scoreText.setText("Score: "+ this.player.score); coin.destroy(); }; ``` If you run this you will see that you can now collect coins and increase your score. Success! There is only one more step before we are done. #### Spikes Time to add some difficulty to the game. We are going to have spikes that if you step on they will clear your score and respawn you. Let's first add them to our map as an `s`: ```javascript const map = '11111111111111111111111111.'+ '1 c 1.'+ '1 c c s c 1.'+ '1 2 1 s 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c s s 1.'+ '1 c 1 s 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c s c c 1.'+ '1 s 1 c 1 c 1 s 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c c 1.'+ '11111111111111111111111111'; ``` And now we can render them into our game: ```javascript this.platforms = this.physics.add.staticGroup(); this.coins = this.physics.add.group(); //================================== this.spikes = this.physics.add.group(); //================================== let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } }else if(row.charAt(i)==='c'){ this.coins.create(drawX, drawY+10, "coin"); //================================== }else if(row.charAt(i)==='s'){ this.spikes.create(drawX, drawY+10, "spike"); } //================================== drawX+=40; } drawY+=40; }); ``` Let's do what we did last time - add an overlap detector between the player and the spikes. The code is pretty much the same: ```javascript //Next to the other overlap checker for the coins this.physics.add.overlap(this.player, this.spikes, this.die, null, this); ``` And now we have to make a function `die` that will be run when the player hits the spike. All we will do is stop the game and display text saying **YOU DIED**: ```javascript this.die = ()=>{ this.physics.pause(); let deathText = this.add.text(0, 0, "YOU DIED", { color:"#d53636", fontFamily:"Arial Black", fontSize:"50px" }).setScrollFactor(0); Phaser.Display.Align.In.Center(deathText, this.add.zone(400, 250, 800, 500)); } ``` `this.physics.pause` is what stops the game. The text adding should be pretty self explanatory. The bit that may be confusing is the line after that. This is the code I used to center the text. It accepts two arguments - the object to center and the zone in which to center it in. `this.add.zone` in turn accepts four arguments - the x, y, width and height of the zone. The x and y are in the center of the screen and the width is the width of the screen and the same for the height. When you run this code and jump on a spike you will see that it shows some big red text saying __YOU DIED__. And there we have it! Our completed game! Make sure to celebrate by wrapping __lots__ of duct tape around some cardboard. That was what the duct tape and cardboard were for. Nothing, really :). ## Final Word Thank you for sticking to the end of this monster of a tutorial. I hope you are proud of what you have made. If you liked this tutorial, please show support by voting for it. If you have any questions, suggestions or if you found a typo don't hesitate to post it in the comments! Also, if you put a spin on the game or make a cool map that be sure to share it! I would love to see what you guys can make out of this :). If you are too lazy to scroll up, the link to the repl that I made is [here](https://phaser-tutorial.kaldisberzins.repl.co/). Also, if you would like me to make some follow up tutorials outside of the competition about some more advanced features like scenes and (multiplayer?) then be sure to leave a comment. If enough people want it I will be sure to make some more tutorials. [email protected]_
15
posted to Challenge by kaldisberzins (94) 3 days ago
β–²
4
How to make a simple website.
First, add a header: <div class="header"> <h1>Header Goes Here</h1> </div> Second, go to the style.css file and change the looks: h1{ color: font color here; font-family: font family here*; font-size: ___px; } * Go to google fonts and do as it says when you pick out a font. Next, add this in the css file: * { box-sizing: border-box; } Then, add more about your website under the first header. <h1>What my Website is about.</h1> <p>More about what my Website is about.</p> If you want you can add a footer too: <div class="footer"> <h2>Footer</h2> </div> Make sure this is all under the "body" tab!
3
posted to Challenge by Cailyn99 (12) about 14 hours ago
β–²
10
StuTech Grants | Get $200 to work on your project!
Hi repl Talk! I’m Theo, a 15-year-old fellow hacker and high-schooler. I’m the founder of StuTech Grants, a nonprofit that gives grants out to students who are building impactful and innovative STEM projects. We get rid of all the pains of traditional grantsβ€” long applications, expense forms, bureaucracy; allowing you to get on with what you do best, making. I started StuTech Grants a few months ago, after trying to start a 3D Printing Club to get kids in my school into STEMβ€” we got about 20 signups for the club, but had to shut it down due to not having a working 3D printer. Our first public grant round for $200 (sponsored by repl.it!) starts tomorrow. and I wanted to invite all of you to apply. It will be judged by some incredible industry leaders, including Ryan Hoover, Geoff Ralston, and others! Applying is simple, fill out the application within the next 4 days, then our panel of judges will vote on Friday night, and you’ll find out whether you won on Saturday! If you’re interested, check our our website: https://grants.stutech.org, there are more details (and a full list of our judges) there.
0
posted to Announcements by theos_space (9) 1 day ago
β–²
8
How To Create a Code Cracker Game in Python
Note: There may be some errors with indents in this tutorial. Correct accordingly. Another Note: if you prefer a video version of this tutorial here it is πŸ˜€! Please like and subscribe! http://bit.ly/CodeCrackerVideoTutorial The code on GitHub: http://bit.ly/GitHubCodeCracker The code on Repl.it: http://bit.ly/TheCodeOnReplit Objective: Generate a random password which is 3 to 5 integers long. Based on the length of the password, we generate the number of lives considering the fact that 'n' integer long password can have n! possible ways of arranging those 'n' numbers. The user has to guess the password based on the computer generated hints provided. First, click on the plus sign in the bottom-right corner of your screen. ![Screenshot 2018-10-14 at 10.06.19 AM](https://storage.googleapis.com/replit/images/1539540877304_6dcae5439ca3431190c660e07a31fc6b.pn) Then, click "Python3" in "Popular", or you can search. Now let's get coding! First, we need to import the modules needed for our code. So type in: import random import time Now we can use the files that the creators made in our code! So we do not have to reinvent the wheel. Let's make our functions to make our program more reusable and easy to understand. We will call these functions later when displaying our hints. Now, we need to let the player have a certain number of tries before the game ends. This is why we need the factorial function. To make it, type in this code: def factorial(n): if n == 0: return True else: return n * factorial(n-1) This code will basically puts this equation into code: n!=nΓ—(nβˆ’1)! or in visuals: ![Facty](https://storage.googleapis.com/replit/images/1539573913398_36a8825d37c77aff0926f4b44d078332.pn) Thanks to Wikipedia for the image. What this code does is that when n, the parameter that the player will input, is 0, the program will stop. If that fails to be true, it subtracts itself until it becomes 0. This is what's called a recursive function (a function which either calls itself or is in a potential cycle of function calls). Now we have to check if the number is even, so we create a function called even. To do so, we type in the following code: def even(num): if num % 2 == 0: return True else: return False Quite straightforward, when the value inputted divided by two leaves a remainder of 0, it returns True, telling the program that the number inputted is even. Now, we need to make a function that counts the number of even numbers. To do so, we type in the following code: def countEven(password): isEven = 0 for x in password: if even(int(x)): isEven += 1 return isEven What this code does is that we use the previous function for them to see if it is even, and it moves the variable isEven up by one. Finally it returns isEven. We also need to make the function that finds the sum. To do so, we type the following code: def Sum(password): _sum_ = 0 for x in password: _sum_ += int(x) return _sum_ In this code, we make the value of the sum in a variable called _sum_ because "sum" is a function in python. And we can't assign a variable the name of a function. This code returns the sum. The final function we are going to make is the product of all the numbers. This works like Sum(), except with multiplication. This is the code: def product(password): producty = 1 for x in password: producty *= int(x) return producty Yay!!! πŸ˜€πŸ˜€πŸ˜€πŸ˜πŸ˜πŸ˜πŸ˜ŠπŸ˜ŠπŸ˜ŠπŸ˜‚ You made all the functions! Now that we've made them, it's time to call them and display them on the screen. We will use concatenation to join the words together, or in other words, concatenate. On this line, we choose the length of the code. integer = random.randint(3, 5) This creates a list of numbers to choose from. chars= "1234567890" This line creates the password. password = random.sample(chars, integer) This determines the lives the player will have. lives = factorial(integer) This defines the sum. _sum_ = Sum(password) Loading print('loading...') time.sleep(random.randint(0, 5)) Taking out all the weird characters (Delete the next line and put print(password) instead and you'll see what I mean.) password = ''.join(password) Notifying player the code is generated. print("CODE GENARATED") Print the hints. print('it is', integer ,'numbers long') print('the sum is', _sum_) producty = product(password) print('the product is', producty) isEven = countEven(password) print('The number of even numbers is', isEven) print('The first number is', int(password[0])) print('The last number is', int(password[-1])) isOdd = integer - isEven print('The number of odd numbers is', isOdd) print('The highest number is', str(max(password))) print('The lowest number is', str(min(password))) print('you have', lives, 'lives') Checking if the player has any lives left. If not, it breaks the program, stopping the game. while lives > 0: answer = input('what is your password') if answer == password: print('OMG, you got it ') print('The password was', password) break if answer != password: lives -= 1 print('you have', lives, 'lives') print('BOO') if lives <= 1: print ('GAME OVER!!!!!') break AND THAT'S IT! You made it! πŸ˜…πŸ˜„πŸ˜ƒπŸ˜…πŸ˜‚πŸ˜ŽπŸ‘ If you viewed this tutorial, please upvote it. It means a lot. Also, I would like to give thanks to a special coding academy called "The Coder School". If you're a kid younger than 18 or 19 you should enroll yourself in there. I couldn't have done it without them.
5
posted to Challenge by laksh5 (29) 2 days ago
β–²
21
How To Create A Black Hole Spiral in Python W/ Turtle
Hello Programmers, This is a innovative and creative way of showing of your programming skills in Python with Turtle by creating this Spiral which later centres into a Black Hole. Step 1 - Import and Name your turtle Step 2 - Create a for - in range and mark anything more than 100 Step 3 - Go forward by 180 or more Step 4 - Go left by 70 or more Step 5 - Go forward by 60 or more Step 6 - Go right by 40 or more Step 7 - Pen up Step 8 - Set position 0,0 Step 9 - Pen down Step 10 - Go right by 2 or more Challenge: Add Colour to make it a Rainbow Spiral There you have it Ten Easy Steps to make a pretty fascinating Black Hole Spiral and impress other programmers.
33
posted to Challenge by nothplus (25) 7 days ago
β–²
12
How to draw Pixel Art on Python with Turtle!
# How to Draw Pixel Art on Python with Turtle! In this Tutorial you shall learn how to create your own pixel art on Python with Turtle, I hope you enjoy. The first step to creating our art is to import turtle and set a background. My personal tip is to use black as it works best with pixel art. Here is model code: ``` import turtle t=turtle.Turtle() wn=turtle.Screen() wn.bgcolor("Black") #Remember Speech Marks. ``` Then, for step 2, we will set the speed of your turtle to be a high value, using this command: ` t.speed(0) ` Then, now the technical aspects are over with, let us get into the real juicy code! First, we must define square. My optimum size after a lot of testing was a 20 by 20 square. You define a function using this piece of code: ``` def square(): for x in range(4): t.forward(20) t.right(90) #Remember Indentation. ``` Then, After that step, we can start making pixel art! To add colours to our squares, we use the begin_fill command. Let me show an example about how this works. ``` def Tetris_Piece_1(): for x in range(4): t.begin_fill() square() t.color("Blue") t.end_fill() t.color("Black") t.forward(20) ``` We created this function. Now we may uses it whenever we like with this command: ` Tetris_Piece_1(). ` This code will make a Horizontal line of 4 pixels, like the Tetris piece! Look at the example below to see Pac-Man also. You've come to the end of the Tutorial. However, if you would like to extend this, here are some ideas. Find a way to define Red_Square or Blue_Square. Make a video-game character. Create a model of a Tetris screen. It has lots of uses, so try it today. Remember to click on Python with Turtle and not python 2.7, Python or Django. I recommend you watch the example in larger screen by pressing Open in Repl.it.
14
posted to Challenge by John_WardWard (20) 4 days ago
β–²
16
Repl.it CodeJam Event #4
Welcome to the fourth Repl.it CodeJam! This challenge that fits every coder from beginning to advanced will have you coding new ideas for a topic that is announced. If you need help, you can ask the Admins, Moderators, or your competitors on the Discord server. If you win this free challenge, you will get to be featured on the newsletter, get an emoji on the Discord server, and get the special role on the Discord server. You'll never want to miss out on this coding opportunity, so sign up, and code away! EVENT DETAILS: Date: Friday October 26th, 6:30pm EDT to Sunday October 28th, 6:30pm EDT Length: 48 hours SignUp Form: https://goo.gl/forms/6iu0iHrMw9cir13q2 Discord Server: https://discord.gg/346Tapr
3
posted to Announcements by Mosrod (103) 4 days ago
β–²
2
Build a WhatsApp bot with Twilio APIs, in 30 minutes πŸ•
A few months ago, I'd started making chatbots on [Telegram](https://t.me) - I'd seen APIs for WhatsApp but they were unoffical and there was a chance for getting your number blocked πŸ“± ❌ A week ago, I saw that [Twilio](https://twilio.com) had an official WhatsApp API. 30 minutes later, I made a [Wikipedia bot on WhatsApp](https://wikibot.4ty2.fun) πŸ‘‡ ![](https://wikibot.surge.sh/Untitled-b9da3f92-94c0-4f97-8afb-787110d8a9d3.png) This is a tutorial to help you make a something like this, and make your own chatbots on WhatsApp πŸŽ“ ## πŸ”‘ Accounts and Keys First, Sign up for [Twilio](https://www.twilio.com/try-twilio) - it's free and you won't need a credit card πŸ’³ ![](https://wikibot.surge.sh/screely-1535885763017-fc654067-9557-4bf7-98b5-4337911ff4ba.png) Once you're done verifying your phone number, select Procuts > Programmable SMS and then continue to name your project. ![](https://wikibot.surge.sh/screely-1535885937977-c5a924ec-8cc3-4430-9345-9b5e1dc74ef3.png) Feel free to skip steps for adding teammates - you won't need that for now. You must now take note of some authentication keys you'll need for building the WhatsApp bot πŸ‘‡ ![](https://wikibot.surge.sh/screely-1535886250966-f68b6cfb-c104-4adf-80e7-4e3f9bd15b5b.png) The final step - setup your WhatsApp Sandbox [here](https://www.twilio.com/console/sms/whatsapp/sandbox) - choose any number, and join your sandbox following instructions on the page. ![](https://wikibot.surge.sh/screely-1535886798623-1dac1ba9-c362-4e49-87ab-7bbb6138e8c7.png) Aaaaaand you're done with credential setup! Don't worry, that was the toughest part of this tutorial πŸ˜› ## πŸš€ Getting Started So that we don't spend too much time on setup, I've created an environment (with repl.it!) you can use within your browser. Head over [here](https://repl.it/@jajoosam/wikibot-start), and wait for a couple of seconds to fork it. Next, open up `server.js` and put in your Account SID and Auth Token, on lines `7` and `8` ```javascript const accountSid ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //Account SID const authToken ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Auth Token ``` You can see, this environment already has dependencies installed, and an `express` server set up. We still need to give Twilio a URL to send incoming messages to, though πŸ”— Let's go back to the [WhatsApp Sandbox](https://www.twilio.com/console/sms/whatsapp/sandbox), and put in a webhook URL for incoming messages. ![](https://wikibot.surge.sh/Untitled-3ed5263b-c6d8-492b-ba08-b4644ab502cf.png) This URL must be what you see on the preview panel of your [repl.it](http://repl.it) project + `/incoming` ![](https://wikibot.surge.sh/Untitled-1779b21f-9100-4942-b732-320dc48c5f76.png) We can now finally read messages that are sent to the bot. Add a simple `console.log()` in your webhook handler πŸ‘‡ ```javascript app.post('/incoming', (req, res) => { console.log(req.body) }); ``` When you send a message to your bot, you should be able to see something like this in your repl console πŸ‘¨β€πŸ’» ![](https://wikibot.surge.sh/Untitled-163eb09e-e6ab-4910-badb-d8aa0aa789f7.png) Building an echo bot would look something like this, using `twiml` to write a message πŸ‘‡ ```javascript app.post('/incoming', (req, res) => { const twiml = new MessagingResponse(); twiml.message(req.body.Body); res.writeHead(200, {'Content-Type': 'text/xml'}); res.end(twiml.toString()); }); ``` But, since we're actually trying to build a useful bot - let's use informative APIs! ## 🌐 Fetching Information DuckDuckGo has an amazing, free instant answer API. It takes in a query and returns back a summary from WikiPedia and more. A few examples πŸ‘‰ [WikiPedia](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=WikiPedia), [Macbook Air](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=MacBook%20Air), [Twilio](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=Twilio) I spent some time creating a decent parser which usually returns information from this API. Try pasting this code in your [repl.it](http://repl.it) project, and your [console](https://dsh.re/f7477c) should have stuff about Trump in it πŸ˜› ```javascript var base = 'https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q='; var query = 'Donald Trump'; request(base + query, function (error, response, body) { body = JSON.parse(body) if(body["Abstract"] == ""){ body["Abstract"]= body["RelatedTopics"][0]["Text"] } var msg = body["Heading"]+"\n\n"+body["Abstract"]; console.log(msg) }); ``` Pretty straight forward, right? πŸ˜„ ## πŸ› οΈ Putting it all together To make our actual bot, all we need to do is get the query from our request - which we can get as `req.body.Body` - and use `twmil` to send across the data we collected in `msg` ```javascript app.post('/incoming', (req, res) => { const twiml = new MessagingResponse(); var base = 'https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q='; var query = req.body.Body; request(base + query, function (error, response, body) { body = JSON.parse(body) if(body["Abstract"] == ""){ body["Abstract"]= body["RelatedTopics"][0]["Text"] } var msg = twiml.message(body["Heading"]+"\n\n"+body["Abstract"]); res.writeHead(200, {'Content-Type': 'text/xml'}); res.end(twiml.toString()); }); }); ``` You now have a fully functionaing WhatsApp bot! Send anything you want to know about your bot πŸ€– and you should see it respond super fast πŸ’¬ ⚑ Adding welcome messages and a little formatting is quite simple, look at the final [repl](https://repl.it/@jajoosam/wikibot) to see how I did it πŸ‘¨β€πŸ’» ## πŸ”— Sharing the bot For others to use this bot, they'll need to join your sandbox first - and send a message just like you did earlier πŸ‘‰ `join <two-words>` You can create links with this text too - For example this link lets you join my bot πŸ‘‡ ``` https://wa.me/14155238886?text=join ultramarine-tapir ``` `14155238886` is my bot's number, while `ultramarine-tapir` is the sandbox phrase. ## ⚑ What's next? Now that you know how to build a bot on WhatsApp, try sending notifications to yourself, and building more useful tools! Twilio has loads of [other mediums](https://www.twilio.com/channels) through message through too! All code for my WikiBot is on [Github](https://github.com/jajoosam/wikibot)! I'm a 15 year old maker πŸ‘¨β€πŸ’» For more cool things to make and to stay update with my progress, sign up for [my newsletter πŸ“§](https://buttondown.email/jajoosam)
0
posted to Challenge by jajoosam (4) about 2 hours ago
β–²
15
Music you guys listen to
Do you regularly listen to music? If so, what genres and artists of music?
37
posted to Ask by JSer (861) 7 days ago
β–²
19
Working Memory Tutorial
This is a tutorial about how to improve your working memory. Before we start you need to know what working memory is. According to google working memory is the part of short-term memory that is concerned with immediate conscious perceptual and linguistic processing basically it is the ability to be given data to memorize it and then to be able to recall it immediately. Before learning some techniques from my tutorial to improve your working memory I want you to go to the bottom of the code and play my memory game. This memory game will give you score and I want you to record this score because after reading my tutorial you are going to play the game again and I am almost 99% sure that you will see some improvement. Now you will learn about how to improve your working memory! # The Link Method ------------------------ The Link Method is one of the easiest mnemonic (a device such as a pattern of letters, ideas, or associations that assists in remembering something.) techniques available, yet quite powerful. To use the link method you just associate items in a list with memorable things which are easy to remember. Let’s say that you want to remember that Surrey is in British Columbia Example: The Devil lives in British Columbia and she got mad. Now the Devil feels SoRRY (Surrey) he bothered her. # The Number/Rhyme System ---------------------------------------- The Number/Rhyme technique is a very simple way of remembering lists of items in a specific order. You can take items in a list and match them so they rhyme as shown below. **1 - Bun** ** 2 - Shoe ** ** 3 - Tree ** ** 4 - Door ** ** 5 - Hive ** ** 6 - Bricks ** **7 - Heaven ** ** 8 - Skate ** ** 9 - Line ** ** 10 - Hen ** ** A - Eh? ** **B - Bee ** etc. # The Number/Shape System -------------------------------------- The Number/Shape system is very similar to the Number/Rhyme system. It is very effective for remembering numbers and is very easy to do . Associate numbers and letters which look like common shapes to the human eye. Example: 0 = ball 1 = stick 2 = swan 3 = butterfly 4 = sailboat 5 = hook 6 = elephant's trunk 7 = boomerang 8 = snowman 9 = balloon on a string # The Alphabet Technique --------------------------------- The Alphabet system is basically the same as the number and shape system but it is used for memorizing letters. You can associate letters with words which sound out the letter here our some examples: A - Ace of spades B - Bee C - Sea D - Diesel engine E - Eagle F - Effluent # The Roman Room Mnemonic --------------------------------------- _This is the most efficient yet hardest one to master on the list._ This method is just to imagine the given set of data in front of you as if it is in a room with you. If you were trying to remember the names of books imagine the books with their names on a bookshelf. # Phone Number Method or Group Method ------------------------------------------------------ I thought of this one myself because it helps me a lot! This method is the best for me. I memorize things in groups as if they were phone numbers. Example: You are given a list of random characters to memorize A,7,9,6,5,4,3,2,D,O instead of just memorizing each one individually memorize them in groups. **(A - 7 - 9) (5 - 4 - 3) (2-D-O)** It is much easier to memorize the 3 small groups then one big one. Now you have learnt how to memorize things more efficiently! Try the game out again using these techniques and see if you can beat the score you got before. I am sure you will! Make sure to leave this tutorial a like and comment your score before you read my tutorial and than your score after! _**PS I will be adding some more methods and this is in its editing stage right now so please ignore typos:). Also if you know any methods that help you memorize stuff please list them below in the comment section! If you enjoyed this tutorial make sure to leave a like!**_
7
posted to Challenge by IEATPYTHON (86) 6 days ago
β–²
21
A Quick Guide to Repl.it Talk Markdown
Guys! In this quick tutorial, I'll be showing you how to make your posts pretty using Markdown styling! # Headers First we'll learn about headers. A header starts with a hashtag symbol `#` followed by a space: ```md # A header ``` Output: # A header Headers can be a variety of sizes. A smaller header starts with more hashtags. The number of hashtags can be 1 to 6: ```md #### A header with 4 hashtags ``` Output: #### A header with 4 hashtags Alternatively, you can also "underline" a text with `=` or `-` to produce headers ```md First header (Same as # First header) -------------- Second header (Same as ## Second header) =========== ``` ___ # Text Styles You can make *italic*, **bold** or ~~strikethrough~~ text. Put the text between a pair of `*` or `_` to make it *italic*. ```md *italic text* _also italic_ ``` Output: *italic text* _also italic_ Put two `*` or `_` on both sides of text to make it **bold**. ```md **bold text** __also bold__ ``` Output: **bold text** __also bold__ You can also do a ~~strikethrough~~ by putting two tildes (`~`) on each side: ```md ~~strikethrough~~ ``` Output: ~~strikethrough~~ It's ok to mix up those stylings: ```md **_~~bold, italic and strikethrough~~_** ``` Output: **_~~bold, italic and strikethrough~~_** ___ # Lists There's two kind of lists in Markdown: **unordered** (bulleted) and **ordered** (numbered). Since repl.it talk Markdown doesn't support ordered lists (sadly), we'll only deal with unordered lists. An unordered list item starts with either a `*`, `+` or `-` followed by a space: ```md * this + that - and stuff ``` Output: * this + that - and stuff Use indentations of 2 spaces to make sublists ```md * list item * sublist item * yet another sublist item ``` Output: * list item * sublist item * yet another sublist item ___ # Links Just paste the URL and it'll work: ```md https://repl.it ``` Output: https://repl.it If you want **custom link text**, try this: `[link text](URL)`: ```md [Repl.it](https://repl.it) ``` Output: [Repl.it](https://repl.it) ___ # Images The Markdown syntax for **images** is pretty simple: `![alt text](URL)`: ```md ![Repl.it logo](https://repl.it/public/images/icon-square.png) ``` Output: ![Repl.it logo](https://repl.it/public/images/icon-square.png) **Wait... what if my image is stored in my computer? It doesn't have a URL!** Well, repl.it provided an easy way to upload images. All you need is to click the **select files** button below to upload it. After that, you'll see the Markdown code for your image in the text box. ___ # Code And finally, code!! **Inline code** and **code blocks** are widely used in repl.it talk since repl.it talk is a platform for coders to share. Wrap a pair of **backticks** (`` ` ``) around text to make a span of code (inline code): ```md `$ node index.js` ``` Output: `$ node index.js` To indicate a block of code, put three backticks (` ``` `) at both the start and end of your code: ````md ``` This is a code block. Everything here is monospaced. ``` ```` Output: ``` This is a code block. Everything here is monospaced. ```` Additionally, repl.it supports code block syntax highlighting, which is pretty useful for emphasizing readability. Just put the language name (or its short form) after the three backticks: ````md ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ```` Output: ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ___ # Blockquotes To do blockquotes put a `>` before each line of the block: ```md > Timchen is the greatest and > we should praise him ``` Output: > Timchen is the greatest and > we should praise him Don't forgot to leave a blank line after each blockquote! ___ # Horzontal rules A horzontal rule (a line that separates content) can be made of either three asterisks (`*`) or underscores (`_`): ```md There's a horizontal rule below *** There's a horizontal rule above ``` Output: There's a horizontal rule below *** There's a horizontal rule above That's all what I can teach in this very tutorial. Start using Markdown to style your posts, and find more about it!
5
posted to Learn by JSer (861) 6 days ago
β–²
15
Pathfinder II
An improved version of my first path finding algorithm. This time it notes down each intersection and makes a choice there. If it later runs into a dead end it will jump back to that intersection and make a different choice. The dead end paths are marked in blue. The red path is the way to the end. It also will first pick a way that leads down because the end is at the bottom. Only if that is a dead end will it chose anther. I also switched out the maze for something a lot bigger because it would solve the smaller maze so fast that you did not get to see it. I recommend you open it in a new tab to see the whole maze. I hope you like it! Post any recommendations in the comments.
18
posted to Share by kaldisberzins (94) 7 days ago
β–²
5
Basic HTML & CSS Tutorial
(Not finished yet) There Is nothing here but if you press this link https://html-tutorial.frdobagins.repl.co You will be amazed
1
posted to Challenge by frdobagins (4) 1 day ago
β–²
13
Basic Platformer With Javascript and HTML
# BASIC PLATFORMER TUTORIAL **End Result:** https://basic-platformer--luchutton.repl.co/ **The Code:** https://repl.it/@LucHutton/Basic-Platformer ## Prerequisites And Advice: For this tutorial you should already have a basic understanding of programming (preferrably in Javascript) as **I will not be explaining basic Javascript concepts in this tutorial.** If you wish to learn some/more Javascript I recommend you visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript ## Setup: It is best if you follow along using a **HTML + CSS + JS REPL**, as when created the REPL will already have all the boiler plate stuff, but also because you will be able to see the result straight away on the same screen (when you run the code). The first (and most important) line of code you will write will be in the ```index.html``` file. Don't worry this is the only bit of HTML you will have to write :). Place the line of code after the opening ```body``` tag but before the ```script``` tag, like so: ```html <body> <canvas id="canvas" width="512" height="512"></canvas> <script src="script.js"></script> </body> ``` Make sure the id of the ```canvas``` is "canvas", but you can change the width and height to whatever number you want as long as the **width and height are multiples of 32!** ---- Navigate yourself to the ```script.js``` file where we will be spending the remainder of this tutorial. The first thing that we need to do is to create a place in which we can store the attributes of the player, this will be done using an **Object**. For starters our player needs to have an X coordinate, a Y coordinate, a Width and a Height. For simplicity's sake the player will be a 32 x 32 pixel square, and the initial X will be set to half the ```canvas``` width, and Y will be set to half the ```canvas``` height. ```javascript const player = { x: 256, y: 256, width: 32, height: 32 } ``` **Make sure the final value doesn't have a comma after it!** At the top of the Javascript file we need to create a reference to the ```canvas``` element we created in the first step like so: ```javascript const c = document.getElementById("canvas").getContext("2d"); ``` It basically gets the ```canvas``` element -> specifys that we will be working in two dimensions -> sets the value of c to that. Now we need a way to draw the player at its location with its size. To do this we will create a **draw function**, inside it we will need to specify the fill colour of the player and how to draw the player. To specify the colour to fill the next object drawn, you update the canvas' fill colour. ```javascript c.fillStyle = "red"; ``` You can set the colour to whatever you want. On the next line you need to actually draw the player rectangle using a canvas function called ```fillRect``` which draws and fills the rectangle at the same time. The ```fillRect``` function takes four parameters in the following order: an x value, a y value, a width and a height. ```javascript c.fillRect(player.x, player.y, player.width, player.height); ``` As shown above, you access the attributes of an object using the template: ```objectName.attribute```. To call this draw function: at the bottom of the Javascript file put: ```javascript draw(); ``` If you followed the steps above correctly your Javascript code should look like this: ```javascript const c = document.getElementById("canvas").getContext("2d"); const player = { x: 256, y: 256, width: 32, height: 32 } function draw(){ c.fillStyle = "red"; c.fillRect(player.x, player.y, player.width, player.height); } draw(); ``` When you run this code you should see a red square appear somewhere in the top-left of your screen. Now remove the line calling the draw function as it was only for testing. --- ## Going Loopy Every meaningful game needs to have a main function that is looped, to update and draw new things so fast that it is almost imperceptible to the human eye. For our game we need a main function that is called when all the updating for one frame is done. So create a function called main, and inside you can put a call to the draw function: ```javascript function main(){ draw(); } ``` In this state the main function will only be called once, to fix this we need to put another line below the call to draw that re-runs the main function. ```javascript function main(){ draw(); requestAnimationFrame(main); } ``` It basically allows the HTML to render what is drawn and then calls the main function again. --- ## Startup If you run the code you will notice that nothing happens, this is because nothing calls the main function in the first place. What we need is something that runs when the page is fully loaded, luckily Javascript has a function just for this: ```javascript window.onload = function(){ main(); } ``` When the page loads, whatever is in the function will be executed, so if you run the code now you should now see the red square appear again! --- ## Level Making And Drawing We will be making this game's level using a tile map based system because it is easy to use and design. The main concept is that there will be a multi-line string with each line being a certain length long filled with either a 0 or a 1 (Air or a Wall). You can define the level variable like: ```javascript const level = `0000000000000000 0000000000000000 0010000000000000 0000000000001111 0000111000000000 0000000000011111 0000000000000000 0000000000111111 0000000000011000 1110000000000000 0000000010000110 0001111111100000 0000000000000000 0000000000000000 0000000001111110 0000000000000000`; ``` This gives us the ability to create multiple levels really easily. Feel free to tweak the positions of the 1s and 0s until you see fit. *Side Note: Levels should really be defined in external text files, but file handling would distract us too much from the making of the game so I decided just to define it in the Javascript.* Before being able to use this level data we need to make a function that parses it into a 2D Array (Arrays within arrays (but only to one layer)). We need to: + Split the string up by line + Split each line up by character + Return that result To split by line and store the result in an array we can do: ```javascript const lines = lvl.split("\n"); ``` Where lvl is the level data that we pass to the function. To split each line in the array by characters we need to use the ```map``` function *(Introduced in ES5)*. ```javascript const characters = lines.map(l => l.split("")); ``` If you are unsure on how to use the ```map``` function refer to [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). The final level-parsing function should look like: ```javascript function parse(lvl){ const lines = lvl.split("\n"); const characters = lines.map(l => l.split("")); return characters; } ``` To make the level data accessible to all of the program we need to define a variable in the global scope, at the top of the Javascript file, below the ```c``` variable, write: ```javascript let currentLevel; ``` This just tells Javascript that we want this variable to be declared but that we don't need to use it yet. In the ```window.onload``` function update the value of ```currentLevel``` to the return value of the parse function: ```javascript window.onload = function(){ currentLevel = parse(level); main(); } ``` Now all we need to do is draw the level! In the draw function we need to loop through each of the level data lines and on each line we need to loop through each character, and if the character is a 1 then we need to draw a square at the position on canvas relative to the character's position. Also before the looping we need to define a new colour for walls! ```javascript function draw(){ c.fillStyle = "red"; c.fillRect(player.x, player.y, player.width, player.height); c.fillStyle = "black"; for (let row = 0; row < currentLevel.length; row++) { for (let col = 0; col < currentLevel[0].length; col++) { if (currentLevel[row][col] === "1") { c.fillRect(col * 32, row * 32, 32, 32); } } } } ``` Here we are using that ```fillRect``` function again, but instead of the player we are drawing each wall tile. If you now run the code you should see squares that match what is written in the level variable. --- ## Handling User Input Our game right now is pretty boring as there is nothing to do, only stare at the beautifully arranged squares that should now populate you screen. To fix this we need to add a way to listen for keyboard input and move the player based on which key is pressed. At the top of the Javascript file write the line: ```javascript let keysDown = {}; ``` This is an empty **object** which will hold the keys currently pressed. If you are wondering why we need to store current keys down it is because this way allows multiple keys to be pressed at once. To listen for key presses, and then store that key press in the```keysDown``` variable we will use an ```eventListener```: ```javascript addEventListener("keydown", function(event){ keysDown[event.keyCode] = true; }); ``` This function executes whenever the user presses a key on their keyboard, the key pressed information is stored in the event parameter, it then sets the key to true in ```keysDown```. Now we need a similar function that executes when a key is released: ```javascript addEventListener("keyup", function(event){ delete keysDown[event.keyCode]; }); ``` It removes the entry of the released key from ```keysDown```. --- To detect and act upon keys that are pressed we need to create an input function that checks whether certain keys are pressed. ```javascript function input(){ if(65 in keysDown){ player.x -= 3; } if(68 in keysDown){ player.x += 3; } } ``` In Javascript keys are represented numerically, in this example 65 is the number for the "A" key and 68 is the number for the "D" key, if you wish to find out the keycodes for other keys you can use [this website](https://keycode.info/). In main you need to call this function so that input is checked every time main is executed. If you run the code you should see that when you press "A" or "D" the player moves horizontally, but you may also notice that the red square's "previous states" are still visible, to fix this write the following line at the top of the draw function: ```javascript c.clearRect(0, 0, canvas.width, canvas.height); ``` --- ## Horizontal Collisions When moving the red square you will notice that it passes straight through walls, this is because we haven't defined any collisions yet! But before we do collisions we need to create a function called ```getTile``` that gets the tile at a certain X and Y value: ```javascript function getTile(x,y){ return(currentLevel[Math.floor(y / 32)][Math.floor(x / 32)]); } ``` To start collisions we need to define another player attribute called ```speed```, this will determine how fast the player can move horizontally: ```javascript const player = { x: 256, y: 256, width: 32, height: 32, speed: 3 } ``` Now move back to the input function and add two if statements around the updating of the ```player.x``` value, and update the previous code to add ```player.speed``` instead of 3: ```javascript function input(){ if(65 in keysDown){ if (getTile((player.x - player.speed) + 1, player.y + 16) !== "1") { player.x -= 3; } } if(68 in keysDown){ if (getTile(((player.x + player.width) + player.speed) - 1, player.y + 16) !== "1") { player.x += 3; } } } ``` This checks whether the tile, when the player will move by ```player.speed```, at the player's location is a wall or air, if it is air then the player is allowed to move in the direction, else do nothing. If you now run the code, the red square should stop whenever it hits a wall. --- ## Gravity This section will involve a little bit of physics, if you are unaware of how gravity and jumping works you can look at [this website](https://www.khanacademy.org/science/physics/work-and-energy/work-and-energy-tutorial/a/what-is-gravitational-potential-energy), but note that this knowledge isn't required to follow along the next section (it just clarifies things). Firstly we need to update the player object with three attributes required for calculating Gravitational Potential Energy, they are: + Mass (mass) + Kinetic Energy On The Y-Axis (yke) + Gravitational Potential Energy (gpe) ```javascript const player = { x: 256, y: 256, width: 32, height: 32, speed: 3, mass: 64, yke: 0, gpe: 0 } ``` Now we need to create a function to update the player's Y position, the player's Y Kinetic Energy and the player's GPE, but first we will create a function that takes the player as a parameter and calculates the GPE of it. GPE = mass * 9.8 * height. As we will be working in pixels instead of meters we will need to divide the Gravitational Field Strength (9.8) by a million so it scales correctly, and as (0,0) on ```canvas``` is the top left we need to take the player's Y value from the height of the canvas (512 in my case), and finally so the GPE doesn't increase so quickly per pixel we will divide the player's 'height' by 32. ```javascript function calcGPE(obj) { return obj.mass * (9.8 / 1000000) * ((canvas.height - obj.height) - (obj.y / 32)); } ``` Now that that is out of the way we can create a function called ```gravity``` that takes the player as a parameter and: 1. Takes yke away from y 2. Takes GPE away from yke 3. Recalculates GPE ```javascript function gravity(obj){ obj.y -= obj.yke; obj.yke -= obj.gpe; obj.gpe = calcGPE(obj); } ``` Now add a call to ```gravity``` in the ```main``` function and pass ```player``` to it. Now if you run the code you should see that the red square now falls off the screen in a realistic manner. --- ## Vertical Collisions When our red square falls, it goes straight through the walls/floors, to fix this we need to add some more code to the gravity function. Firstly we will check for downwards collisions (landing on the floor), to do this we need to utilise the check squares function to see if the tile at the player's feet is a wall, if yes then we need to set the player's Y Kinetic Energy to 0 and move the player up until it looks seamless with the floor. Also as a preventative measure against future bugs we will need to check that the player is actually falling (Y Kinetic Energy is less than 0). ```javascript // Place Below Previous Code Written if (getTile(obj.x + 32, (obj.y + 32)) !== "0" || getTile(obj.x, (obj.y + 32)) !== "0") { if (obj.yke <= 0){ obj.yke = 0; obj.y -= (obj.y % 32); } } ``` Now we need to do the same for upwards collisions, and also we should only check one vertical collision if the other is false. ```javascript if (getTile(obj.x, obj.y) !== "0" || getTile(obj.x + 32, obj.y) !== "0") { if (obj.yke >= 0){ obj.yke = -0.5; obj.y += 1; } } ``` This does almost the same thing except it sets the Y Kinetic Energy to a small negative number so that it doesn't get stuck on the wall above. Your ```gravity``` function should now look like this: ```javascript function gravity(obj) { obj.y -= obj.yke; obj.yke -= obj.gpe; obj.gpe = calcGPE(obj); if (getTile(obj.x, obj.y) !== "0" || getTile(obj.x + 32, obj.y) !== "0") { if (obj.yke >= 0){ obj.yke = -0.5; obj.y += 1; } } else { if (getTile(obj.x + 32, (obj.y + 32)) !== "0" || getTile(obj.x, (obj.y + 32)) !== "0") { if (obj.yke <= 0){ obj.yke = 0; obj.y -= (obj.y % 32); } } } } ``` On running the code you can see that the red square stops when it hits a wall! --- ## Jumping Congratulations if you made it this far (this tutorial is very long...), this will be the final section before the basic platformer is complete! The final thing that we need to add is jumping. If we just move the player's Y value by a certain amount the jumping will look very unnatural, so instead we will increase the player's Y Kinetic Energy which gives it a nice realistic looking jump. The keycode for the "W" key (the jump key) is 87, so in the ```input``` function add a check for if 87 is in ```keysDown``` and if so increase the player's Y Kinetic Energy by however much you desire (5-8 is generally good), but to disallow the player to jump when directly below a wall we need to add a check to see if they are (and disallow jumping). ```javascript if (87 in keysDown && player.yke === 0) { if (getTile(player.x,player.y - 1) !== "1" && getTile(player.x + 32,player.y - 1) !== "1"){ player.yke += 8; } } ``` This also checks whether the player's Y Kinetic Energy is 0 (is on floor) to prevent mid-air jumping. And now... if you run the code you should be able to jump! --- ## Finished Thank you for taking the time to read through this tutorial! If you enjoyed this tutorial please give me an **upvote**! by lucdadukey
6
posted to Challenge by LucHutton (33) 5 days ago
β–²
7
Rectangle Drawer
The tutorial is within the comments of the code! I encourage you to play around with it!
17
posted to Challenge by ChandlerMorell (35) 5 days ago
β–²
4
Game of Za simulator
This is a schoolkids' game where i come from. Enjoy the fun of a time past your consciousness when you could not worry about stuff. With crosskill, strictly 2 player, no hide, no tiger, classic old vanilla za.
3
posted to Share by RYAN_WONG_WERN_ (6) 1 day ago
β–²
14
the rules of Minecraft (the first two and a few others!)
Just a funny tutorial!
11
posted to Challenge by epicman702 (20) 7 days ago
β–²
15
Python Advanced Concepts Explanation (for beginners)
(just wrote this up in a few minutes, so there might be typos and stuff) (the reader is expected to have at least basic knowledge of python) (and programming in general) (if not, read [fullern's introduction][0]) (if you have a question about it (or feedback), comment here or join the repl.it discord and DM elias#7990) This document is an explanation of how Python handles and manipulates data. It is an attempt to clarify some common misconceptions about Python. Important vocabulary and facts will be **bolded**. First, forget what you know about Python objects (but not syntax). I will be explaining most of the useful features here. ## Expressions: Expressions in python are the main way of manipulating data. They calculate (**evaluate**) a value based on the current state of the program. There are a few types of expressions: - Literals: Literals always evaluate to the same thing. For example, the literal `5` always evaluates to the number `5`. - Operations: Operations combine values. For example, the `+` operations adds numbers (or concatenates strings). An expression with an operation looks like `<some expression> <operation (+, -, *, etc.)> <other expression>` (without the angle brackets). Operations follow an extended version of PEMDAS, described [here][1]. - Function calls: These are described in the Functions section. - Ternaries: Ternary expressions look like `<expression a> if <condition expression> else <expression b>`. First `<condition expression>` is evaluated, and if it is **truthy** (acts like True; see Truthiness section for more), `<expression a>` is evaluated. If it is not truthy (**falsy**), `<expression b>` is evaluated instead. - Comprehensions: See the Comprehension section ## Code structure: Python code is composed of lines and blocks. Lines in python can have a few different forms (more than the ones shown here, but the others are used less): ```python <expression> # <expression> is evaluated, and then the value is discarded variable = <expression> # <expression> is evaluated, and assigned to variable as described in Scoping. var1, var2 = <expression> # <expression> is evaluated, and (assuming it's a list, tuple, etc.; see Iterables) var1 is set to its zeroth element and # var2 is set to its first (var1, var2), var3 = <expression> # <expression> is evaluated, and (var1, var2) is set to its zeroth element and var3 is set to its first # other patterns similar to those above also work, like (var1, var2), (var3, var4) # i use <lvalue> to represent any of those patterns if <expression>: # <expression> is evaluated <more lines of code, indented by some amount> # if <expression> was truthy, <more lines of code, indented> is run and the code skips to <more lines, not indented> elif <expression2>: # <expression2> is evaluated (only if <expression> was falsy). elifs are optional, and don't have to be included <more indented code> # if <expression2> was truthy, <more indented code> is run and the code skips. ... # the pattern continues else: <last indented code> # if none of <expression>, <expression2>, ... was truthy, <last indented code> is run. <more lines, not indented> while <expression>: # evaluate <expression>. if it is true, <indented code> # run <indented code> and go back to the start for <lvalue> in <expression>: # for every element in <expression> (probably a list, tuple, or iterable), set <lvalue> to that element and <indented code> # run <indented code> def name(value): # described in Functions <indented code> class name(): # described in User-Defined Classes <indented code> ``` `if`, `while`, `for`, `def`, and `class` can also be used in indented code. ## Scoping: When a program starts running, all variables are in a **scope** (collection of variables) called the **global scope**. Other scopes can be created and manipulated as described in Functions and User-Defined Classes. ## Objects & Types: Data in Python is an object. Numbers are **objects**, string are objects, and functions are objects. Statements like `if`, `for`, and `while` are not objects, since they are code, not data. Every object in Python has a **type**, a.k.a. class. The type of a number is `int` or `float`. The type of a string is `str`. The type of an object can be determined with `type(obj)`. These types are also objects. Their type is called `type`. `type`'s type is itself. Types (but not non-type objects) also have superclasses. These superclasses are also types, and specify additional data about the type (more info in Attributes). If a type has multiple superclasses, [this algorithm][2] is used to determine priorities for them in certain situations. ## Attributes: Objects also have **attributes**. These attributes are named. Their names start with a character a-z, A-Z, or \_. The characters after the first can be a-z, A-Z, \_, or a digit. For example, an attribute could be called `an_attribute`, `AbC123`, or `__add__`, but not `123AbC` (the first character cannot be a digit). These attributes can be accessed with `the_object.attribute_name`. When an attribute is accessed, if it is not found, the object's class (a.k.a. type) is checked. If the attribute is not present there, the superclasses of the type are checked next, in order by priority. If none of the superclasses have the attribute, an exception is raised (see Exceptions). Attributes also have **values**, which are the values returned when an attribute is accessed. These values can be any object. There are also **descriptors**, which allow code to be run when an attribute is accessed. They are described in more detail in the Descriptors section. Some attribute names are special. For example, an attribute named `__add__` specifies how objects are added together with `+`. This will be described in more detail in the User-Defined Classes section. ## Functions: **Functions** are snippets of Python code, and are also objects. They can be **called** with `the_function_object(argument_1, argument_2, ...)`. When a function is called, the code that called it is paused, the passed arguments are placed in variables, and the function's code is run. When the function executes a `return` statement, the function's code stops, and the returned value is send back to the calling code. If the function reaches the last line, it returns `None`, an object representing no data. For example, ```python def a_function(number): # when a_function(value) is called, the calling code is paused # then a new scope is created, # and a variable called number is created with the argument in it # the function's code is then run in the new scope result = number + 1 # result is created in this function's scope return result # the function's code stops here, and result is sent to the calling code. function_result = a_function(41) # calling a_function, where argument is set to 41 # function_result is set to the value returned from a_function print(function_result) # print is a function too! it returns None ``` When run, this code takes the following path: 1: ```python def a_function(number): # all that code above ``` This line (and the code in the `def`) creates a function object, then puts it in a variable called `a_function`. 2: ```python function_result = a_function(41) ``` This line calls `a_function` with the argument `41`. We'll come back to this line once the function returns. 3: ```python def a_function(number): ``` The function is called, so a new scope is created. Here, the argument `41` corresponds to the variable `number`, so the variable `number` in the new scope is set to `41`. 4: ```python result = number + 1 ``` This line calculates `41` (the value of the `number` variable) `+ 1`, which equals `42`. The `result` variable is then set to `42`. 5: ```python return result ``` This line ends the function, returning the value of `result` (`42`). You don't need to return a variable, so this function could have just returned `number + 1` instead. This also goes back to the scope that existed before the function was called (the global scope). 6: ```python function_result = a_function(41) ``` Now that the function has returned, `function_result` is set to the value it returned, which is `42`. Note that this variable is created in the global scope, not in `a_function`'s scope. 7: ```python print(function_result) ``` This outputs the value of `function_result`, or `42`. ## Generators, Iterators, and Iterables **Generators** are one of my favorite features in Python. They are easiest to understand with an example, so here is one: ``` def a_generator_func(): print("about to yield first value") yield "first value" print("just yielded first value") print("about to yield second value") yield "second_value" print("done yielding, there is no third value") a_generator = a_generator_func() print("about to get first value") print("the first value is", repr(next(a_generator))) print("about to get second value") print("the first value is", repr(next(a_generator))) print("about to get third value") print("the first value is", repr(next(a_generator))) ``` This code will output ``` about to get first value about to yield first value the first value is 'first value' about to get second value just yielded first value about to yield second value the first value is 'second_value' about to get third value done yielding, there is no third value Traceback (most recent call last): File "python", line 17, in <module> StopIteration ``` `a_generator_func` is a function, that, instead of pausing the main program when called, returns an object representing the current state. `next` can be repeatedly called on that object to run it until it `yield`s a value. When a generator runs out of things to yield, a `StopIteration` exception (TODO: section on exceptions) is raised. These can be caught with: ``` try: next_val = next(a_generator) except StopIteration: print("the generator ended") ``` Generators can also be used with `for`: ``` for elem in a_generator_func(): print(elem) ``` This would output ``` about to yield first value elem: first value just yielded first value about to yield second value elem: second_value done yielding ``` , but would not raise `StopIteration` (`for` automatically handles this). Generators are a special class of **iterators**, which are objects that can have `next` called on them, and can be used with `for`. `list`s and `tuple`s are not iterators, but **iterables**, which can be converted to iterators by calling `iter` on them. ## User-Defined Classes There are many online tutorials about creating classes, most of which are better than I can write. So before you read this, go look at one of those tutorials (but keep in mind that everything in play is an object). So, now that you have read one of those tutorials (go read one if you haven't), consider the following example class: ```python class Point(): def __init__(self, x_pos, y_pos): self.x_pos = x_pos self.y_pos = y_pos def print(not_self): print(not_self.x_pos, not_self.y_pos) def __add__(tomayto, tomahto): return Point(tomayto.x_pos + tomahto.x_pos, tomayto.y_pos + tomahto.y_pos) a = Point(1, 2) b = Point(3, 4) a.print() b.print() (a + b).print() ``` This code creates a `Point` class, and 2 `instances` of it (`a` and `b`). It then calls `.print` on both instances and `a + b`. The only peculiarity you might notices about this is that it doesn't use `self`, but different argument names. Despite what most tutorials would have you believe, there is nothing special or magic about `self`. You can replace it with any other name and your code will work fine. If your tutorial didn't cover `__add__` and similar functions, they basically define what happens when `a + b` is executed. More information can be found [here][3]. The only "magic" thing left in this code is how the `self`/`not_self`/`tomayto` arguments actually get added; `a.print()` never specifies a value for `not_self`. This is covered in the next section, ## Descriptors Descriptors are a way to make code run when an attribute is accessed. They are objects with `__get__` or `__set__` special methods. When they are accessed as an attribute of a class (but not from an instance), the `__get__` method is called with the instance and the class the descriptor was found on. When attributes are set, a similar thing is done with `__set__`. This is how functions automatically add a `self` argument. They are descriptors, so when they are accessed, it returns a "bound" version of the function, that has the instance (`self`) already added as an argument. A shorthand way to create descriptors is: ```python class Test(): @property def x(): print("getting x") @x.setter def x(): print("setting x") a = Test() a.x a.x = 1 ``` The `@property` and `@x.setter` lines are decorators, described in the next section. ## Decorators Consider the following code: ```python def function_making_function(old_function): print("making a new function from", old_function) def new_function(): print("calling the old function") old_function() print("done calling the old function") print("made the new function") return new_function ``` This code is relatively simple, except for the fact that a function is defined inside another function. This gives the inner defined function access to all the variable in the outer function. Now, running ```python def some_function(): print("in some_function") print("starting to make a new function") new_function = function_making_function(some_function) # not calling it here, just moving at around (remember, functions are objects!) print("done making the new function") print("calling the new function") new_function() print("done") ``` will output: ``` starting to make a new function making a new function from <function old_function at 0xhesyfyua> made the new function done making the new function calling the new function calling the old function in some_function done calling the old function done ``` The code ```python9o print("starting to make a new function") @function_making_function def some_function(): print("in some_function") print("done making the new function") print("calling the new function") some_function() print("done") ``` does the exact same thing as the other code above. `@function_making_function` is just shorthand for `some_function = function_making_function(some_function)` (but it must be before the `def`). This is called a decorator. Multiple decorators can be used on the same function, and are applied bottom-to-top. Decorators do not have to return functions; they can also return other objects (such as descriptors in the case of `@property`). `@property_name.setter` works by having a `setter()` method on the descriptor objects `@property` returns. This `setter()` method changes the behavior of the property's `__set__` method (but not the value as an instance attribute, then the function binding descriptor wouldn't work). That is most of the features I regularly use in Python. There are a few simplifications and some things are left out, but for the most part this should be accurate. However, I left out a lot of information about the standard library (built-in functions and modules). Information about them can be found [here][4] and [here][5]. ## Internals This section details how a certain Python interpreter ([CPython][6]) actually runs Python code. Most things discussed here don't apply to other interpreters, although some concepts might be the same. ### Processing order When Python code is run, it is **lexed**, **parsed**, converted to **bytecode**, and then run. #### Lexing Lexing, or tokenizing, is the process of breaking code up into groups of symbols so it is easier to process later. A simple example of lexing (not with Python code) could look like: ``` 1 + 2*(3 +4- 5) -> NUM 1 OP + NUM 2 OP * OPEN_PAREN NUM 3 OP + NUM 4 OP - NUM 5 CLOSE_PAREN ``` Note that this takes care of unused whitespace and other things that might complicate the process later on. TODO: explain python lex #### Parsing Parsing converts tokenized code into a tree structure that is easier for code to process. For example, using the arithmetic expression from earlier: ``` NUM 1 OP + ... NUM 5 CLOSE_PAREN -> ADD( 1, MUL( 2, SUB( ADD(3,4), 5 ) ) ) ``` This takes care of things like parentheses that don't really affect how code actually runs. TODO: explain python parse #### Bytecode: What is it? Bytecode is an **intermediate language**, which means that code is translated to it before being run. For example, again with the arithmetic expression: ``` ADD(1, MUL(...)) -> PUSH 1 PUSH 3 PUSH 2 PUSH 4 ADD // 3 + 4 PUSH 5 SUB // 3 + 4 - 5 MUL // 2 * (3 + 4 - 5) ADD // 1 + 2 * (3 + 4 - 5) ``` That code is actually not the bytecode, just a simplified version. Bytecode would actually be represented as a sequence of bytes, like in the following example (with bytes as hexadecimal): ``` PUSH 1: 00 01 // the stack is currently 1 PUSH 3: 00 03 // the stack is currently 1 3 PUSH 2: 00 02 // the stack is currently 1 3 2 PUSH 4: 00 04 // the stack is currently 1 3 2 4 ADD: 01 // the stack is currently 1 3 6 PUSH 5: 00 05 // the stack is currently 1 3 6 5 SUB: 02 // the stack is currently 1 3 1 MUL: 03 // the stack is currently 1 3 ADD: 01 // the stack is currently 4 ``` Here, the **opcode** for `PUSH` is `00` (with 1 parameter), `ADD` is `01`, etc. The bytecode for Python is complicated and has many operations (detailed [here][7]), so I will not fully document it here. It is stack-based, which means most of its instructions operate on a data stack, similar to the arithmetic example above. This stack contains Python objects. There are also a set of slots, which are used to store variables, constants, names, etc. Here are some common instructions: ``` POP_TOP: remove the top element of the stack (TOS) BINARY_ADD: pop the TOS and the element below the TOS (TOS1), add them, and push it back onto the stack BINARY_SUBTRACT: see above (-) BINARY_MULTIPLY: see above (*) BINARY_FLOOR_DIVIDE: see above (//) BINARY_TRUE_DIVIDE: see above (/) STORE_FAST(slot_num): pop the TOS and store to a slot LOAD_FAST(slot_num): read a slot and push to the stack LOAD_CONST(slot_num): load a constant and push it CALL_FUNCTION(arg_count): pop the some elements and call the last one as a function with the other elements RETURN_VALUE: return from a function JUMP_ABSOLUTE(where): jump to the <where>th bytecode instruction POP_JUMP_IF_TRUE(where): pop the TOS, if true, jump to <where> POP_JUMP_IF_FALSE: ... GET_ITER: pop the TOS, convert to an iterator, and push it FOR_ITER(delta): use the iterator in TOS (w/o popping) and get the next element. If there is no next element, jump ahead by <delta> instructions UNPACK_SEQUENCE(unpack_len): pop an iterable as the TOS and push its elements (there should be <unpack_len>) to the stack ``` #### Bytecode: How is it made? In Python, bytecode for arithmetic expressions is implemented similarly to the example with the arithmetic expressions. For example, ``` a + b: <bytecode for a> <bytecode for b> BINARY_ADD a - b: <bytecode for a> <bytecode for b> BINARY_SUBTRACT a * b: <a> <b> BINARY_MULTIPLY a / b: ... a // b: ... a(b, c, d): <a> <b> <c> <d> CALL_FUNCTION(3) ... ``` Bytecode for an `<expression>` line looks like `<bytecode for <expression>> POP_TOP` Bytecode for a `<variable> = <expression>` line in the global scope looks like `<bytecode for <expression>> STORE_NAME(<variable>)` Bytecode for a `<variable> = <expression>` line in the local scope looks like `<bytecode for <expression>> STORE_FAST(<variable slot>)` Bytecode for a `<var1>, <var2>, <var3> = <expression>` line looks like `UNPACK_SEQUENCE(3) <assign to var1, global or local> <assign to var2> <assign to var3>` Bytecode for a `(<var1>, <var2>), <var3> = <expression>` line looks like `UNPACK_SEQUENCE(2) UNPACK_SEQUENCE(2) <assign to var1> <assign to var2> <assign to var3>` Bytecode for an `if <expr>: <code>` line looks like `<bytecode for <expr>> POP_JUMP_IF_TRUE(END) <bytecode for <code>> LABEL(END)` (this will sometimes be optimized) Bytecode for an if-elif-else statement looks similar, but more complicated Bytecode for a `while <expr>: <code>` line looks like `LABEL(START) <bytecode for if <expr>: <code>> JUMP_ABSOLUTE(START)` Bytecode for a `for <lvalue> in <expr>: <code>` line looks like `<bytecode for <expr>> GET_ITER LABEL(START) FOR_ITER(END)`<br> `<assign to <lvalue>> <bytecode for <code>> JUMP_ABSOLUTE(START) LABEL(end)` TODO: `def`, `class` Python applies some rudimentary optimizations, like converting `JUMP_ABSOLUTE`s to more efficient `JUMP` instructions. [0]: https://repl.it/talk/challenge/Introduction-To-Python/7484 [1]: https://docs.python.org/3/reference/expressions.html#operator-precedence [2]: https://www.python.org/download/releases/2.3/mro/ [3]: https://docs.python.org/3/reference/datamodel.html#special-method-names [4]: https://docs.python.org/3/library/functions.html [5]: https://docs.python.org/3/library/ [6]: https://github.com/python/cpython [7]: https://docs.python.org/3/library/dis.html#python-bytecode-instructions
8
posted to Challenge by pyelias (518) 8 days ago
β–²
5
Infinite Sine Wave in Python (really simple)
In my university they made engineers write a program in C (programming language) that prints out the **sine wave**. Many of my friends do engineering and they all told me about their "beloved" assignment. It was about 8 p.m. and I was really bored... so I decided to do it myself but in Python (because I'm a lazy @ss). If you are interested, I am going to walk you through the process of this creation. First of all, we have to `import` 3 useful functions from Python's standard library. ```python from math import sin, radians from time import sleep ``` + `sin()` function returns the numerical (float) value of any angle **in radians**. We don't want to deal with those nasty radians (or at least I don't), so we import... + ...`radians()` function that converts normal angles like 45Β°, 90Β°, 180Β° etc. into **radians**. As you may have guessed already, we are going to feed this value in radians to the `sin()` function. + `sleep()` function allows us to slow down the printing of our sine wave by **halting** the program for a given amount of seconds. Computer calculates those values too fast and so we need to make it pause for a few milliseconds in order to see what it's printing. Now that we have all those necessary functions, we can start coding for real. Python prints data into the Terminal line by line, so our graph will be vertical, top-to-bottom in direction. ![demo1](https://storage.googleapis.com/replit/images/1539534227150_13d2481795ad20410ed9e1cff5610113.pn) We also want our wave to be infinite so we are going to write a function `wave()` that prints out just one cycle of a sine wave -180 to 180 degrees and then we'll put it into the `while True` loop to make it repeat itself forever (or until you stop it by closing the Terminal window or pressing `Ctrl + C` known as *Keyboard Interrupt*). Therefore, this is the layout of our script: ```python from math import sin, radians from time import sleep def wave(): # PLEASE IMPLEMENT ME! while True: # let the FUN last FOREVER wave() ``` > And we are almost there! Only 5 additional lines of code to go. One cycle of our sine wave includes all the angles starting at -180Β° and finishing at 180Β°. All those angles will have to be processed one by one. When I say these words, they instantly remind me of a `for` loop and it is exactly what we need here. ```python # concentrating on the wave() function now: def wave(): for a in range(-180, 180): # 'a' stands for 'angle' # 1. process angle somehow # 2. print angle at the beginning of line # 3. print some spaces ending with * # 4. sleep() for some time to slow down the printing ``` That's all we've got to do now. The first line is objectively the hardest bit here. It took me quite a bit of time to figure it out. Basically, our idea is that Terminal's space is divided into many lines and each line has many rectangles **equal in size**, each rectangle can hold one symbol; in our case we are only interested in spaces `_` and asterisks `*`. Sine wave ranges from -1 to 1 on the `y` axis. We will set this graph's maximum value to be 100 rectangles wide *excluding the angle value at the beginning of every line* (it is going to be the rightmost asterisk in our graph). Its 0 value will be right in the middle of the line and its -1 value will be the leftmost rectangle. ![demo2](https://storage.googleapis.com/replit/images/1539534199016_bc89403a39140f578414c775d3149150.pn) What we are really calculating here is the number of spaces in every line before the asterisk. This number of spaces increases and decreases with the sine value of the angle. Long story short, let's write this line already. Line 1: We've got to find the `sin()` for the angle `a` that is given by the `for` loop. This value we will store in a variable called `s` for `sine`. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = sin( radians(a) ) ``` Line 1: If we open the Terminal, run Python interpreter, import `sin()` and `radians()` functions, we can see the format of output. ```powershell Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from math import sin, radians >>> sin(radians(45)) 0.7071067811865475 ``` Line 1: We need to convert this value into an integer between 0 and 100 that is going to represent the number of spaces for each specific line. To do this, we multiply this ridiculous `float` by a 100 and display the result to 2 decimal places. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = "{:.02f}".format( sin( radians(a) ) * 100 ) ``` Line 1: Now, `s` is a `str` that looks like a `float`, but we want the `float` so we wrap all this into `float()` function. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ``` Line 1: However, we actually need an integer, not a `float`, so we wrap it all again into the `round()` function. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) ``` Line 1: And the last thing for this line (I promise) is we need to divide this number by 2 because we have negative values as well, so both positive and negative side will be 50 spaces wide. Here we are, the first line is ready! ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 ``` > Now we simply need to use this value to print out the graph. Line 2: First things first, we want to know what angle each line represents, so... ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") # for those who aren't familiar with this syntax # this line is equivalent of # print( "{} degrees:".format(a), end="\t" ) ``` Line 3: Print `(s + 50)` spaces. The idea behind `s + 50` is that our `0` point must be in the middle and negative numbers must take up first 50 spaces, so we push every `s` by 50 spaces to the right. Note that negative numbers simply subtract from 50 and are therefore going to be placed left-of-center. ```python def wave(): for a in range(-180, 180): s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") print( (s + 50) * " ", end="*\n" ) ``` Line 4: Last one and the easiest one. Just halt the process for 0.01 seconds to slow it down a bit. ```python def wave(): for a in range(-180, 180): s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") print( (s + 50) * " ", end="*\n" ) sleep(0.01) ``` Voila! Our `wave()` function is ready and the script is now complete.
2
posted to Challenge by sharpvik (6) 2 days ago
β–²
16
Plat!
**UPDATE** this will not be updated or any bugs found be fixed, all fixes will be made at http://plat-online--fhillis.repl.co/ **ORIGINAL** A fun little platformer with hyper-sensitive controls with a focus on speed. Complete the level as quickly as you can, controls are WASD and the cyan (blue) rectangle is the finish. Link to game is https://plat--fhillis.repl.co/ Share your scores, mine is 6097! ![2018-10-07 (2)](https://storage.googleapis.com/replit/images/1538963436946_a64d788b95d406f90353f4ec03f8621b.pn) *note* Only runs when opened in its own tab.
9
posted to Share by Fhillis (27) 9 days ago
β–²
9
Colorful Circle Spiral Generator Using Python Turtle
Welcome to the python turtle circle pattern tutorial! In this tutorial you will learn how to make a colorful circle pattern creator with python using turtle! This patterns will look somewhat like this and the best part is that you can customize them! ![Screen Shot 2018-10-12 at 3.48.46 PM](https://storage.googleapis.com/replit/images/1539373814562_2b0b2e8bfd93e89ec57a4c6d39e0cc42.pn) First log on to your repl.it account and make a new python turtle code ![Screen Shot 2018-10-11 at 9.44.49 PM](https://storage.googleapis.com/replit/images/1539308815295_06a93f67ba00ca4869f5981583a9a8b3.pn) On your new repl.it first you are going to put in your imports. For this code you will need to import math, and obviously turtle. It should look like this now! ```python import turtle import math ``` We now want to set the background color! To do this you are going to type ```python turtle.Screen().bgcolor('black') #This sets the color to black but you can choose any background color! ``` Now you need to create 5 turtles for this code. I named mine Johny, Steve, Terry, Barry, ,Will, and Nich yours can be named anything you would like. Just make sure to use the same name every time. I also defined its speed and color! ```python Johny = turtle.Turtle() Johny.speed(0) Johny.color('white') #When the speed of the turtle is set to 0 then it will turn off the animation and it will go as fast as possible. I used the color white for my turtle but you can use any color you want it does not matter :). Do this 5 times for 5 different names and 5 different colors but keep the speed the same! ``` So far our code looks like this: ```python import turtle import math turtle.Screen().bgcolor('black') Johny = turtle.Turtle() Johny.speed(0) Johny.color('white') Steve = turtle.Turtle() Steve.speed(0) Steve.color('yellow') Barry = turtle.Turtle() Barry.speed(0) Barry.color('blue') Terry = turtle.Turtle() Terry.speed(0) Terry.color('orange') Will = turtle.Turtle() Will.speed(0) Will.color('pink') Nich = turtle.Turtle() Nich.speed(0) Nich.color('red') #When the speed of the turtle is set to 0 then it will turn off the animation and it will go as fast as possible ``` To make this colorful circle generator you would want a user input so that you can get a new pattern each time!. To do this use a input statement and then a statement to make sure your number is a integer. It will look like this ```python random = input("Enter a random number") random = int(random) ``` Now we will need to make a while true loop so that the pattern will keep drawing forever and this will look like this: ```python while True: ``` _Anything which is in this while true loop needs to be tabbed in!_ We are very close to finishing our code! Inside this while true loop you will need to put this code in ```python def drawCircles(t,size): for i in range(10): t.circle(size) size=size- minus+62 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Johny ,100,10) ``` There are comments in the code to tell you what this code means. In this code the turtle Johny is drawing which means it will be the color white. Now you will want to put this code in for each turtle and you will be done! I recommend that for every size = size - minus + 62 line that you change the +62 to something else like -12 or *32 to get a very interesting pattern each time. Here is the final code. ```python import turtle import math turtle.Screen().bgcolor('black') Johny = turtle.Turtle() Johny.speed(0) Johny.color('white') Steve = turtle.Turtle() Steve.speed(0) Steve.color('yellow') Barry = turtle.Turtle() Barry.speed(0) Barry.color('blue') Terry = turtle.Turtle() Terry.speed(0) Terry.color('orange') Will = turtle.Turtle() Will.speed(0) Will.color('pink') Nich = turtle.Turtle() Nich.speed(0) Nich.color('red') minus = input("Give me a random number") minus = int(minus) print "Click on results now" while True: def drawCircles(t,size): for i in range(10): t.circle(size) size=size- minus+62 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Johny,100,10) def drawCircles(t,size): for i in range(4): t.circle(size) size=size - minus -3 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Steve,100,10) def drawCircles(t,size): for i in range(4): t.circle(size) size=size- minus def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Barry,100,10) def drawCircles(t,size): for i in range(4): t.circle(size) size=size- minus + 2 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Terry,100,10) def drawCircles(t,size): for i in range(4): t.circle(size) size=size-minus*3 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Will,100,10) def drawCircles(t,size): for i in range(4): t.circle(size) size=size-minus-45 def drawSpecial(t,size,repeat): for i in range (repeat): drawCircles(t,size) t.right(360/repeat) drawSpecial(Nich,100,10) ``` To run the code you first must press run button and then you have to go to console and type your random number. Your random number can be a negative number and if you make the number too big the code does not work. After you do that then you should be good to go into result and view your pattern. If you discovered a cool looking pattern put it down below in the comments! Here is are some cool patterns the generator made! ![Screen Shot 2018-10-12 at 3.49.37 PM](https://storage.googleapis.com/replit/images/1539373802126_aa9e1ced7f74cb7c611b9d79fc39c527.pn) ![Screen Shot 2018-10-12 at 3.49.15 PM](https://storage.googleapis.com/replit/images/1539373805966_2798667f8c3d949293c2851387f98b53.pn) ![Screen Shot 2018-10-12 at 3.48.46 PM](https://storage.googleapis.com/replit/images/1539373814562_2b0b2e8bfd93e89ec57a4c6d39e0cc42.pn) _Thanks to nothplus for the idea of making a tutorial for python turtle! Be sure to check his tutorial right here>>>https://repl.it/talk/challenge/How-To-Create-A-Black-Hole-Spiral-in-Python-W-Turtle/7423_ # **Stay Tuned For More! And make sure to smash that upvote button**
5
posted to Challenge by IEATPYTHON (86) 5 days ago
β–²
7
Leaderboard For This Competition
This leaderboard shows you the current stats for this competition.
4
posted to Share by fullern000 (493) 4 days ago
β–²
7
Vacations
If you were able to go on a vacation ANYWHERE where would you go and why?
13
posted to Ask by IEATPYTHON (86) 6 days ago
β–²
2
Please give me the answer
Instructions from your teacher: Lab Description : Given a distance traveled (miles) and elapsed time (hours and minutes), calculate the speed in miles per hour. distance = rate * time minutes / 60 = hours ( 360 / 60 == 6 hours ) Sample Output : Enter the distance :: 45 Enter the hours :: 0 Enter the minutes :: 32 45 miles in 0 hour and 32 minutes = 84 MPH. Enter the distance :: 96 Enter the hours :: 1 Enter the minutes :: 43 96 miles in 1 hour and 43 minutes = 56 MPH. Enter the distance :: 100 Enter the hours :: 2 Enter the minutes :: 25 100 miles in 2 hour and 25 minutes = 41 MPH.
4
posted to Ask by ThomasWeaver (1) about 23 hours ago
β–²
9
Fullern Tutorials: Webscraping
View the website at https://webscraping-tutorial--fullern000.repl.co/. Thank you and please upvote!
16
posted to Challenge by fullern000 (493) 8 days ago
Load more