Learn to Code via Tutorials on Repl.it

Posts
Pinned
5
LLC GOLANG: Web apps & structs (Videos 5+6)
## Hi everyone! This week, we'll focus on: * [Creating a simple web app](https://www.youtube.com/watch?v=-QmdZ7821wA) * [Structs](https://www.youtube.com/watch?v=3fsvqo9pQyg) **Weekly Quiz:** Quiz yourself on last week's concepts [here](https://forms.gle/CAn1mx8j4R5j74y39 ). This week's quiz is self-grading, so there's... 🥁🥁🥁 no due date! If you completed last week's quiz, you should have received your scores tonight, Tuesday, May 14th. **Next week's quiz** By Sunday, 5/19, please make sure you post your new quiz questions below. Please only include items covered in videos 1-6. 'Til next week, friends!
4
posted by katyadee (613) 1 month ago
HTML, CSS, JS
HTML, CSS, JS
115
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 window 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.platforms.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 an 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. ## __EDIT__ I made an additional demo that delves into some more complicated concepts but it looks a lot better (I stole some sprites off the internet). It is just some uncommented code that you can play around with and try and see if you can make anything out of it. If you want to check it out you can find it [here](https://repl.it/@kaldisberzins/Phaser-Demo). Just wanna play it? Go [here](https://phaser-demo--kaldisberzins.repl.co/). Also, thank you guys for all the support in the comments! So heartwarming to see that many people like it. [email protected]_
22
posted by kaldisberzins (254) 8 months ago
Express
Express
85
Build a WhatsApp bot 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 while 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, your own chatbots on WhatsApp - these bots are immediately available to 2 billion users, and there are so many things possible 🎓 I can't wait to see what you make! Now, let's get started 🏃‍♂️ ## 🔑 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) to 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)
14
posted by jajoosam (525) 8 months ago
Python
Python
75
Building AI: Neural Networks for beginners 👾
Teaching Machine to recognize Hand-written Numbers! I am excited to share some of my experience studying machine learning with you, guys! I'm not an expert but I'll try to explain it the way I see it myself. I'm going to try to give you some intuition about how Neural Networks work, omitting most of the math to make it more understandable but, for the most curious of you, I'll leave the links to complete explanations/courses in the end. ![Predicted class_ 4](https://storage.googleapis.com/replit/images/1541033154259_e80e9609e421c89077d1b92aa1d33f36.pn) In 29 mins, you'll be able to configure an algorithm that's going to recognize the written digits in python :) ## **🧠 What is a Neural Network?** Imagine Neural Network as an old wise wizard who knows everything and can predict your future by just looking at you. ![magicbox](https://storage.googleapis.com/replit/images/1541033176006_a6af80c5d6034944a58c1fc595834691.pn) It turns out that he manages to do so in a very non-magical way: 1. Before you visited him, he trained, carefully studied everything about many thousands of people who came to see him before you. 2. He now collects some data about what you look like (your apparent age, the website you found him at, etc). 3. He then compares it to the historical data he has about people that came to see him before. 4. Finally, he gives his best guess on what kind of person you are based on the similarities. ![nn](https://storage.googleapis.com/replit/images/1541033195545_03966c8b28c6a5a6e037593ca2d5fd2f.gi) In very general terms, it is the way many machine learning algorithms work. They are often used to predict things based on the history of similar situations: Amazon suggesting the product you might like to buy, or Gmail suggesting to finish the sentence for you, or a self-driving car learning to drive. ## **📙 Part 1: Import libraries** Let's start! I have put together a class that is doing all the math behind our algorithm and I'd gladly explain how it works in another tutorial or you could go through my comments and try to figure it out yourself if you know some machine learning. **For now, create a file called `NN.py` and paste this code:** ```python import numpy as np from scipy.optimize import minimize class Neural_Network(object): def configureNN(self, inputSize, hiddenSize, outputSize, W1 = np.array([0]), W2 = np.array([0]), maxiter = 20, lambd = 0.1): #parameters self.inputSize = inputSize self.outputSize = outputSize self.hiddenSize = hiddenSize #initialize weights / random by default if(not W1.any()): self.W1 = np.random.randn( self.hiddenSize, self.inputSize + 1) # weight matrix from input to hidden layer else: self.W1 = W1 if (not W2.any()): self.W2 = np.random.randn( self.outputSize, self.hiddenSize + 1) # weight matrix from hidden to output layerself.W2 = W2 else: self.W2 = W2 # maximum number of iterations for optimization algorithm self.maxiter = maxiter # regularization penalty self.lambd = lambd def addBias(self, X): #adds a column of ones to the beginning of an array if (X.ndim == 1): return np.insert(X, 0, 1) return np.concatenate((np.ones((len(X), 1)), X), axis=1) def delBias(self, X): #deletes a column from the beginning of an array if (X.ndim == 1): return np.delete(X, 0) return np.delete(X, 0, 1) def unroll(self, X1, X2): #unrolls two matrices into one vector return np.concatenate((X1.reshape(X1.size), X2.reshape(X2.size))) def sigmoid(self, s): # activation function return 1 / (1 + np.exp(-s)) def sigmoidPrime(self, s): #derivative of sigmoid return s * (1 - s) def forward(self, X): #forward propagation through our network X = self.addBias(X) self.z = np.dot( X, self.W1.T) # dot product of X (input) and first set of 3x2 weights self.z2 = self.sigmoid(self.z) # activation function self.z2 = self.addBias(self.z2) self.z3 = np.dot( self.z2, self.W2.T) # dot product of hidden layer (z2) and second set of 3x1 weights o = self.sigmoid(self.z3) # final activation function return o def backward(self, X, y, o): # backward propgate through the network self.o_delta = o - y # error in output self.z2_error = self.o_delta.dot( self.W2 ) # z2 error: how much our hidden layer weights contributed to output error self.z2_delta = np.multiply(self.z2_error, self.sigmoidPrime( self.z2)) # applying derivative of sigmoid to z2 error self.z2_delta = self.delBias(self.z2_delta) self.W1_delta += np.dot( np.array([self.z2_delta]).T, np.array([self.addBias(X)])) # adjusting first set (input --> hidden) weights self.W2_delta += np.dot( np.array([self.o_delta]).T, np.array([self.z2])) # adjusting second set (hidden --> output) weights def cost(self, nn_params, X, y): #computing how well the function does. Less = better self.W1_delta = 0 self.W2_delta = 0 m = len(X) o = self.forward(X) J = -1/m * sum(sum(y * np.log(o) + (1 - y) * np.log(1 - o))); #cost function reg = (sum(sum(np.power(self.delBias(self.W1), 2))) + sum( sum(np.power(self.delBias(self.W2), 2)))) * (self.lambd/(2*m)); #regularization: more precise J = J + reg; for i in range(m): o = self.forward(X[i]) self.backward(X[i], y[i], o) self.W1_delta = (1/m) * self.W1_delta + (self.lambd/m) * np.concatenate( (np.zeros((len(self.W1),1)), self.delBias(self.W1)), axis=1) self.W2_delta = (1/m) * self.W2_delta + (self.lambd/m) * np.concatenate( (np.zeros((len(self.W2),1)), self.delBias(self.W2)), axis=1) grad = self.unroll(self.W1_delta, self.W2_delta) return J, grad def train(self, X, y): # using optimization algorithm to find best fit W1, W2 nn_params = self.unroll(self.W1, self.W2) results = minimize(self.cost, x0=nn_params, args=(X, y), options={'disp': True, 'maxiter':self.maxiter}, method="L-BFGS-B", jac=True) self.W1 = np.reshape(results["x"][:self.hiddenSize * (self.inputSize + 1)], (self.hiddenSize, self.inputSize + 1)) self.W2 = np.reshape(results["x"][self.hiddenSize * (self.inputSize + 1):], (self.outputSize, self.hiddenSize + 1)) def saveWeights(self): #sio.savemat('myWeights.mat', mdict={'W1': self.W1, 'W2' : self.W2}) np.savetxt('data/TrainedW1.in', self.W1, delimiter=',') np.savetxt('data/TrainedW2.in', self.W2, delimiter=',') def predict(self, X): o = self.forward(X) i = np.argmax(o) o = o * 0 o[i] = 1 return o def predictClass(self, X): #printing out the number of the class, starting from 1 print("Predicted class out of", self.outputSize,"classes based on trained weights: ") print("Input: \n" + str(X)) print("Class number: " + str(np.argmax( np.round(self.forward(X)) ) + 1)) def accuracy(self, X, y): #printing out the accuracy p = 0 m = len(X) for i in range(m): if (np.all(self.predict(X[i]) == y[i])): p += 1 print('Training Set Accuracy: {:.2f}%'.format(p * 100 / m)) ``` ## **📊 Part 2: Understanding Data** Cool! Now, much like the wizard who had to study all the other people who visited him before you, we need some data to study too. Before using any optimization algorithms, all the data scientists first try to *understand* the data they want to analyze. **Download files `X.in` (stores info about what people looked like - question) and `y.in`(stores info about what kind of people they were - answer) from [here](https://www.dropbox.com/sh/b04b2xb5j3ncir3/AABlau8wnzWmuyekJ8iVlmPga?dl=0) and put them into folder `data` in your repl.** * X: We are given 5,000 examples of 20x20 pixel pictures of handwritten digits from 0 to 9 (classes 1-10). Each picture's numerical representation is a single vector, which together with all the other examples forms an array `X`. * Y: We also have an array `y`. Each column represents a corresponding example (one picture) from `X`. `y` has 10 rows for classes 1-10 and the value of only the correct class' row is one, the rest is zeros. It looks similar to this: ``` [0, 0, 0, 0, 0, 0, 0, 0, 0, 1] # represents digit 0 (class 10) [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] # represents digit 1 (class 1) ...... [1, 0, 0, 0, 0, 0, 0, 0, 1, 0] # represents digit 9 (class 9) ``` Now, let's plot it! ![TrainingData](https://storage.googleapis.com/replit/images/1541033299328_0478599ab1b7884435cc3bf629b1edc1.pn) In the end, I'd want a function `displayData(displaySize, data, selected, title)`, where * `displaySize` - the numer of images shown in any one column or row of the figure, * `data` - our X array, * `selected` - an index (if displaying only one image) or vector of indices (if displaying multiple images) from X, * `title` - the title of the figure **Create a `plots` folder to save your plots to. Also, if you use repl, create some empty file in the folder so that it doesn't disappear.** **Create a `display.py` file and write the following code in there. Make sure to read the comments:** ```python import matplotlib.pyplot as plt # Displaying the data def displayData( displaySize, data, selected, title ): # setting up our plot fig=plt.figure(figsize=(8, 8)) fig.suptitle(title, fontsize=32) # configuring the number of images to display columns = displaySize rows = displaySize for i in range(columns*rows): # if we want to display multiple images, # then 'selected' is a vector. Check if it is here: if hasattr(selected, "__len__"): img = data[selected[i]] else: img = data[selected] img = img.reshape(20,20).transpose() fig.add_subplot(rows, columns, i+1) plt.imshow(img) # We could also use plt.show(), but repl # can't display it. So let's insted save it # into a file plt.savefig('plots/' + title) return None ``` Great, we are halfway there! ## **💪 Part 3: Training Neural Network** Now, after we understand what our data looks like, it's time to train on it. Let's make that wizard study! It turns out that the results of the training process of the Neural Networks have to be stored in some values. These values are called *parameters* or *weights* of the Neural Network. If you were to start this project from scratch, your initial weights would be just some random numbers, however, it would take your computer forever to train to do such a complex task as recognizing digits. For this reason, I will provide you with the initial weights that are somewhat closer to the end result. **Download files `W1.in` and `W2.in` from [here](https://www.dropbox.com/sh/b04b2xb5j3ncir3/AABlau8wnzWmuyekJ8iVlmPga?dl=0) and put them into `data` folder.** We are now ready to write code to use our Neural Network library! ![training](https://storage.googleapis.com/replit/images/1541033327074_30bf734c3f1fa129d15be3285be6e453.gi) **Create a `train.py` file and write the following code in there. Make sure to read the comments:** ```python # This code trains the Neural Network. In the end, you end up # with best-fit parameters (weights W1 and W2) for the problem in folder 'data' # and can use them to predict in predict.py import numpy as np import display from NN import Neural_Network NN = Neural_Network() # Loading data X = np.loadtxt("data/X.in", comments="#", delimiter=",", unpack=False) y = np.loadtxt("data/y.in", comments="#", delimiter=",", unpack=False) W1 = np.loadtxt("data/W1.in", comments="#", delimiter=",", unpack=False) W2 = np.loadtxt("data/W2.in", comments="#", delimiter=",", unpack=False) # Display inputs sel = np.random.permutation(len(X)); sel = sel[0:100]; display.displayData(5, X, sel, 'TrainingData'); # Configuring settings of Neural Network: # # inputSize, hiddenSize, outputSize = number of elements # in input, hidden, and output layers # (optional) W1, W2 = random by default # (optional) maxiter = number of iterations you allow the # optimization algorithm. # By default, set to 20 # (optional) lambd = regularization penalty. By # default, set to 0.1 # NN.configureNN(400, 25, 10, W1 = W1, W2 = W2) # Training Neural Network on our data # This step takes 12 mins in Repl.it or 20 sec on your # computer NN.train(X, y) # Saving Weights in the file NN.saveWeights() # Checking the accuracy of Neural Network sel = np.random.permutation(5000)[1:1000] NN.accuracy(X[sel], y[sel]) ``` **Now, you have to run this code either from:** * **Repl.it** - but you would need to move code from `train.py` into `main.py`. Don't delete `train.py` just yet. It would also take approximately 12 minutes to compute. You can watch [this](https://www.youtube.com/watch?v=z-EtmaFJieY) Crash Course video while waiting :) * **Your own computer** - just run `train.py`, which takes 20 sec on my laptop to compute. If you need help installing python, watch [this](https://www.youtube.com/watch?v=LrMOrMb8-3s) tutorial. ![trained](https://storage.googleapis.com/replit/images/1541033350157_38c60efaabc74234ee72285f0e17048b.pn) ## **🔮 Part 4: Predicting!** By now, you are supposed to have your new weights (`TrainedW1.in`,`TrainedW2.in`) saved in `data` folder and the accuracy of your Neural Network should be over 90%. Let's now write a code to use the trained weights in order to predict the digits of any new image! ![giphy](https://storage.googleapis.com/replit/images/1541033387111_bcb40155cc2e8ef38749e91c207033d8.gi) **Create a `predict.py` file and write the following code in there. Make sure to read the comments:** ```python import numpy as np import display from NN import Neural_Network NN = Neural_Network() # Loading data X = np.loadtxt("data/X.in", comments="#", delimiter=",", unpack=False) y = np.loadtxt("data/y.in", comments="#", delimiter=",", unpack=False) trW1 = np.loadtxt("data/TrainedW1.in", comments="#", delimiter=",", unpack=False) trW2 = np.loadtxt("data/TrainedW2.in", comments="#", delimiter=",", unpack=False) # Configuring settings of Neural Network: NN.configureNN(400, 25, 10, W1 = trW1, W2 = trW2) # Predicting a class number of given input testNo = 3402; # any number between 0 and 4999 to test NN.predictClass(X[testNo]) # Display output display.displayData(1, X, testNo, 'Predicted class: ' + str(np.argmax(np.round(NN.forward(X[testNo]))) + 1) ) ``` **Change the value of `testNo` to any number between 0 and 4999. In order to get a digit (class) prediction on the corresponding example from array X, run the code from:** * **Repl.it** - but you would need to move code from `predict.py` into `main.py`. Don't delete `predict.py` just yet. * **Your own computer** - just run `predict.py`. Yay, you are officially a data scientist! You have successfully: 1. Analyzed the data 2. Implemented the training of your Neural Network 3. Developed a code to predict new testing examples ![congrats](https://storage.googleapis.com/replit/images/1541033425490_308fdfc015d494a8aeceae5564956f4b.gi) ## **🚀 Acknowledgments** Hat tip to @shamdasani whose code I used as a template for Neural Network architecture and Andrew Ng from Stanford whose data I used. Plenty of things I told you are not completely correct because I rather tried to get you excited about the topic I am passionate about, not dump some math on you! If you guys seem to enjoy it, please follow through with studying machine learning because it is just an amazing experience. I encourage you to take [this free online course](https://www.coursera.org/learn/machine-learning) on it to learn the true way it works. Also, it's my first post here and I'd appreciate any feedback on it to get better. Keep me updated on your progress, ask any questions, and stay excited! ✨✨✨
16
posted by ArtemLaptiev1 (74) 8 months ago
LOLCODE
LOLCODE
74
A Crash Course in LOLCODE 🐱
# A Crash Course in LOLCODE ___ OHAI! This is a crash course in the beautiful programming language known as LOLCODE! LOLCODE is a great language, and while it is similar to many other programming languages, trying to learn it may confuse some people because of the syntax. For this tutorial, any time I say `[variable1]`, `[variable2]`, or `[variable]`, as long as I'm not talking about initializing a variable, you can put a value instead. ### Creating a new program To begin a program, you need to have the line `HAI 1.2`. This will declare that it's a LOLCODE program that's written in LOLCODE 1.2. The last line in the program must be `KTHXBYE`. ### Comments There are two different ways of doing commenting - `BTW` and `OBTW`. The differences are shown below: ```lolcode BTW This is a one-line comment. OBTW This is a multi-line comment TLDR ``` The indentation is not necessary, but it makes it easier to read. ### Variables Variables are dynamically typed in LOLCODE, so you don't have to give them a type when declared. To declare a variable, use `I HAS A [variable]`. However, if you do want to give it a type, you can use `I HAS A [variable] ITZ A [type]`. There are 4 usable types of variables: - TROOF (a boolean - `WIN` or `FAIL`, corresponding to true or false.) - NUMBR (an integer - whole numbers) - NUMBAR (a float - decimal places) - YARN (a string - text, defined by "") Variable names are case-sensitive, so INT is different from Int. You can use capital and lowercase letters, underscores, and numbers - as long as neither underscores nor numbers begin the variable name. To assign one variable to another, use `[variable 1] R [variable 2]`. ### Concatenation It's very simple to concatenate YARNS in LOLCODE - you use `SMOOSH [variables to concatenate, seperated by AN] MKAY`. It will cast any input given to it to a YARN before concatenating. See below for an example. ```lolcode I HAS A VAR1 ITZ "Hi" I HAS A VAR2 ITZ 1234 I HAS A VAR3 ITZ WIN I HAS A VAR4 ITZ SMOOSH VAR1 AN VAR2 AN VAR3 MKAY VISIBLE VAR4 BTW The output will be Hi1234WIN ``` ### Casting There are a couple different ways of casting a variable from 1 type to another. The first is `MAEK [variable] A [type]`. This will attempt to cast from whatever type the variable is to the desired type. However, this will not work if it's illogical - for instance, trying to cast letters into a NUMBR or NUMBAR. To cast a variable to a different type and save the output in a different variable, use `[variable 1] R MAEK [variable 2] A [type]`. ### Expressions There are 3 different types of expressions in LOLCODE - **Math**, **Boolean**, and **Comparison**. The basic form for all expressions is either `[expression] [variable]` or `[expression] [variable1] AN [variable2]`. #### Math In LOLCODE, you have all the typical expression types - addition, subtraction, multiplication, division, and modulus (remainder), as well as some less-common ones - min (returns the value of the smaller of 2 variables) and max (returns the value of the larger of 2 variables). If either variable is a YARN and has a decimal, it is cast to a NUMBAR for the calculation. If it doesn't have a decimal, it's cast to a NUMBR. If both variables used are NUMBRs, then integer math is performed. If one or both are NUMBARS, floating floating point math is invoked. See below for a list of math expressions: ```lolcode SUM OF [variable 1] AN [variable 2] BTW This is addition DIFF OF [variable 1] AN [variable 2] BTW This is subtraction PRODUKT OF [variable 1] AN [variable 2] BTW This is multiplication QUOSHUNT OF [variable 1] AN [variable 2] BTW This is division MOD OF [variable 1] AN [variable 2] BTW This is modulus (remainder) BIGGR OF [variable 1] AN [variable 2] BTW This returns the bigger variable's value SMALLR OF [variable 1] AN [variable 2] BTW This returns the smaller variable's value ``` #### Boolean The boolean expressions work pretty much as you would expect, comparing WINs and FAILs. You can use and, or, xor, and not. Any value passed to this is cast to a TROOF. See below for the complete list: ```lolcode BOTH OF [variable 1] AN [variable 2] BTW This is an and statement EITHER OF [variable 1] AN [variable 2] BTW This is an or statement WON OF [variable 1] AN [variable 2] BTW This is an XOR statement NOT [variable] BTW This is a not statement ALL OF [variable 1] AN ... MKAY BTW This is an infinite and statement, keep adding variable names and ANs to check more ANY OF [variable 1] AN ... MKAY BTW This is an infinite or statement, see above ``` ### Comparisons This is very similar to boolean expressions - it takes in 2 variables and checks if they're either the same or different. However, it doesn't have to be 2 TROOFS, but they do have to be the same type. "9" and 9 will NOT be recognized as the same. See below for examples ```lolcode BOTH SAEM [variable 1] AN [variable 2] BTW returns WIN if variable 1 == variable 2 DIFFRINT [variable 1] AN [variable 2] BTW returns WIN if variable 1 != variable 2 BOTH SAEM [variable 1] AN BIGGR OF [variable 1] AN [variable 2] BTW variable 1 >= variable 2 BOTH SAEM [variable 1] AN SMALLR OF [variable 1] AN [variable 2] BTW variable 1 <= variable 2 DIFFRINT [variable 1] AN BIGGR OF [variable 1] AN [variable 2] BTW variable 1 < variable 2 DIFFRINT [variable 1] AN SMALLR OF [variable 1] AN [variable 2] BTW variable 1 > variable 2 ``` ### Printing To output text, you have to use the `VISIBLE [output]` command. This can also be used with variables by using `VISIBLE [variable]`. See below for examples: ```lolcode VISIBLE "Invisible" VISIBLE INT ``` ### Input To get input from the user, you can use `GIMMEH [variable]`. For this, you MUST specify a variable because that is where the output is stored. GIMMEH stores input as a YARN, so if you want to get a NUMBR or NUMBAR you have to cast it as such. ### Conditionals Creating conditionals is fairly straightforward in LOLCODE. There are 2 basic formats - one utilizing TROOFs, and one utilizing other types of variables. To create a conditional using TROOFs, use the following: ```lolcode [expression], O RLY? YA RLY BTW This code will execute if the result of [expression] is WIN NO WAI BTW This code will execute if the result of [expression] is FAIL OIC ``` To create a conditional using other variable types is a little more involved. Basically, `OMG [value]` is the same as checking if the expression is equal to [value], and `OMGWTF` is an else. To end a statement, you must put GTFO. ```lolcode [expression], WTF? OMG 5 BTW This code will execute if the result of [expression] is 5 GTFO OMG 91 OMG 21 BTW This code will execute if the result of [expression] is 91 or 21 GTFO OMGWTF BTW This code will execute if the result of [expression] is not 5, 91, or 21 OIC ``` ### Loops Loops are a somewhat confusing beast at first, but actually aren't that hard. First, you need `IM IN YR [label for the loop - I would recommend just calling it LOOP]`. Then, if you want to increase the iterator variable have `UPPIN YR [variable]`, and if you want to decrease the iterator variable have `NERFIN YR [variable]`. Finally, if you want to go until a certain value, use `TIL [expression]`, and if you want to go while a certain expression is true, use `WILE [expression]`. To end the loop, use `IM OUTTA YR [label]`. See below for an example: ```lolcode I HAS A ITERATOR ITZ 0 IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN 9 VISIBLE ITERATOR IM OUTTA YR LOOP BTW This will output 0 through 8, and then stop before printing 9. ``` ### Conclusion Aaaand that's pretty much everything I could possibly find on the internet about LOLCODE... There is documentation for functions and BUKKITs (arrays), but I couldn't get them to work and so I decided against detailing them. If you still want MOAR LOLCODE documentation, go [here](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md), [here](https://esolangs.org/wiki/LOLCODE), or [here](https://learnxinyminutes.com/docs/LOLCODE/). If you want a fairly simple random python with turtle spiral generator, go check out my tutorial for that [here](https://repl.it/talk/challenge/Python-Turtle-Graphics-Random-Spirals/7651). If you want a super long tutorial about how to make your own game using only python with turtle graphics, go [here](https://repl.it/talk/challenge/How-to-make-a-fairly-basic-game-using-Python-with-Turtle-Graphics/8182). If you liked this tutorial, feel free to leave an upvote. Thanks! :)
14
posted by minermaniac447 (169) 8 months ago
66
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 hash symbol `#` followed by a space: ```md # A header ``` Output: # A header Headers can be a variety of sizes. A smaller header starts with more hash symbols. The number of hash symbols can be 1 to 6: ```md #### A header with 4 hash symbols ``` Output: #### A header with 4 hash symbols 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!
24
posted by JSer (1083) 8 months ago
Pygame
Pygame
64
🚀 A Starter Guide to Pygame 📀
# 🚀 A Starter Guide to Pygame 📀 Pygame is an open-source library for making graphical applications with Python. Learn more about it on the official [website](https://pygame.org). This tutorial is intended to help you setup a very basic Pygame interface. It's for Python beginners or people who want to quickly bootstrap a Pygame project. Find more about Repl.it's GFX public beta announcement [here](https://repl.it/talk/announcements/Replit-GFX-Public-Beta-Build-Games-and-GUI-Apps/11545). So let's get started! We're going to be building a simple screen saver. The final result will look like the following ![programProgress4](https://i.imgur.com/dEileMP.gif) ## Starting out When creating a new project, be sure to select "PyGame" when creating a project. ![image](https://storage.googleapis.com/replit/images/1552705106070_4aa0e807cd3fb5197a7251222d74d724.pn) Now we're ready to start writing some code! ## Painting the Screen Red 🎨 First, we're importing Pygame and initializing all the imported pygame modules with [`pygame.init()`](https://www.pygame.org/docs/ref/pygame.html#pygame.init). Second, we're declaring `width` and `height` variables that represent the size of the screen. Third, we're setting `backgroundColor` to a tuple of 3 elements that represent the RGB numbers. Fourth, `screen` is a display Surface, or an initialized window or screen for display with the [`set_mode()`](https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode) method. Lastly, in the infinite loop, we're filling the screen to the `backGroundColor` and updatiang the display Surface to the screen. In other words [`pygame.display.flip()`](https://www.pygame.org/docs/ref/display.html#pygame.display.flip) "refreshes" the screen with changes you made to the grahpics. ```python import pygame pygame.init() width, height = 800, 600 backgroundColor = 255, 0, 0 screen = pygame.display.set_mode((width, height)) while True: screen.fill(backgroundColor) pygame.display.flip() ``` So, we get a red background! ![programProgress1](https://storage.googleapis.com/replit/images/1552448696584_73e029d5335f2d2a06c92a180e7103be.pn) ## Adding the DVD Right before you while loop, import an image of your DVD. Feel free to use the same image I used, in the repl below. ```python dvdLogo = pygame.image.load("dvd-logo-white.png") ``` Then, create a rectangle from the Surface, or from the image you just loaded with [`get_rect()`](https://www.pygame.org/docs/ref/surface.html?highlight=get_rect#pygame.Surface.get_rect) ```python dvdLogoRect = dvdLogo.get_rect() ``` Now, inside of the `while` loop (after filling the background color), "map" the imported image to the `dvdLogoRect` rectangle using the [`blit()`](https://www.pygame.org/docs/ref/surface.html?highlight=blit#pygame.Surface.blit) method. That way, the image stays inside of the invisible `dvdLogoRect` rectangle. ```python screen.blit(dvdLogo, dvdLogoRect) ``` Now, we get a DVD! ![programProgress2](https://storage.googleapis.com/replit/images/1552449702561_27872d2c7a30d4d9dbb53d3c908851d9.pn) ## Moving the DVD Logo To move the DVD logo, simply use `move()` by a speed: ```python dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed) ``` Make sure you also declare and initialie dvdLogoSpeed at the top of the file. `dvdLogoSpeed[0]` represents the speed in the `x` direction. ```python dvdLogoSpeed = [1, 1] ``` Finally, I added a `time.sleep(10 / 1000)` so the logo moves slower. So my code ended up looking like ![programProgress3](https://i.imgur.com/dsh8TYo.gif) The DVD logo *will* move off the screen because there is no bouncing. To implement a check for bouncing, add the following: ```python if dvdLogoRect.left < 0 or dvdLogoRect.right > width: dvdLogoSpeed[0] = -dvdLogoSpeed[0] if dvdLogoRect.top < 0 or dvdLogoRect.bottom > height: dvdLogoSpeed[1] = -dvdLogoSpeed[1] ``` The `.left` and `.right` properties don't seem to be [documented](https://www.pygame.org/docs/ref/rect.html?highlight=rect%20left), but it's implied that `.left` measures the distance from the left part of the `dvdLogoRect` Rect (rectangle) to the left part of the `screen.` And so on and so fourth for `.right`, `.top`, and `.bottom`. Here is the final result ![programProgress4](https://i.imgur.com/dEileMP.gif) Now let me know when the logo hits the corner!
31
posted by eankeen (494) 3 months ago
59
Game Tutorial: Canyon Runner
Hey everyone, I made a canyon runner game (https://repl.it/@ericqweinstein/EverlastingEmbellishedDevelopments) and wrote up a tutorial for it here: https://medium.com/@eric.q.weinstein/canyon-runner-repl-it-tutorial-cdc6208d3358 Hope you like it!
27
posted by ericqweinstein (193) 10 months ago
48
3D graphics, a beginners mind.
# Preface In this tutorial I would like to show how 3d graphics is done today, why it's important, and how it will change the way you see 3d graphics applications. To better understand, we'll end up creating a 3d engine with Python. # Requirements I expect you to be familiar with Python, if you understand what `class` means you're probably qualified in this department. I also expect you to understand what the terms fov (field of view), vertex, mesh..etc. mean. # But 3d graphics is hard! No, it's not. This is an awesome area of programming you'll be able to show to your friends, there *will* be math(s) involved, so strap in, but it'll all be explained. If there are aspects you do not understand, simply copy my solution. # Fundamentals To start, let's go through the basic building blocks. Imagine we have a simple object, a cube. ![blender_2018-10-24_10-42-00](https://image.ibb.co/b5RdgV/blender-2018-10-24-10-42-00.png) There's more going on under the hood, this cube is made up of two things, *vertexes* and *triangles*. Vertexes are essentially points in 3d space. Look around your room, and imagine a speck of dust, a single point in 3d space. Triangles are, well just triangles, normal 2d flat triangles. However their three points are connected to specific vertexes. Let's look at the vertexes. ![blender_2018-10-24_10-43-32](https://image.ibb.co/dtgpoA/blender-2018-10-24-10-43-32.png) On the above image of a cube, you can see there are eight points, these are the points which make up the cube. In memory, these points each have a 3d coordinate: X, Y, Z axis. however when we go to *render* the cube, we map each 3d coordinate to 2d screen space. And the way we do that is surprisingly simple. Next, let's look at the triangles. ![blender_2018-10-24_10-43-33](https://image.ibb.co/fMqh8A/blender-2018-10-24-10-43-33.png) As you can see, a triangle is now connected to three of the points. Do this 12(*) times and you'll get a cube. *: A cube is made up of 6 faces, however to make a face with a triangle, you must use two triangles, so it ends up being 12 triangles. # Enough "fundamentals", more coding! Alright, now that we understand the basic structure for rendering 3d shapes. Let's get more technical. We'll be doing this in `Python (with Turtle)`. First, we import Turtle, I will assume you already know how to use Turtle and are familiar with it's functionality. In short, it's just a graphics library aimed at kids learning how to code with graphics, and making flowers and all sorts of things... Except we'll be going much further than flowers. ```python import turtle ``` Next we need to store our object data. We need to store all our vertexes and triangles. ```python VERTEXES = [(-1, -1, -1), ( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1), (-1, -1, 1), ( 1, -1, 1), ( 1, 1, 1), (-1, 1, 1)] TRIANGLES = [(0, 1, 2)] ``` For now, we only have one triangle connected to the first three points. # Our basic main loop We want to simulate a normal graphics library with turtle. Our program will follow this structure: ```python # Create turtle, pointer = turtle.Turtle() # Turn off move time, makes drawing instant, turtle.tracer(0, 0) pointer.up() while True: # Clear screen, pointer.clear() # Draw, # ... # Update, turtle.update() ``` # Rendering Alright, now we need to somehow map these 3d vertex coordinates to 2d screen coordinates. To do this, let's use the *Perspective Formula*. Before we dive into the details of what exactly this formula does, let's start with an observation. Place an object in front of you, for instance a cup. As you move away, the cup shrinks; now this is all very obvious, but it is an essential property of 3d space we must consider. When we're creating a 3d engine, what we're doing is simulating this observation. When we move away from our objects, that is - the Z axis, we're essentially *converging* the X and Y axis toward zero. Look at this front-view of a cube, you can see the back vertexes are closer to the center (zero). ![blender_2018-10-24_19-01-34](https://image.ibb.co/kzOfvq/blender-2018-10-24-19-01-34.png) # So what is this "formula"? ```python f = field_of_view / z screen_x = x * f screen_y = y * f ``` Where x, y, z are vertex coordinates. We can simplify this to: ```python f = fov / z sx, sy = x * f, y * f ``` Easy right? So let's add `FOV` at the top of the file: ```python FOV = 100 ``` # Drawing the points Let's iterate through each vertex: ```python # Draw, for vertex in VERTEXES: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = vertex # Perspective formula, f = FOV / z sx, sy = x * f, y * f # Move to and draw point, pointer.goto(sx, sy) pointer.dot(3) ``` What we get is: ![chrome_2018-10-24_19-45-21](https://image.ibb.co/kONUoA/chrome-2018-10-24-19-45-21.png) But where are our four other points from before? The ones behind? The issue is we're inside the cube, we need to move the camera out. # The camera Alright, I won't go into the camera in this tutorial, you can look at my repl at the bottom to see how to properly implement a 3d engine, but we're taking baby steps here. When we think of moving the camera, we think of the camera object moving, simple right? Well that's not easy to implement in a rasterized renderer. However what's easier is to move the *world* around it. Think about it, either you can move the camera, or move the world; it's the same effect. As it turns out, it's a lot easier to offset the vertex positions than somehow change the perspective formula to equate the position; it would be a whole lot more complex. So quickly solve this, let's move the camera out: ```python # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f ``` ![chrome_2018-10-24_19-52-05](https://image.ibb.co/ceSJgV/chrome-2018-10-24-19-52-05.png) And adjust the `FOV` to say, `400`. ![chrome_2018-10-24_19-53-04](https://image.ibb.co/i62jMV/chrome-2018-10-24-19-53-04.png) Nice! # Drawing triangles To draw triangles, consider this code. By this point you should be able to understand it: ```python # Draw, for triangle in TRIANGLES: points = [] for vertex in triangle: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = VERTEXES[vertex] print(x, y, z) # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f # Add point, points.append((sx, sy)) # Draw trangle, pointer.goto(points[0][0], points[0][1]) pointer.down() pointer.goto(points[1][0], points[1][1]) pointer.goto(points[2][0], points[2][1]) pointer.goto(points[0][0], points[0][1]) pointer.up() ``` # Rotation To rotate our object, we'll be using the *Rotation Matrix*. It sounds scary, right? If you're familiar with linear algebra, you should already know this, but the rotation matrix is commonly defined as: ``` [x'] = [cos(0), -sin(0)] [y'] = [sin(0), cos(0)] ``` *using `0` as theta* I won't go into detail of the matrix. If you're unfamiliar, feel free to either research or copy & paste. To implement this, we'll first need the `math` library: ```python from math import sin, cos ``` Let's make a function to rotate: ```python def rotate(x, y, r): s, c = sin(r), cos(r) return x * c - y * s, x * s + y * c ``` Then let's place this before we do our perspective formula calculations: ```python # Rotate, x, z = rotate(x, z, 1) ``` As you can see the triangle is now rotated: ![chrome_2018-10-24_20-21-51](https://image.ibb.co/n60tFq/chrome-2018-10-24-20-21-51.png) Let's make the rest of the triangles: ```python TRIANGLES = [ (0, 1, 2), (2, 3, 0), (0, 4, 5), (5, 1, 0), (0, 4, 3), (4, 7, 3), (5, 4, 7), (7, 6, 5), (7, 6, 3), (6, 2, 3), (5, 1, 2), (2, 6, 5) ] ``` ![chrome_2018-10-24_20-23-06](https://image.ibb.co/k3Knaq/chrome-2018-10-24-20-23-06.png) Awesome! Let's initialize a counter at the start of the file: ```python counter = 0 ``` and increment this at the end of every loop: ```python # Update, turtle.update() counter += 0.025 ``` And replace our rotation function: ```python x, z = rotate(x, z, counter) ``` It's rotating, awesome! To rotate on the X, Y and Z axis: ```python x, z = rotate(x, z, counter) y, z = rotate(y, z, counter) x, y = rotate(x, y, counter) ``` We're done! # Complete code Before you read, I recommend you do read through the above, I know it's easier to just skip down to the bottom for the solutions. However, if you're here after reading through the above, feel free to post `Full read` in the comments as a token of my respect, and feel free to copy this code =) ```python from math import sin, cos import turtle VERTEXES = [(-1, -1, -1), ( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1), (-1, -1, 1), ( 1, -1, 1), ( 1, 1, 1), (-1, 1, 1)] TRIANGLES = [ (0, 1, 2), (2, 3, 0), (0, 4, 5), (5, 1, 0), (0, 4, 3), (4, 7, 3), (5, 4, 7), (7, 6, 5), (7, 6, 3), (6, 2, 3), (5, 1, 2), (2, 6, 5) ] FOV = 400 # Create turtle, pointer = turtle.Turtle() # Turn off move time, makes drawing instant, turtle.tracer(0, 0) pointer.up() def rotate(x, y, r): s, c = sin(r), cos(r) return x * c - y * s, x * s + y * c counter = 0 while True: # Clear screen, pointer.clear() # Draw, for triangle in TRIANGLES: points = [] for vertex in triangle: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = VERTEXES[vertex] # Rotate, x, z = rotate(x, z, counter) y, z = rotate(y, z, counter) x, y = rotate(x, y, counter) # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f # Add point, points.append((sx, sy)) # Draw trangle, pointer.goto(points[0][0], points[0][1]) pointer.down() pointer.goto(points[1][0], points[1][1]) pointer.goto(points[2][0], points[2][1]) pointer.goto(points[0][0], points[0][1]) pointer.up() # Update, turtle.update() counter += 0.025 ``` # Conclusion If you want to see an expanded and better written version: https://repl.it/@CoolqB/3D-Engine If there's demand I will perhaps dive into shading, lighting, culling, clipping and even texturing. If you've got any questions, fire away in the comments. Good luck!
6
posted by CoolqB (101) 8 months ago
44
From Scratch: AI Balancing Act in 50 Lines of Python
![Cart Pole Balancing](https://media.giphy.com/media/QKFkgF2ZtTVbsZBeb2/giphy.gif) Hi everyone! Today I want to show how in 50 lines of Python, we can teach a machine to balance a pole! We’ll be using the standard OpenAI Gym as our testing environment, and be creating our agent with nothing but numpy. I'll also be going through a crash course on reinforcement learning, so don't worry if you don't have prior experience! The cart pole problem is where we have to push the cart left and right to balance a pole on top of it. It’s similar to balancing a pencil vertically on our finger tip, except in 1 dimension (quite challenging!) You can check out the final repl here: https://repl.it/@MikeShi42/CartPole. ## RL Crash Course If this is your first time in machine learning or reinforcement learning, I’ll cover some basics here so you’ll have grounding on the terms we’ll be using here :). If this isn’t your first time, you can go on and hop down to developing our policy! **Reinforcement Learning** Reinforcement learning (RL) is the field of study delving in teaching agents (our algorithm/machine) to perform certain tasks/actions without explicitly telling it how to do so. Think of it as a baby, moving it's legs in a random fashion; by luck if the baby stands upright, we hand it a candy/reward. Similarly the agent's goal will be to maximise the total reward over its lifetime, and we will decide the rewards which align with the tasks we want to accomplish. For the standing up example, a reward of 1 when standing upright and 0 otherwise. An example of an RL agent would be AlphaGo, where the agent has learned how to play the game of Go to maximize its reward (winning games). In this tutorial, we’ll be creating an agent that can solve the problem of balancing a pole on a cart, by pushing the cart left or right. **State** A state is what the game looks like at the moment. We typically deal with numerical representation of games. In the game of pong, it might be the vertical position of each paddle and the x, y coordinate of the ball. In the case of cart pole, our state is composed of 4 numbers: the position of the cart, the speed of the cart, the position of the pole (as an angle) and the angular velocity of the pole. These 4 numbers are given to us as an array (or vector). This is important; understanding the state is an array of numbers means we can do some mathematical operations on it to decide what action we want to take according to the state. **Policy** A policy is a function that can take the state of the game (ex. position of board pieces, or where the cart and pole are) and output the action the agent should take in the position (ex. move the knight, or push the cart to the left). After the agent takes the action we chose, the game will update with the next state, which we’ll feed into the policy again to make a decision. This continues on until the game ends in some way. The policy is very important and is what we’re looking for, as it is the decision making ability behind an agent. **Dot Products** A dot product between two arrays (vectors) is simply multiplying each element of the first array by the corresponding element of the second array, and summing all of it together. Say we wanted to find the dot product of array A and B, it’ll simply be A[0]*B[0] + A[1]*B[1]... We’ll be using this operation to multiply the state (which is an array) by another array (which will be our policy). We’ll see this in action in the next section. ## Developing our Policy To solve our game of cart pole, we’ll want to let our machine learn a strategy or a policy to win the game (or maximize our rewards). For the agent we’ll develop today, we’ll be representing our policy as an array of 4 numbers that represent how “important” each component of the state is (the cart position, pole position, etc.) and then we’ll dot product the policy array with the state to output a single number. Depending on if the number is positive or negative, we’ll push the cart left or right. If this sounds a bit abstract, let’s pick a concrete example and see what will happen. Let’s say the cart is centered in the game and stationary, and the pole is tilted to the right and is also falling towards the right. It’ll look something like this: ![game](https://i.imgur.com/KjSx230.png) And the associated state might look like this: ![state table](https://i.imgur.com/E6luv5U.png) The state array would then be [0, 0, 0.2, 0.05]. Now intuitively, we’ll want to straighten the pole back up by pushing the cart to the right. I’ve taken a good policy from one of my training runs and its policy array reads: [-0.116, 0.332, 0.207 0.352]. Let’s do the math real quick by hand and see what this policy will output as an action for this state. Here we’ll dot product the state array [0, 0, 0.2, 0.05] and the policy array (pasted above). If the number is positive, we push the cart to the right, if the number is negative, we push left. ![dot product between policy and state](https://i.imgur.com/OStbHOq.png) The result is positive, which means the policy also would’ve pushed the cart to the right in this situation, exactly how we’d want it to behave. Now this is all fine and dandy, and clearly all we need are 4 magic numbers like the one above to help solve this problem. Now, how do we get those numbers? What if we just totally picked them at random? How well would it work? Let’s find out and start digging into the code! ## Start Your Editor! Let’s pop open a Python instance on repl.it. Repl.it allows you to quickly bring up cloud instances of a ton of different programming environments, and edit code within a powerful cloud IDE that is accessible anywhere as you might know already! ![New Python Project on Repl.it](https://media.giphy.com/media/4T1KlYdYoabwmzSfIS/giphy.gif) ## Install the Packages We’ll start off by installing the two packages we need for this project: numpy to help with numerical calculations, and OpenAI Gym to serve as our simulator for our agent. ![Installing Gym Package on Repl.it](https://media.giphy.com/media/82OOeCknK40hPvkDQv/giphy.gif) Simply type `gym` and `numpy` into the package search tool on the left hand side of the editor and click the plus button to install the packages. ## Laying Down the Foundations Let’s first import the two dependencies we just installed into our main.py script and set up a new gym environment: ```python import gym import numpy as np env = gym.make('CartPole-v1') ``` Next we’ll define a function called “play”, that will be given an environment and a policy array, and will play the policy array in the environment and return the score, and a snapshot (observation) of the game at each timestep. We’ll use the score to tell us how well the policy played and the snapshots for us to watch how the policy did in a single game. This way we can test different policies and see how well they do in the game! Let’s start off with the function definition, and resetting the game to a starting state. ```python def play(env, policy): observation = env.reset() ``` Next we’ll initialize some variables to keep track if the game is over yet, the total score of the policy, and the snapshots (observations) of each step during the game. ```python done = False score = 0 observations = [] ``` Now we’ll simply just play the game for a lot of time steps, until the gym tells us the game is done. ```python for _ in range(5000): observations += [observation.tolist()] # Record the observations for normalization and replay if done: # If the simulation was over last iteration, exit loop break # Pick an action according to the policy matrix outcome = np.dot(policy, observation) action = 1 if outcome > 0 else 0 # Make the action, record reward observation, reward, done, info = env.step(action) score += reward return score, observations ``` The bulk of the code above is mainly just in playing the game and recording the outcome. The actual code that is our policy is simply these two lines: ```python outcome = np.dot(policy, observation) action = 1 if outcome > 0 else 0 ``` All we’re doing is doing the dot product operation between the policy array and the state (observation) array like we’ve shown in the concrete example earlier. Then we either choose an action of 1 or 0 (left or right) depending if the outcome is positive or negative. So far our main.py should look like this: [Github Gist](https://gist.github.com/MikeShi42/c6ea4f19bf628cc40dc9c76087f5d4fb) Now we’ll want to start playing some games and find our optimal policy! ## Playing the First Game Now that we have a function to play the game and tell how good our policy is, we’ll want to start generating some policies and see how well they do. What if we just tried to plug in some random policies at first? How far can we go? Let’s use numpy to generate our policy, which is a 4 element array or a 4x1 matrix. It’ll pick 4 numbers between 0 and 1 to use as our policy. ```python policy = np.random.rand(1,4) ``` With that policy in place, and the environment we created above, we can plug them into play and get a score. ```python score, observations = play(env, policy) print('Policy Score', score) ``` Simply hit run to run our script. It should output the score our policy got. ![policy score of 9.0](https://i.imgur.com/z7EUsWM.png) The max score for this game is 500, chances are is that your policy didn’t fare so well. If yours did, congrats! It must be your lucky day! Just seeing a number though isn’t very rewarding, it’d be great if we could visualize how our agent plays the game, and in the next step we’ll be setting that up! ## Watching our Agent To watch our agent, we’ll use [flask](http://flask.pocoo.org/) to set up a lightweight server so we can see our agent’s performance in our browser. Flask is a light Python HTTP server framework that can serve our HTML UI and data. I’ll keep this part brief as the details behind rendering and HTTP servers isn’t critical to training our agent. We’ll first want to install ‘flask’ as a Python package, just like how we installed gym and numpy in the previous sections. ![Installing Flask Gif](https://media.giphy.com/media/67s8AmPt8GbZdDlhCD/giphy.gif) Next, at the bottom of our script, we’ll create a flask server. It’ll expose the recording of each frame of the game on the `/data` endpoint and host the UI on `/`. ```python from flask import Flask import json app = Flask(__name__, static_folder='.') @app.route("/data") def data(): return json.dumps(observations) @app.route('/') def root(): return app.send_static_file('./index.html') app.run(host='0.0.0.0', port='3000') ``` Additionally we’ll need to add two files. One will be a blank Python file to the project. This is a technicality of how repl.it detects if the repl is either in [eval mode or project mode](https://repl.it/site/docs/repls/files). Simply use the new file button to add a blank Python script. After that we also want to create an index.html that will host the rendering UI. I won’t dive into details here, but simply **upload this [index.html](https://gist.github.com/MikeShi42/7b5ff55e2320e41228b5c25ad1113321) to your repl.it project**. You now should have a project directory that looks like this: ![project directory screenshot](https://i.imgur.com/xOTcsbj.png) Now with these two files, when we run the repl, it should now also play back how our policy did. With this in place, let’s try to find an optimal policy! ![Policy Replay Gif](https://media.giphy.com/media/1ZuOyqmDLilxJrsQi0/giphy.gif) ## Policy Search In our first pass, we simply randomly picked one policy, but what if we picked a handful of policies, and only kept the one that did the best? Let’s go back to the part where we play the policy, and instead of just generating one, let’s write a loop to generate a few and keep track of how well each policy did, and save only the best policy. We’ll first create a tuple called `max` that will store the score, observations, and policy array of the best policy we’ve seen so far. ```python max = (0, [], []) ``` Next we’ll generate and evaluate 10 policies, and save the best policy in max. ```python for _ in range(10): policy = np.random.rand(1,4) score, observations = play(env, policy) if score > max[0]: max = (score, observations, policy) print('Max Score', max[0]) ``` We’ll also have to tell our /data endpoint to return the replay of the best policy. ```python @app.route("/data") def data(): return json.dumps(observations) ``` should be changed to ```python @app.route("/data") def data(): return json.dumps(max[1]) ``` Your main.py should look something like [this now](https://gist.github.com/MikeShi42/3c270ce2d13f2709ef2d5983492a1693). If we run the repl now, we should get a max score of 500, if not, try running the repl one more time! We can also watch the policy balance the pole perfectly fine! Wow that was easy! ## Not So Fast Or maybe it isn’t. We cheated a bit in the first part in a couple of ways. First of all we only randomly created policy arrays between the range of 0 to 1. This just *happens* to work, but if we flipped the greater than operator around, we’ll see that the agent will fail pretty catastrophically. To try it yourself change `action = 1 if outcome > 0 else 0` to `action = 1 if outcome < 0 else 0`. This doesn’t seem very robust, in that if we just happened to pick less than instead of greater than, we could never find a policy that could solve the game. To alleviate this, we actually should generate policies with negative numbers as well. This will make it more difficult to find a good policy (as a lot of the negative ones aren’t good), but we’re no longer “cheating” by fitting our specific algorithm to this specific game. If we tried to do this on other environments in the OpenAI gym, our algorithm would definitely fail. To do this instead of having `policy = np.random.rand(1,4)`, we’ll change to `policy = np.random.rand(1,4) - 0.5`. This way each number in our policy will be between -0.5 and 0.5 instead of 0 to 1. But because this is more difficult, we’d also want to search through more policies. In the for loop above, instead of iterating through 10 policies, let’s try 100 policies by changing the code to read `for _ in range(100):`. I also encourage you to try to just iterate through 10 policies first, to see how hard it is to get good policies now with negative numbers. Now our main.py should look [like this](https://gist.github.com/MikeShi42/e1c5551bbf2cb2064da962ad8b198c1b) If you run the repl now, no matter if we’re using greater than or less than, we can still find a good policy for the game. ## Not So Fast Pt. 2 But wait, there’s more! Even though our policy might be able to achieve the max score of 500 on a single run, can it do it every time? When we’ve generated 100 policies, and pick the policy that did best on its single run, the policy might’ve just gotten very lucky, and in it could be a very bad policy that just happened to have a very good run. This is because the game itself has an element of randomness to it (the starting position is different every time), so a policy could be good at just one starting position, but not others. So to fix this, we’d want to evaluate how well a policy did on multiple trials. For now, let’s take the best policy we found from before, and see how well it’ll do on 100 trials. ```python scores = [] for _ in range(100): score, _ = play(env, max[2]) scores += [score] print('Average Score (100 trials)', np.mean(scores)) ``` Here we’re playing the best policy (index 2 of `max`) 100 times, and recording the score each time. We then use numpy to calculate the average score and print it to our terminal. There’s no hard published definition of “solved”, but it should be only a few points shy of 500. You might notice that the best policy might actually be subpar sometimes. However, I’ll leave the fix up to you to decide! ## done=True Congrats! 🎉 We’ve successfully created an AI that can solve cart pole very effectively, and rather efficiently. Now there’s a lot of room for improvement to be made that’ll be part of an article in a later series. Some things we can investigate more on: - Finding a “real” optimal policy (will do well in 100 separate plays) - Optimizing the number of times we have to search to find an optimal policy (“sample efficiency”) - Doing a proper search of the policy instead of trying to just randomly pick them. - Solving [other environments](https://gym.openai.com/envs/#classic_control). If you’re interested in experimenting more with ML with pretrained models and out-of-the-box working code, check out [ModelDepot](https://modeldepot.io)!
7
posted by MikeShi42 (95) 9 months ago
Python
Python
42
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 by pyelias (656) 8 months ago
Python (with Turtle)
Python (with Turtle)
41
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. Special Credit to JSer for teaching me how to use markdown on this post! Up the pensize to 4 if you want it really blocky using this command! ` t.pensize(4) `
22
posted by John_WardWard (140) 8 months ago
38
How to use a custom domain
In case you've worked with repl.it before, you may have noticed that you are given a decently long subdomain for your project, like the following: `my-little-blog--dotcomboom.repl.co` You may have wanted to change that into a shorter, more memorable domain name, like this: `mylittleblog.cf` Let's see how. ## Getting your domain This section will cover registering a domain name with Freenom. If you already have a domain, [skip this part](https://repl.it/talk/learn/How-to-use-a-custom-domain/8834#attaching-to-repl.it). ### A word on Freenom #### You don't own it Freenom hands a selection of domain names out like free candy. If you've heard of dot.tk, it's these guys. In this tutorial I'll walk you through them, but I'd also like to point out that by registering a domain name with Freenom, you are still not entitled to it. It's perfectly valid and legal for them to all of a sudden deactivate your domain and use it to make money with ads, without notification. This is just a fair warning, some people have had domains from Freenom for a long time without any issues, but anything can happen. In short, nothing could be actually free. You are borrowing Freenom's domains for your purposes, and don't own them like you would from another registrar. #### HTTPS ~~If you use Freenom, you won't be able to use HTTPS. You need to use "http://" before your domain instead. You will still be able to use your repl.co domain name if you need to use HTTPS, so make note of that.~~ **As https://repl.it/@turbio pointed out, HTTPS does work with a Freenom domain! You just need to wait a little bit of time for it to get set up.** As for "mission critical" applications, like, say, Uptime Robot or something like that, you will probably want to use your repl.co domain. ### Registering the domain You will want to make or log into a Freenom account first. Then, you will be brought to the [Client Area](https://my.freenom.com/clientarea.php). Once you're signed in, you will find "Register a New Domain" under the Services menu. ![image](https://storage.googleapis.com/replit/images/1543204601000_441af0314e3fc5e71a0139e9f766e678.pn) This will bring you to Freenom's domain search. Type in the name you want. In this example, I searched for "mylittleblog". It will give you a list of what domains they have available. ![image](https://storage.googleapis.com/replit/images/1543204667654_d8c9142df0d4f1487abdc49631a435ad.pn) Choose the one you want, then scroll down to the bottom and choose "Checkout". Don't touch the section in the middle, we'll cover that later. Choose the period you'll be using the domain, which is from 3 months to 12 months. (If memory serves, when you're going close to the due date, you are offered the opportunity to renew.) ![image](https://storage.googleapis.com/replit/images/1543204740295_ac2737cabaa59f81f9e162774f281755.pn) Check the box to agree to the Terms and Conditions (reading them is a good idea too) and complete the order. Then, go back to your client area. ## Attaching to repl.it ### Repl.it setup Go to your repl and click on the pencil icon next to the address in the preview pane. ![image](https://storage.googleapis.com/replit/images/1543205234697_4f6cbafaf7aae5af99d0c74ae423b95f.pn) Type in your domain name and if the domain is registered correctly, it will prompt you to add a `CNAME` record to your domain: ![image](https://storage.googleapis.com/replit/images/1543205288588_5e41390b98167f4e887b0de892808666.pn) Copy where the record should point to, then go to your client area at your registrar (in my case, Freenom). ### Registrar setup From [My Domains](https://my.freenom.com/clientarea.php?action=domains), go to the management page for the domain you chose. From Management Tools, choose Nameservers. Make sure it is checked to use default nameservers. ![image](https://storage.googleapis.com/replit/images/1543205432252_a191c52c1f996716d91e8266a41efd7c.pn) Then, find the area where you can add records; for Freenom, it is "Manage Freenom DNS". In the Name textbox, enter your domain name, nothing more, nothing less. Change the type to `CNAME`. Then, set the target to what repl.it asked you. Then, choose Save Changes. ![image](https://storage.googleapis.com/replit/images/1543205550116_8df6cb0139894e925b9a6fb80ea454aa.pn) ### Finish Now go back to your repl. Repl.it now should have noticed that your domain is set up correctly and now lets you click on the Link button. ![image](https://storage.googleapis.com/replit/images/1543205653984_83f953b10c6a8cbea3959c8f3709b06d.pn) You're done! Your domain should now be attached to your repl.
26
posted by dotcomboom (54) 7 months ago
37
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
9
posted by LucHutton (156) 8 months ago
35
How I solved the Secret Announcement
# A Detailed Solution to Secret Announcement ### Background: You are most likely busy creating a game for the game jam and you probably know that an announcement came 2 weeks before the jam as a secret message using [steganography](https://en.wikipedia.org/wiki/Steganography) I was one of those chaps who actually solved the secret, but didn't do anything. The challenge can be found [here](https://repl.it/@timmy_i_chen/secret-announcement?ref=newsletter). There was a solution, but that was not very explanatory.This post will explain how ~I~ solved the announcement. This post assumes basic knowledge of the binary system. *** The first thing I did after seeing the newsletter was to read up on steganography.I found this on wikipedia: >Concealing messages within the lowest bits of noisy images or sound files Interesting... ## Reverse Engineering: Then, I looked at the code.Apart from imports and loops to go through all pixels,this was the crux of the code: ```py secret_red = secret_pix[0] >> shift_amt secret_green = secret_pix[1] >> shift_amt secret_blue = secret_pix[2] >> shift_amt public_red = public_pix[0] & all_except_LSB_mask public_green = public_pix[1] & all_except_LSB_mask public_blue = public_pix[2] & all_except_LSB_mask final = ( secret_red + public_red, secret_green + public_green, secret_blue + public_blue ) ``` `>>` and `&` are [binary operators](https://en.wikipedia.org/wiki/Bitwise_operation).shift_amt was 7 and all_except_LSB_mask was 254 What does the >> operator do? It shifts the bits towards towards right.For example: `11100010101 >> 6` outputs `11100` i.e. the last 6 bits are removed. In our case, all the 8 bit data(because 255 is the maximum in RGB color format and 255 is 8 bits) is shifted by 7 bits so that would leave only the highest bit as one or zero. This would also imply that anything greater than 127.5 (255 / 2) would leave 1 while anything lesser would leave zero. `10101010 >> 7 == 1` `01010000 >> 7 == 0` So that's our secret pixel Then, we see the `&` operator with all_except_LSB_mask as 254.The & operator is called bitwise and. Basically, it returns one only if both expressions are one.Like `1&1 == 1` `1&0 == 0` `0&0 == 0` An important property of the & operator is that `something & all 1s = something` another one is that `something & 0 = 0` `10100100`&`11111111`==`10100100` 254 in binary is `11111110` So,all the bits except the last one would remain intact `10011011 & 11111110 ==10011010` So,this would turn all public pixels into even numbers as the last bit is 2**0=1 and if it is absent, the number must be even. The final pixel is secret_pix + public_pix.We know that public pix is either 0 or 1.Since the last bit of public pix is always zero,The last bit of final pixel must reflect the secret image. So here's my code: ```py from PIL import Image public=Image.open('out.png').convert('RGB') secret=Image.new('RGB',(600,600)) for x in range(600): for y in range(600): secret.putpixel((x,y),tuple((i%2)*255 for i in public.getpixel((x,y)))) secret.save('secret.png') ``` All the juicy stuff is in one line:`(i%2)*255 for i in public.getpixel((x,y)` What this does is: + take the public pixel + compute modulo two (returns 1 if odd and 0 if even) + multiply that by 255 because 00000001 or 00000000 show no visible difference but 11111111 and 00000000 do + put this in the secret image, pixel by pixel And Heres my output: ![secret](https://storage.googleapis.com/replit/images/1553919764220_1470a455120ad93feec70c9423124f04.pn) waow indeed
12
posted by Lord_Poseidon (108) 3 months ago
33
Build your very own URL shortener 🔗🚀
## Build a tiny URL shortener, using a remote database ![](https://boring-lamport-1b901a.netlify.com/2018-12-2214-5f2c1bbe-59a2-4ba7-9544-438b1ab5e1dd.39.01.gif) [Demo](https://l.4ty2.fun) ⏯️ [Code](https://repl.it/@jajoosam/tyni) 👨‍💻 Setting up a URL shortener is a lot of work - either you have to pay, or spend hours setting up your own server. This is a guide to making your own URL shortener with [repl.it](http://repl.it) - using `express`, and a remote database - all on `node.js` ## 🛠️ Getting our environment running First up, fork the [https://repl.it/@jajoosam/tyni-starter](https://repl.it/@jajoosam/tyni-starter) repl, so that you have a running project. Next, create a new file - `.env` ![](https://boring-lamport-1b901a.netlify.com/Untitled-675a864b-7c8c-487d-8ca7-595eb8af67ba.png) A `.env` file can store secrets for you, that no one else will be able to see. This is where we want to store our token for accessing the remote database. ## 📁 Making our database We're going to be using [jsonstore.io](http://jsonstore.io) for storing all our URLs. Head over to [jsonstore.io/get-token](https://www.jsonstore.io/get-token) - and copy the token you see - this is the secret we want to store in our `.env` file. Open up your `.env` file, and set `KEY` to your token, like this 👇 ```bash KEY=yourTokenGoesHere ``` Remember to keep **no whitespace**, or your token might not be recognized right! When you open `index.js` you'll see that I've already initialized the database, and a small web server for you. Now let's get to making our API so we can shorten them URLs 🚀 ## 👨‍💻 The API There are two parts to our URL shortener: 1. Storing the short link, corresponding to the long URL - in our database. 2. Redirecting visitors from the short link to the long link Both of these are super simple to implement, thanks to the `express` server we're using - we'll just be collecting `get` requests for both of the tasks. For adding links to our database, we have a special endpoint - requests to it have two parts: the long URL, and the short path. ```javascript app.get('/shorten', (req, res) => { db.write(req.query.key, {"url": req.query.url}); res.status(200); }); ``` Adding this to our code lets us correspond the short path (`key`) to the long `url`, and then we finally send a successful response. For the second task, we'll just be collecting the short path (`key`) from a request, finding the corresponding URL in our database, and then redirecting our visitor ⬇️ ```javascript app.get('/:key', (req, res) => { db.read(req.params.key + "/url").then( (url) => { res.redirect(url); }); }); ``` That's prety much it - we have a fully functional URL shortener 🤯 - check it out for yourself, open a new URL which looks like this 🔗 ``` https://tyni.jajoosam.repl.co/shorten?key=yay&url=https://dsh.re/50854 ``` Now, going to [`http://tyni.jajoosam.repl.co/yay`](http://tyni.jajoosam.repl.co/yay) will be nice to see 👇 ![](https://boring-lamport-1b901a.netlify.com/1-8380b52f-92c2-4acc-87dc-64011c6fd502.jpg) Of course, you'll be replacing `tyni.jajoosam` in those URLs with your own repl! ## ✨ The Frontend Our URL shortener does work, but it's tedious, having to type out a huge URL before shortening it - we can make the whole process much simpler with a simple frontend. I've already created this - and gone for a neat and minimal look using [wing.css](https://github.com/kbrsh/wing) ![](https://boring-lamport-1b901a.netlify.com/Untitled-0fa3af54-ddae-46ca-abdf-4fcbcb218f8b.png) You just have to add code to send visitors to the hompage in the `static` folder 🏠 ```javascript app.get('/', (req, res) => { res.sendFile("static/index.html", {root: __dirname});; }); ``` If you browse through the `static` folder, you'll find a simple `HTML` file with a form, `CSS` to style our page, and most importantly, `JS` to send requests to our URL shortening API. The `HTML` is quite straightforward, we're asking for the long URL, and *optionally* a short path. Open up `script.js` and you'll see the `shorten()` function. Here's what the JS file does (*I've also annotated the code with comments*) 👇 🔍 Getting the path(`key`) and the long `url` from the form. 📝 Possibly generating a random 5 character hash as our path (in case there's no path entered) 🔗 Sending a get request to our API, with our `key` and `url` as parameters 🖥️ Displaying the shortened URL on our page ## 🌐 Getting our custom domain Sure, our links are shorter - but we still don't have them on our own domain, and the `repl.co` links can be pretty long 👀 Luckily for us, the folks at [repl.it](http://repl.it) recently allowed custom domains to be used! That means this project could be something you actually use all the time 😄 Check out `dotcomboom`'s guide on [using custom domains](https://repl.it/talk/learn/How-to-use-a-custom-domain/8834), it should only take a few minutes. It also teaches you about getting free domains 💸 Be sure to put down any questions or improvements down in the comments 💬 - and here's all the code for you to go over again 🤖 https://repl.it/@jajoosam/tyni
11
posted by jajoosam (525) 6 months ago
32
Game Tutorial: SSSnake!
Hi everyone, I put together a little [Snake](https://repl.it/@ericqweinstein/SSSnake) game based on [the arcade game _Blockade_](https://en.wikipedia.org/wiki/Snake_(video_game_genre)) (created in 1976!) and thought I'd write a tutorial on how the game works. (This code is based on work by [Ahira Patel](https://github.com/ahirapatel/python-snake-cli).) Feel free to fork the REPL and add to it! The code is broken up into four main files: `board.py`, `constants.py`, `snake.py`, and `main.py`. The first file manages drawing the game board, `constants.py` sets up nice [enums](https://en.wikipedia.org/wiki/Enumerated_type) for our board colors and symbols, `snake.py` handles drawing the snake itself, and the last file, `main.py`, ties everything together to run our game. ## `constants.py` Since `constants.py` is the simplest, we'll start there. The entire file looks like this: ```py from enum import Enum class Colors(Enum): ''' Terminal colors. ''' BLUEBACK = '\x1b[44m' END = '\033[0m' GREEN = '\033[92m' RED = '\033[91m' class Symbols(Enum): ''' Symbols used during gameplay. ''' SNAKE = f'{Colors.GREEN.value}o{Colors.END.value}' EMPTY = ' ' GRID = '.' FOOD = f'{Colors.RED.value}*{Colors.END.value}' WALL = f'{Colors.BLUEBACK.value}{Colors.GREEN.value}|{Colors.END.value}' ``` All we're doing is setting up some nicer syntax so we can use `Colors.RED.value` or `Symbols.FOOD.value` throughout our code. This also makes it easier for us to change things throughout our program by centralizing logic in one place—for example, we can change the "food" symbol from `*` to `+` by just changing one character. ## `board.py` Next, let's take a look at `board.py`. This file is a little longer, so we won't reproduce it here, but feel free to follow along in the REPL as we move from function to function. All our functions are inside a `Board` class, which keeps track of the symbols we use in the terminal for the various pieces of our board (such as walls and empty squares). (Note that functions inside classes are called _methods_, so we'll call them that throughout this tutorial.) We also do some arithmetic to build the board from rows and columns, which are in turn dictated by the dimensions of our terminal. (Feel free to play around with different terminal sizes! You can find these values in the `get_terminal_dimensions` function in `main.py`.) Next, we define [getters and setters](https://en.wikipedia.org/wiki/Mutator_method), `get` and `set`. The `get` method gives us the symbol associated with a particular pair of terminal coordinates (that is, what symbol is located at a particular row and column), and the `set` method lets us change the symbol located at a set of coordinates. We also define `width` and `height` to give us the number of columns and rows, respectively, as well as an `is_valid_coord` method that checks if a proposed row/column coordinate pair is within the bounds of our terminal. Our last two methods handle drawing the board itself. The `draw_initial_board` method does exactly that: it goes through and draws the board row-by-row (including the outer walls). Finally, the `draw` method goes to the provided coordinates on the board and draws the provided symbol (for example, drawing the food symbol at a random spot on the board). Note that both methods use `sys.stdout.flush()` to ensure the changes we've made are written to the screen (since content we write to the terminal is buffered; you can read more about data buffers in [here](http://en.wikipedia.org/wiki/Data_buffer)). You can think of `write`ing as telling the program how the terminal content is going to change, and `flush`ing makes those changes appear in the terminal. ## `snake.py` Moving on, we get to the `Snake` class in our `snake.py` file. In our `__init__` method, we keep track of the snake's current direction, head, tail, and what the snake has eaten, as well as a bit of bookkeeping to help us draw the snake. (A discussion of threading in Python is beyond the scope of this tutorial, but you can Google "Python threading" to find some more information on the topic, such as [this WikiBook](https://en.wikibooks.org/wiki/Python_Programming/Threading).) Most of our snake's functionality can be found in the `move` method, which controls the snake's movement across the board: we acquire the lock (ensuring no other threads can change the game state while we're in the middle of moving), move the head to its new position, remove the tail, and then signal that we're done moving by updating our `movement_processed` flag and releasing the thread lock. The result? Our snake moves one cell at a time across the board! The `consume` method handles the snake's behavior when it eats something: when it successfully eats the food symbol, we grow the snake by one unit. The `is_hungry` method helps us figure out whether the snake has recently eaten any food, and `is_dead` handles the two conditions that make us lose the game: if we "eat" a wall or "eat" our own tail (that is, collide with a wall or ourselves). The `set_movement` method allows the snake to change direction (note that it prevents a snake that's more than one unit long from "reversing"—that is, the snake can't immediately go down while it's going up, left while it's going right, and so on). Last but not least, the `get_head` and `get_old_tail` methods are helpers that make it easier for us to get ahold of the snake's head and tail while updating its state on the board. ## `main.py` Finally, we'll tie everything together in a `Game` class inside our `main.py` file. Most of our game logic lives here, so we'll spend a bit more time unpacking this code. First, we `__init__`ialize our class with a board (`self.board`), how many pieces of food the player has to eat to win (`self.num_food`), and the snake (`self.snake`), as well as some bookkeeping to keep track of whether the game is over (`self.over`) and, if so, how the player signalled they wanted to quit the game (`self.key_quit`, `self.sig_quit`). Next, we have our `play` method, which `sleep`s for two seconds to give the player time to switch over to the REPL, then does the following inside a loop: * Ends the game as needed (if the player crashes into a wall/themselves, eats all the food, or quits); * Updates the game board state; * Draws the updated board on the terminal; * Briefly sleeps to allow the user time to react. Next, the `spawn_new_food` method does what you'd expect: it generates a random coordinate, tries to place the food at that spot, and retries if it's not successful (for example, if the snake is already occupying that spot on the board). The `draw_game_board` and `update_game_board` are also fairly straightforward: the first method updates the board (and the snake as well, as long as it's still hungry), and the second updates the game state by moving the snake and updating the board, allowing the snake to consume whatever's in the current square (growing the snake if it eats food and ending the game if the snake bites the wall or itself). Outside of our `Game` class, we have a handful of helper functions that allow us to handle user input and nicely transition the terminal from "game mode" back to the regular REPL (and vice-versa). These can be a little confusing, since they have more to do with the particulars of the terminal than the mechanics of our game, so we'll go over them one by one: * `movement_listener` listens for user input and sets the snake's direction via `snake.set_movement()`. (It also does some nice things to ensure the terminal looks good; these are described in the comments.) * `get_terminal_dimensions` is just a nice helper function for getting the height and width of our terminal. (We actually do some subtraction to make the dimensions slightly smaller than the actual terminal, in order to ensure the entire game is visible on-screen.) * `start_alternate_screen` and `end_alternate_screen` are pretty much as-advertised: they handle the switch to the terminal game from the REPL and back again. * `exit_as_needed` is also pretty straightforward: it handles the four ways our game can end (the user loses by crashing the snake, the user wins by getting all the food, or the user quits the game by either explicitly quitting or stopping the game by sending `Ctrl-C`). * `signal_handler` is a callback function we provide to `signal.signal` to tell Python what to do if it gets an interrupt (`SIGINT`) or terminate (`SIGTERM`) signal from the user: in either case, we quit the game. * Finally, `quit` sets `game.over` to `True` and cleans up the game terminal, restoring our settings to the way they were before the game started. The last few lines of code in `main.py` set up our game for us by getting the terminal dimensions, showing a countdown timer for the game to begin, handle the switch from the "regular" REPL to the game (lines 181 to 183), and finally, creating a new game and starting it. ...and that's it! I hope you enjoyed this tutorial, and feel free to [fork the REPL](https://repl.it/@ericqweinstein/SSSnake) and add more to the game.
0
posted by ericqweinstein (193) 7 months ago
28
Tutorial: Building a Discord Bot with Python
Hey all, I published this tutorial on writing chatbots with Python and Discord a few weeks ago and I'm excited to share it with you here now. I'm watching the comments here and over at codementor so let me know if you have any questions. https://www.codementor.io/garethdwyer/building-a-discord-bot-with-python-and-repl-it-miblcwejz
11
posted by GarethDwyer1 (90) 9 months ago
27
Learning Web Development w/ Python Part 1
# Learning Web Development with Python and Django ## Part 1 *If you already know a bit about web development, then check out [Gareth Dwyer's Tutorial](https://repl.it/talk/learn/Tutorial-Building-a-Django-web-application/6660). This tutorial is intended for beginners, and takes things a bit more slowly.* ## Welcome! In this tutorial, I'm going to be teaching you how you can use the `Django` web framework to make your own web apps with Python. ### Prerequisites For this tutorial, you should have a decent understanding of Python. Knowing some `HTML` and `CSS` helps. ## The Client and the Server Before we can start coding our own web app, we need to know a little of how the internet actually works - clients and servers. **Servers** Servers are basically the computers that 'run the websites'. Each website has its own server (in reality, large websites have lots of servers). Each server has its own **domain name**, e.g. www.google.com or www.repl.it. **Clients** Clients are computers that connect to servers - i.e. people who visit the website. ### How do Clients connect to Servers? This depends largely on what **protocol** is being used. The most common protocols are `http` (hyper-text transfer protocol) and `https` (secure hyper-text transfer protocol). On a very basic level, what happens is: * The client sends out a message saying "I want to see this page on this website, my address is xxxxx". * The message arrives at the server. * The server checks which page to send and then sends it back in the form of `html` (and often other filetypes, but we will be focusing on html here). * The browser of the client interprets the html to give a visual output. ### How does this apply to Django? When we use Django, we're basically writing our own server. Django takes care of all the sending and stuff, all we have to do is add our pages, and put them in a place Django can find them. ------------------------------------------------------------------------------------------ By now, you'll be itching to write some code, so lets get started! When you create a Django project on repl, there is already some code in there, so I have made a [basic template](https://repl.it/@ArchieMaclean/Basic-Template) which has the bare minimum. Open the template, and click the `fork` button at the top to make your own copy. ![image](https://storage.googleapis.com/replit/images/1554625804315_2a5ed0a55c14c016feacd6dc438d3b20.pn) You can now rename it to `hello-world` (or something else if you prefer). ## Creating your very first app Before we make any changes, you can click the square icon in the top right of the view panel: ![image](https://storage.googleapis.com/replit/images/1554625969590_1b80aeda3f1db062a5e7916c97db3ae3.pn) This will open the page in a new tab so you can see the fullscreen version of it. You should get a page like this: ![image](https://storage.googleapis.com/replit/images/1554626030130_fdf8263732fa1645061a5e309c29154f.pn) This is just the standard Django page, which appears when you haven't written any code yet. ### Creating our first web page When you type in a URL (such as https://ww.repl.it/languages/python) on a browser, there are three parts: * **Protocol** - almost always `http` or `https`. * **Domain name** - looks like `www.repl.it/`. * **Page name** - looks like `languages/python`, and is after the domain name. With our project, we don't need to worry about the domain, because `repl` creates one for us to use (in the form `<repl-name>--<username>.repl.co`). However, we will need to think about our page names. #### URLs and Views There are 2 parts to displaying a page on Django - the URL, and the `view`. The `view` is what the client will see when they visit the page. ##### Writing our view For this first project, we will be using **function-based views**. This means that each view is a Python `function`. Navigate to the `views.py` file, and add the following code: ```python from django.http import HttpResponse def homePageView(request): html = "Hello, World!" return HttpResponse(html) ``` So, what does this code do? `Line 1` imports HttpResponse , which we will need in order to return the html in the correct format. On `Lines 3-5` we create our view. * `Line 3` - this is our function, called `homePageView`, because it will be the homepage of our website. It takes `request` as an argument - for more advanced projects, you will use `request` in your function, but we don't need to worry about it right now. `request` is a request **object**, that carries information about the request for the page. * `Line 4` - this is the html for the website. This is extremely simple hmtl - it doesn't have any tags, all it has is the text `"Hello, World!"`. * `Line 5` - this is where we return the html, in a form Django can understand (`HttpResponse`) If we run this code, we get...nothing! The reason for this is that Django doesn't know what to do with the view. ##### Adding the URL (Page name) We need to tell Django where the view should be displayed. Navigate to the `urls.py` file, and add the following: ```python from .views import homePageView ``` Then change `urlpatterns` to: ```python urlpatterns = [ url(r'^admin/', admin.site.urls), url('',homePageView,name="home"), ] ``` Before we analyse the code, go to your website (in the other tab), and refresh. You'll see we got we wanted! ![image](https://storage.googleapis.com/replit/images/1554627432054_c0f2284207576ce83123b494a7735ee8.pn) So how did this happen? Let's look at the code. ```python from .views import homePageView ``` This imports our `homePageView` function from the `view.py` file. The period `.` at the start tells Django to open it from the current directory (`main`). This is needed because the code will be run from somewhere else, so Django could get confused and try to import it from a different folder. In `urlpatterns` we added ```python url('',homePageView,name="home"), ``` (Note that `''` is 2 single-quotes, not 1 double quote) This tells Django to treat it as a url. There are 3 arguments given: * The first (`''`) is the page name, which I described earlier. If it was something like `about/aboutme` then the page would be located at https://domain.name/about/aboutme (replacing `domain.name` with the domain name, obviously). However, it is just `''` so the view will be located at just https://domain.name/. * The second is our view that we created in `views.py` and imported earlier. * The third is the *name* we give our page. It is not essential, but will come in useful later when we want to keep track of all the pages. ------------------------------------------------------------------------------------- ### Congratulations! You've made your first web page with Django! It may seem a bit convoluted right now, but this format is very helpful when we make bigger web applications and have many files. #### That concludes Part 1 In [Part 2](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-2/12884), we will be looking at the more powerful `class-based views`, as well as multiple pages in out project. Please upvote if you found this tutorial helpful, it supports me and lets me know that you want more! If you have any questions, post in the comments and I (or someone else) will answer them.
2
posted by ArchieMaclean (489) 2 months ago
27
Cave Commander!
Hi everyone, I made a little text-based adventure game in Python called [Cave Commander](https://repl.it/@ericqweinstein/CaveCommander) based on [Colossal Cave Adventure](https://en.wikipedia.org/wiki/Colossal_Cave_Adventure). It's pretty simple right now—only a few rooms in the cave and a handful of items—so feel free to fork the REPL and add to it! The code is divided into three files: `main.py`, `cave.py` (where the cave map is stored), and `constants.py` (where we keep [regular expressions](https://docs.python.org/3/library/re.html) that match against possible commands the player might enter, like `go north` or `take cage`). Let's start with `cave.py`. ```py Map = { 'start': { 'description': 'You are standing at the end of a road before ' \ 'a small brick building. Around you is a ' \ 'forest. A small stream flows out of the ' \ 'building and down a gully to the SOUTH.', 'exits': { 'South': 'grate' }, 'items': [] }, 'grate': { 'description': 'You reach the end of the stream, which flows ' \ 'down through a metal grate and disappears. ', 'exits': { 'North': 'start', 'West': 'debris' }, 'items': ['cage'] }, 'debris': { 'description': 'You walk along a shallow gully and duck under' \ ' the remains of a small bridge. You\'re in a ' \ 'dimly lit room littered with debris.', 'exits': { 'East': 'grate', 'West': 'bird' }, 'items': ['rod'] }, 'bird': { 'description': 'You follow a tunnel into a larger room where' \ ' you can stand upright without hunching.' \ ' You can hear rustling and twittering.', 'exits': { 'East': 'debris', 'South': 'mists' }, 'items': ['bird'] }, 'mists': { 'description': 'You\'re in a huge hall that extends as far ' \ 'as you can see in an east/west direction. ' \ 'The ceiling is shrouded in darkness. An ' \ 'eerie mist covers the floor.', 'exits': { 'North': 'bird', 'West': 'end' }, 'items': [] }, 'end': { 'description': 'You made it to the end.', 'exits': {}, 'items': [] } } ``` Not a lot of fanciness here: just a Python `dict` that keeps track of the rooms in our cave. Note that each entry in the map is a key/value pair where the key is the room name and the value is another map describing that room. Each room has a `'description'`, a list of `'exits'` where the player can go next, and a list of `'items'` that are in the room. Next up: `constants.py`! ```py import re class Directions(object): NORTH = re.compile('(?:^\s*n\s*$|.*north\s*$)', re.IGNORECASE) SOUTH = re.compile('(?:^\s*s\s*$|.*south\s*$)', re.IGNORECASE) EAST = re.compile('(?:^\s*e\s*$|.*east\s*$)', re.IGNORECASE) WEST = re.compile('(?:^\s*w\s*$|.*west\s*$)', re.IGNORECASE) class Commands(object): TAKE = re.compile('^\s*(?:take)\s+(.*)', re.IGNORECASE) DROP = re.compile('^\s*(?:drop)\s+(.*)', re.IGNORECASE) INVENTORY = re.compile('(?:^i$|.*inventory)', re.IGNORECASE) HELP = re.compile('(?:^h$|.*help\.*)', re.IGNORECASE) ``` (It's a little overkill to put these in classes, but it will make the syntax nicer later on when we start building out `main.py`.) Note that there are two classes: `Directions` for handling directions the player might want to move in, and `Commands` for other actions (such as picking up and dropping items, checking the player's inventory of items, or getting help in terms of which direction to go next). If you're not used to regular expressions, these might look scary, but they're not too bad! Let's look at `NORTH` as an example. When we type `re.compile('(?:^\s*n\s*$|.*north\s*$)', re.IGNORECASE)`, we're telling Python to build the regular expression `(?:^\s*n\s*$|.*north\s*$)` and to match in a case-insensitive way (that is, we'll match `'north'`, `'North'`, `'NORTH'`, `'nOrTh'`, etc). The first bit, `(?:^\s*n\s*$`, says to match the start of the line (`^`) through the end of the line (`$`), allowing any amount of whitespace (`\s*`) at the beginning or end, and look for the letter `n`. (The `?:` part just tells Python not to keep track of what got matched, since we won't be using it in our code.) The next part, `.*north\s*$`, tells Python to match anything at all (`.*`), followed by `north`, followed by optional whitespace (`\s*`) and then the end of the line (`$`). These two matches are separated by a pipe, `|`, so the entire regular expression says: "Match _either_ the letter 'n', or the word 'north', allowing whitespace on either side, and allowing anything at all before the word 'north'." That way if the player enters 'n', or ' n ', or 'go north', or 'let's go north ', etc., our program will be able to match that input and do the right thing. **Note** that regular expressions can be tricky, so be careful when adding new ones (and apologies in advance if you try to use input that my regular expressions aren't expecting!). I've found [Pythex](https://pythex.org/) to be a really valuable tool for testing my Python regular expressions. Okay! Now on to the main (pun intended) event: `main.py`. Let's start by importing our other files and creating the skeleton of our game: ```py import re from constants import Directions, Commands from cave import Map class Game(object): def __init__(self): self.map = Map self.location = 'start' self.inventory = [] def start(self): while True: instruction = input('> ') if __name__ == '__main__': game = Game() game.start() ``` In our `__init__()` function, we ensure we have access to our cave map, set our location to `'start'` (the first room in our map), and initialize an empty inventory. We also add a `start()` method, which just creates a prompt and lets the user enter input. Next, let's add a new method, `follow()`, that lets the user move around the map. Add this code inside the `Game` class, between `__init__()` and `start()`: ```py def follow(self, instruction): if re.search(Directions.NORTH, instruction): try: self.location = self.map[self.location]['exits']['North'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.SOUTH, instruction): try: self.location = self.map[self.location]['exits']['South'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.EAST, instruction): try: self.location = self.map[self.location]['exits']['East'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.WEST, instruction): try: self.location = self.map[self.location]['exits']['West'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') if not self.map[self.location]['exits']: print('You win!') ``` And let's update our `start()` method to use it: ```py def start(self): print(self.map[self.location]['description']) while True: instruction = input('> ') try: self.follow(instruction) except RuntimeError as err: print(err) ``` If you run the REPL, you should now be able to move around the map. From the starting position, try going `south`, then `west`. If you get stuck, take a look at `cave.py` to read the map and see where you can go next. Checking out the map is fun, but it would be better if we could get hints to tell us where to go next. In order to interact with our game, we'll need to use the `Commands` we included in `constants.py`. In order to do that, we'll update our `follow()` method to use the commands for taking/dropping items, checking our inventory, and getting help with directions, as well as adding a little helper method, `take_item()`, to handle item logic (if you want to catch a bird, you're gonna need a cage, right?). When we add those methods, we get our complete code, which looks like this: ```py import re from constants import Directions, Commands from cave import Map class Game(object): def __init__(self): self.map = Map self.location = 'start' self.inventory = [] def take_item(self, item): if item == 'bird': if 'cage' not in self.inventory: print('With what? Your bare hands? You should probably use a cage or something...') return if 'rod' in self.inventory: print('The bird is frightened and impossible to catch.') return try: self.map[self.location]['items'].remove(item) self.inventory.append(item) print('You picked up a %s.' % item) except ValueError: print('There\'s no %s for you to take.' % item) def follow(self, instruction): if re.search(Directions.NORTH, instruction): try: self.location = self.map[self.location]['exits']['North'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.SOUTH, instruction): try: self.location = self.map[self.location]['exits']['South'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.EAST, instruction): try: self.location = self.map[self.location]['exits']['East'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Directions.WEST, instruction): try: self.location = self.map[self.location]['exits']['West'] print(self.map[self.location]['description']) except KeyError: print('You can\'t go that way.') elif re.search(Commands.TAKE, instruction): match = re.search(Commands.TAKE, instruction).group(1).strip() self.take_item(match) elif re.search(Commands.DROP, instruction): match = re.search(Commands.DROP, instruction).group(1).strip() try: self.inventory.remove(match) self.map[self.location]['items'].append(match) except ValueError: print('You don\'t have a %s to drop.' % match) elif re.search(Commands.INVENTORY, instruction): [print('You\'ve got a %s.' % item) for item in self.inventory] if self.inventory else print('You\'re not carrying anything.') elif re.search(Commands.HELP, instruction): print('Available directions are:') [print(' %s' % direction) for direction in self.map[self.location]['exits']] else: print('I don\'t understand which way you want to go. ' \ 'Please try NORTH, SOUTH, EAST, or WEST.') items = self.map[self.location]['items'] if items: [print('There\'s a %s here.' % item) for item in items] if not self.map[self.location]['exits']: print('You win!') def start(self): print(self.map[self.location]['description']) while True: instruction = input('> ') try: self.follow(instruction) except RuntimeError as err: print(err) if __name__ == '__main__': game = Game() game.start() ``` And that's it! Try moving `south` and `west`, picking up items when you find them (`take bird`), checking your inventory (`inventory`, or just `i`), and getting help with directions whenever you're stuck (`h` or `help`). I hope you enjoyed this tutorial, and again, feel free to [fork the REPL](https://repl.it/@ericqweinstein/CaveCommander) to add more to the game!
2
posted by ericqweinstein (193) 9 months ago
27
Tutorial: Two Player 2048 w/ JS/Node/Express + Socket.io
Hey Everyone! I wrote a multiplayer 2048 game, converting the classic 2048, adding a Node.js server + Socket.io, so you can race with your friends in 2048! I've also written a guide below on how I was able to build this step-by-step for some inspiration :) Check out [the demo here](https://repl.it/@MikeShi42/competitive-2048-demo-final)! Fork the repl and share your fork’s link with a friend to play with them! ![competitive 2048 game gif](https://media.giphy.com/media/fQDbaH9kl4O0UWtc3Y/giphy.gif) # Guide Today we’re going to turn the classic 2048 game, into a competitive multiplayer game for you to race with your friends. The best part is that with repl.it, socket.io and the original open source 2048 code makes this really easy to do! You’ll want to have some experience with HTML/CSS/JS and Node.js to get started with this guide. # Getting Started [repl.it](https://repl.it) is a powerful and beginner friendly web-based IDE that allows you to kick off a programming environment in almost any language you’d ever want to try with a couple of clicks. It has insanely easy Node.js/Express project hosting which we’ll use for this multiplayer project! To start, we’re going to [fork off this starter project](https://repl.it/@MikeShi42/competitive-2048-starter), that’s simply the [2048 single player version](https://github.com/gabrielecirulli/2048) uploaded to repl.it with minimal changes. ![repl.it fork gif](https://media.giphy.com/media/fQuCU2FHuhGym3tuq5/giphy.gif) # Setting Up our Socket.io Server Now with our project set up and base files in place, we can start coding our Node.js server that will coordinate the moves between two players. We’ll be using [Socket.io](https://socket.io/) to let our clients and our server communicate in real time, without latency of HTTP requests and other complexities. Socket.io is a library that handles delivering messages back and forth between our client code (browser game) and our Node.js server via [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). In our game, it’ll allow our games to tell the server about moves we make, and the server to tell us about moves our opponents make, with only a few lines of code! ## Installing the Socket.io NPM Package We first want to install the socket.io package, we can do this via the package tool on the left side of your repl.it editor, and simply search “socket.io” and click the + icon. ![adding socket.io gif](https://media.giphy.com/media/SFL9z46BeHGaAuld6q/giphy.gif) ## Initializing Our Server Next we can go to our “index.js” file for our Node server and clear out the current content so we can start fresh! We’ll then want to import Express, Socket.io and HTTP server dependencies to be able to serve the front-end code we just uploaded into the “public” folder, and accept messages via Socket.io. ```javascript const express = require('express'); const socketio = require('socket.io'); const http = require('http'); const app = express(); const server = http.Server(app); const io = socketio(server); // Attach socket.io to our server app.use(express.static('public')); // Serve our static assets from /public server.listen(3000, () => console.log('server started')); ``` ## Handling Connections Next we’ll want to create an array to hold our users and assign them a player number when they connect to our server. Add this bit of code right after the server.listen line: ```javascript const connections = [null, null]; // Handle a socket connection request from web client io.on('connection', function (socket) { // Find an available player number let playerIndex = -1; for (var i in connections) { if (connections[i] === null) { playerIndex = i; } } // Tell the connecting client what player number they are socket.emit('player-number', playerIndex); // Ignore player 3 if (playerIndex == -1) return; connections[playerIndex] = socket; // Tell everyone else what player number just connected socket.broadcast.emit('player-connect', playerIndex); }); ``` `io.on(‘connection’, function...)` listens for new client connections, and handles each connection by calling the defined function. `socket.broadcast.emit` will send a message to all other clients connected to the server and `socket.emit` will send a message to only the current connected client. Now when a user connects, they’ll be given a player number (either 0, 1 or -1 if the game is full), and everyone else will know when a user has connected (so we know to start the game). ## Handling Moves Next, inside of our connection callback, we can handle when a user gives us a move, we should broadcast it to the other player. We can paste this bit of code right after the `socket.broadcast.emit` line from above. ```javascript socket.on('actuate', function (data) { const { grid, metadata } = data; // Get grid and metadata properties from client const move = { playerIndex, grid, metadata, }; // Emit the move to all other clients socket.broadcast.emit('move', move); }); ``` ## Handling Disconnects We don’t want a player that disconnects to “ghost” on our server as a real user. So we’ll also clear out that user’s socket handle when they disconnect. ```javascript socket.on('disconnect', function() { console.log(`Player ${playerIndex} Disconnected`); connections[playerIndex] = null; }); ``` We can simply add the above snippet below our ‘actuate’ message handler. Your `index.js` should now look like [this](https://gist.github.com/MikeShi42/13b11837c02ad20807d44cd40e8371e4). # Creating our Second (Remote) Game Board Now with the server stuff out of the way, we can focus on turning our single board 2048, into a multi-board 2048! ## Copy Pasta The first thing we’d need to do, is literally copy and paste a second board from our public/index.html document. We first wrap the `<div class="game-container">...</div>` element in another div like `<div id="player-one"><div class="game-container">...</div></div>`. We can duplicate that div and name it “player-two”. In the end, part of your index.html should look like this [gist](https://gist.github.com/MikeShi42/82c173656e539185d78711e53ce293fd). This way we have two boards, and we can address each by their class name as either player-one or player-two. # Sending Messages Over WebSocket Now that we have two game boards, we’ll want to be able to control them over websockets. ## Connecting the Sockets First we’ll want to start talking to our server via socket.io. We’ll want to include the socket.io library via a <script /> tag in `public/index.html`. Like so: ```html ... </div> <!-- Below is the script tag you need to add! --> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script> <script src="js/utils/keyboard_input_manager.js"></script> ... ``` That way we’ll have the socket.io library loaded before any of our game code, any avoid any errors referencing the socket library in our code. Next we’ll have to actually initialize the connection in `public/js/application_manager.js`. ```javascript window.requestAnimationFrame(function () { var socket = io.connect(window.location.origin); ... ``` Here we’re telling the socket.io to connect to our server, and the server is located at `window.location.origin`. This allows it to connect to whatever URL is hosting the page, so if you fork the repl.it, it’ll automatically point to your fork’s URL, instead of a hardcoded URL. ## Modifying Game Manager Now we’ll want to modify the game manager so that it can handle remote players and handle local players. In `public/js/game_manager.js` we can add two new arguments in the front of the constructor called `remotePlayer` and `socket`. `remotePlayer` will be a boolean representing if this GameManager is managing a remote player, or the local player. `socket` will be the socket.io connection we just initialized in the above section. The first couple lines of `public/js/game_manager.js` should look like this: ```javascript class GameManager { constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { this.size = size; // Size of the grid this.inputManager = new InputManager(); ... ``` Before the end of the constructor, we’ll want to “save” the `socket` and `remotePlayer` values as local properties of the object. We’re also going to pass in `remotePlayer` as an argument to `Actuator`, which we’ll use later to decide which HTML Grid we should update (depending if it’s for player 1 or player 2). ```javascript constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { this.size = size; // Size of the grid this.inputManager = new InputManager(); this.storageManager = new StorageManager; // Change Actuator to take in remotePlayer as an argument! this.actuator = new Actuator(remotePlayer); this.startTiles = 2; ... this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); // Add these two lines this.remotePlayer = remotePlayer; this.socket = socket; this.setup(); } ``` ## Sending Moves over Websocket Now we want that every time we make a move on our local board, we should tell the server about it, and the server will tell player 2 about the move we just made. First we want to create a function in our GameManager that will handle sending remote moves. We can simply insert this below our GameManager constructor we were writing in the previous section. ```javascript sendRemoteMove(grid, metadata) { if (!this.remotePlayer) { this.socket.emit('actuate', { grid: grid, metadata: metadata }); } } ``` This function takes in a grid: the current board state, and metadata: the score, win/loss, etc. of the game currently. If the current GameManager is not the remote player (so it’s the local player), then we should send the move over. We’ll emit a message with the event name of “actuate”. Notice how this event name matches the one we’re listening for on the server in `/index.js`. The second argument specifies the message payload of `grid` and `metadata`. Now we want to call our function from `GameManager.actuate`. Notice the function already calls this.actuator.actuate which takes a grid and some metadata object. We can similarly call our `sendRemoteMove` function right after it. The `actuate` function should look like the below: ```javascript // Sends the updated grid to the actuator actuate() { if (this.storageManager.getBestScore() < this.score) { this.storageManager.setBestScore(this.score); } // Clear the state when the game is over (game over only, not win) if (this.over) { this.storageManager.clearGameState(); } else { this.storageManager.setGameState(this.serialize()); } const grid = this.grid; const metadata = { score: this.score, over: this.over, won: this.won, bestScore: this.storageManager.getBestScore(), terminated: this.isGameTerminated() }; this.actuator.actuate(grid, metadata); this.sendRemoteMove(grid, metadata); // Call our sendRemoteMove function! } ``` ## Handling Remote Moves over Websocket We’ll also want to be able to take moves from player 2, and replay them on our local player 2 board to see what our competitor is doing. First we want to define a function that can take a remote move and change the board to make the move. We’ll define the function right after `sendRemoteMove` that we defined before. ```javascript handleRemoteMove(data) { const grid = data.grid; const metadata = data.metadata; this.actuator.actuate(grid, metadata); } ``` Next we’ll want to set up an event handler that will listen to when the remote player makes a move, but only if the current GameManager is handling the remote board. We’ll want to add a new if switch to our constructor function ```javascript constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { ... // Add these two lines this.remotePlayer = remotePlayer; this.socket = socket; // Add this new if statement if (this.remotePlayer) { this.socket.on('move', this.handleRemoteMove.bind(this)); } this.setup(); } ``` If you’re testing the game now, you might notice that sometimes one player can sometimes update the other player’s board, but things aren’t consistent and everything is a bit buggy. We’ll be fixing that up in the following steps! ## Updating Player 2’s HTML Board Now that we can get moves over the socket connection, we want to update the correct board so that we can see what our opponent is doing. We’ll want to modify `public/js/html_actuator.js`, specify the HTMLActuator constructor so that it’ll target the right game board depending if it’s the local player or remote player. The constructor should look like this: ```javascript class HTMLActuator { constructor(remotePlayer) { if (remotePlayer) { this.tileContainer = document.querySelector("#player-two .tile-container"); this.messageContainer = document.querySelector("#player-two .game-message"); } else { this.tileContainer = document.querySelector("#player-one .tile-container"); this.messageContainer = document.querySelector("#player-one .game-message"); } this.scoreContainer = document.querySelector(".score-container"); this.bestContainer = document.querySelector(".best-container"); this.score = 0; this.remotePlayer = remotePlayer; } ``` We’re swapping out the old querySelector for tile container and game messages for one that targets specifically player one or player two’s game board. Additionally, we’re also going to save the remotePlayer as a local property so we can access it later. ## Duplicating Game Manager Next we can create another GameManager for player 2 in `public/js/application.js`, pass in the new arguments that we’ve defined for GameManager, and save the GameManager instances for later. We’ll create two variables called “remoteGame” and “localGame” to store the two GameManager instances we’ll create. After everything, the application.js file should look something like this: ```javascript let remoteGame = null; let localGame = null; // Wait till the browser is ready to render the game (avoids glitches) window.requestAnimationFrame(function () { const socket = io.connect(window.location.origin); remoteGame = new GameManager(socket, true, 4, KeyboardInputManager, HTMLActuator, LocalStorageManager); localGame = new GameManager(socket, false, 4, KeyboardInputManager, HTMLActuator, LocalStorageManager); }); ``` We’ve changed the GameManager to take the `socket` we’ve defined earlier as well as a bool value representing if the GameManager is responsible for the remote board or local board. With that in place, we’re now actually pretty close to having two boards being able to interact with each other. If you’re testing it, you might notice that by opening two different tabs of 2048, that they’re able to talk to each other, but also seem to be weirdly linked together. We’ll fix that right now! ## Don’t Listen To My Keys An issue right now is that both GameManager (both remote and local) are listening to your keystrokes. Which leads to really weird behavior. Let’s make it so that only the local GameManager listens to keystrokes while the remote one only actuates on a socket message. In our GameManager constructor we want to only listen to keystrokes if it’s not the remote player. Additionally, we’ll move the listener binding code into the `setup` function, which will help us control when the user can start issuing inputs into the game (which will be helpful later). GameManager Before: ```javascript class GameManager { constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { ... this.startTiles = 2; // We’ll be deleting these 3 lines this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); this.remotePlayer = remotePlayer; ... ``` After: ```javascript class GameManager { constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { ... this.startTiles = 2; this.remotePlayer = remotePlayer; ... ``` Setup Before: ```javascript setup() { var previousState = this.storageManager.getGameState(); ... } ``` Setup After: ```javascript setup() { if (!this.remotePlayer) { this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); } var previousState = this.storageManager.getGameState(); ... ``` This makes sure that we’re only listening to moves when we’re the local player, and only after `setup` is called. ## Testing! With that, the basic game should be done! You can open two tabs to test out how your moves can be seen by both tabs. However, there’s still a lot of rough edges that need to be ironed out. You may have noticed that the board starts from the last saved state, and you never know if your friend has connected yet and whatnot. We’ll tackle all of those issues in the next section! # Game Polish ## Removing Locally Saved State We don’t want to start the game from whatever we last left off at, as that would gives us an unfair advantage! Instead we’ll disable the ability to restore the game state from local storage. We’ll simply delete the restoring mechanism in `GameManager.setup` in `public/js/game_manager.js`. Additionally, we’ll only put down starting tiles if it’s the local game, so we don’t populate the remote board with starting tiles. In the end our setup function should look like this: ```javascript setup() { if (!this.remotePlayer) { this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); } this.grid = new Grid(this.size); this.score = 0; this.over = false; this.won = false; this.keepPlaying = false; if (!this.remotePlayer) { // Add the initial tiles this.addStartTiles(); } // Update the actuator this.actuate(); } ``` ## Game Starting Message We want to know when player 2 has connected, as well as provide a countdown so that there is a delay between when player 2 has connected, and when the game will start. We’ll first want to add the HTML elements to inform the user that they’re waiting for the next player and a countdown timer message as well. We’ll want to place these elements above the player board divs, that way it’s easily visible when the game loads. ```html … <div class="above-game"> <p class="game-intro">Join the numbers and get to the <strong>2048 tile!</strong></p> <a class="restart-button">New Game</a> </div> <!-- Add these two divs --> <div class="message-container waiting-message" style="display: none;"> Waiting for Player 2... </div> <div class="message-container countdown-message" style="display: none;"> Game starting in <span class="countdown-number"></span>... </div> <div id="player-one"> <div class="game-container"> <div class="game-message"> ... ``` Additionally in `public/style/main.css`, we can define some styling so that our messages are easily visible. ```css @import url(fonts/clear-sans.css); /* Styling to make the message containers look nice */ .message-container { background: #8e7967; color: white; text-align: center; padding: 1em; margin: 1em; font-weight: bold; font-size: 1.2em; } html, body { ... ``` Next we’ll want to define some helper methods to hide/display the messages, as well as display the correct time for the countdown. We should do this in `public/js/application.js`. You can simply define these methods at the top of the script. ```javascript function waitingPlayerTwo(show) { const messageContainer = document.querySelector('.waiting-message'); messageContainer.style.display = show ? 'block' : 'none'; } function countdownMessage(show, number) { const messageContainer = document.querySelector('.countdown-message'); const countdownNumber = document.querySelector('.countdown-number'); messageContainer.style.display = show ? 'block' : 'none'; countdownNumber.textContent = number; } ``` ## Kicking Off the Game Next we’ll want to define a method that actually kicks off the game. In this case, we’ll also have it do a countdown timer before starting the game. We can similarly just define this at the top of `public/js/application.js` ```javascript function startGame() { let seconds = 4; // Number of seconds + 1 to wait // Start a countdown timer const intervalId = setInterval(function() { // Subtract the number of seconds left and update UI seconds--; countdownMessage(true, seconds); if (seconds == 0) { // It's time to start the game! clearInterval(intervalId); // Stop the countdown countdownMessage(false, 0); // Hide the countdown message if (remoteGame != null && localGame != null) { localGame.restart(); // A game already exists, lets just reset the game. } else { // Start the game managers remoteGame.setup(); localGame.setup(); } } }, 1000); } ``` The function may seem a bit complicated at first but breaks down to be fairly simple. We first start with defining a function that is called every second via: ```javascript const intervalId = setInterval(function() { ... }, 1000); ``` Next inside the function, we’ll want to subtract from the number of seconds we want to count down from, and then update the UI using our `countdownMessage` functions. ```javascript seconds--; countdownMessage(true, seconds); ``` When the countdown has hit 0 seconds, we’ll want to stop the function from executing again via `clearInterval`, hide the countdown message, and then start the games. Next we’ll want to sync up the waiting and countdown message with when users connect. In our `requestAnimationFrame` callback where we’re currently creating the game managers, we can listen to socket events to determine when we’ve connected, and when the opponent has connected to the server. We can put this at the bottom of the `requestAnimationFrame` callback. ```javascript window.requestAnimationFrame(function () { ... localGame = new GameManager(socket, false, 4, KeyboardInputManager, HTMLActuator, LocalStorageManager); // Add this socket lisetner socket.on('player-number', function (playerNumber) { if (playerNumber == 1) { waitingPlayerTwo(true); // Show waiting message // On 2nd player connect, start the game socket.on('player-connect', function() { waitingPlayerTwo(false); // Hide waiting message startGame(); }); } else { // Immediately start the game if we're player two startGame(); } }); ``` If we’re player 1, we’ll display that we’re now waiting for player two to the user. When we’ve detected that another player has connected, we’ll hide the waiting message and start the game countdown. If we’re player two, we’ll just immediately start the game countdown after we’ve connected to the server. Now there only leaves one last thing to do, is to not start the game immediately when we create a new GameManager. In our `public/js/game_manager.js`, we’ll simply remove `this.setup();` from the constructor. That way we won’t call it at instantiation, but instead only when we explicitly call it at `startGame` that we defined in application.js. Our constructor should look like this: ```javascript class GameManager { constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) { ... // Add this new if statement if (this.remotePlayer) { this.socket.on('move', this.handleRemoteMove.bind(this)); } // No setup! } ``` If all has gone well, your project should look similar to [this repl](https://repl.it/@MikeShi42/competitive-2048-tutorial-final). # Improve The Game! This ends the basics of creating a multiplayer 2048 game! The [final demo](https://repl.it/@MikeShi42/competitive-2048-demo-final) version has a couple of tweaks that you can check out the source code to see how I’ve done it like: Side by Side Game Boards Opponent Won Message Eliminating Extraneous Buttons Set Game Goal (Instead of winning @ 2048, can be easier or harder) Game Full Message ## Even More! There’s space for even more improvement such as real-time chat using socket.io to chat with your opponent, a timer to time-cap the game, or mechanisms where your success impedes your opponent’s ability to succeed well (ex. frozen tiles). There’s a lot more creative ways to take the game that would be exciting to see! # Fin Let me know if any of the steps were confusing or unclear :) I'll do my best to help!
2
posted by MikeShi42 (95) 10 months ago
26
🌚🕶 How to Enable Repl.it Site-Wide Dark Theme 🕶🌚
# Repl.it Site-Wide Dark Theme Do you like not being blinded while browsing Repl.it? Well me neither! ![Repl talk on dark theme](https://storage.googleapis.com/replit/images/1557091294976_160fda0e32057fb2f3a93d971d4a4203.pn) *** First, you might not have the editor dark theme enabled, so make sure you enable that. 1. Click the settings button at the left of the editor screen. ![Settings Button](https://storage.googleapis.com/replit/images/1557091461609_7a585f76190494f3bc741389062781a0.pn) 2. Find the theme dropdown, and select *dark* ![theme dark](https://storage.googleapis.com/replit/images/1557091792258_8f89ba2a4630090419013d3220ddbd0d.pn) *** Now that you have the editor dark theme enabled, we will enable the site-wide dark theme. 1. Download Tampermonkey for [Chrome](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo) or [Firefox](https://addons.mozilla.org/en-US/firefox/addon/tampermonkey/) 2. Choose a theme from [the list of themes](https://www.darktheme.tk/themes) or [create your own](https://www.darktheme.tk/custom) 3. Click the `install` button. 4. Upvote and post a comment on this tutorial. 5. Profit!
20
posted by mat1 (2165) 1 month ago
24
Make your first Pygame 🎮
## Make games the easy way, and forget about the setup 😌 ![](https://tiresome-aunt.surge.sh/ezgif-9aa456d6-a2de-4d54-a2b3-6828c507544d.com-video-to-gif_(1).gif) [Demo + Code](https://repl.it/@jajoosam/paddleBasket) ⏯️ 👨‍💻 I've heard coding in python is quite delightful! And I agreed once I made my first python app that didn't just run on the terminal - a game made with [Pygame](https://www.pygame.org/). You'd usually have to spend a while getting set up, installing Pygame, dependencies and then have to spend time compiling an executable before sharing your game. But with [replit's new GFX system](https://repl.it/talk/announcements/Replit-GFX-Public-Beta-Build-Games-and-GUI-Apps/11545) - there's absolutely no need for that ✌️ This is a tutorial to get started with Pygame, and make a simple game within 30 minutes! ## 🛠️ Getting our environment running Head over to [repl.it](http://repl.it) and once you're logged in, hit `new repl → Pygame` to create the repl where we're going to be making our game. ![](https://tiresome-aunt.surge.sh/-7158aee6-09d3-41ef-a559-42f5cb010b22untitled) That's it 😉 ## 🎲 Understanding the game Before we start coding, let's understand what we're making 🛠️ Our game concept is pretty straightforward - there's a paddle - a simple rectangle that moves left or right in the screen, attempting to catch balls falling from the top of the screen. A higher score is more number of balls caught ⚾ ## 👨‍💻 Initializing pygame You can go right ahead and paste this code in your repl! ```python # adding libraries we're going to use import pygame from random import randint pygame.init() # initializing variables to account for the number of balls caught, and total dropped score = 0 total = 0 myfont = pygame.font.SysFont('monospace', 50) # creating a font to write the score in # Making dictionaries with settings for everything. display = { "width": 800, "height": 600 } paddle = { "width": 200, "height": 20, "x": 300, "y": 580, "velocity": 10 } ball = { "radius": 15, "y": 30, "x": randint(0, display["width"]), "velocity": 20 } # creating a window, and launching our game win = pygame.display.set_mode((display["width"], display["height"])) # 800 width, 600 height ``` I've added comments to explain what each line does 😄 Make sure to paste in the dictionaries too, they'll be super useful soon! ## 👾 The paddle Our paddle is going to be just a little rectangle that moves when we hit the arrow keys. Before we can start making it, we need to create the main loop. Pygame will run the code inside this loop continuously, to update the screen based on inputs. Paste all this in! ```python while True: pygame.time.delay(100) win.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: break keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: paddle["x"] -= paddle["velocity"] if keys[pygame.K_RIGHT]: paddle["x"] += paddle["velocity"] pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"])) pygame.display.update() ``` ​ ```python pygame.quit() ``` Don't worry, I'm not just going to leave you like that xD Let's break this up into smaller blocks to explain what everything does! Let's talk about everything inside the while loop, which will run forever - since `True` will always remain `True` 😮 ```python pygame.time.delay(100) win.fill((255, 255, 255)) ``` We're adding the delay so that the loop doesn't run too often, and there's some gap between each cycle - keeping our repl from crashing. `100` is delay in milliseconds, causing the loop to run 10 times a second. `win.fill()` takes a color in `RGB` as it's argument - and `255, 255, 255` represents white, filling our window with white before we draw anything onto it 🖌️ ```python for event in pygame.event.get(): if event.type == pygame.QUIT: break ``` This piece of code goes over all events that pygame gives us, and breaks the loop if Pygame has been quit. When the loop breaks, we go to the line which says `pygame.quit()`- you know what that does 😛 ```python keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: paddle["x"] -= paddle["velocity"] if keys[pygame.K_RIGHT]: paddle["x"] += paddle["velocity"] ``` To get this - lets first clear out our understanding about the coordinate grid - it doesn't start at the center in pygame! In fact, the top left corner is `0, 0` and `x` increases as you go right, while `y` increases as you move down. This block of code gets all currently pressed keys, and checks whether the left or right keys are pressed. If they are, it changes the `x` coordinates of the paddle - reducing if ⬅️ is pressed, and increasing if ➡️ is pressed by the velocity we set in the `paddle` dictionary. Try changing the `velocity` to see what happens 🤔 ```python pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"])) pygame.display.update() ``` This is where we actually draw our paddle to the screen - in the window called `win`, red in color (`255, 0, 0` RGB) - at `paddle[x]` on the x axis, and `paddle[y]` on the y axis. We've also set the width and height in the `paddle` dictionary, feel free to mess around with it! Finally, `pygame.display.update()` updates the entire screen with what we've drawn in this cycle of the loop! Try running the code, and hitting the left and right arrow keys! You should see a little rectangle moving around 👇 ![](https://tiresome-aunt.surge.sh/CleanShot_2019-03-13_at_19-ac9eb692-26e2-421e-b279-84978459c836.38.32.gif) ## ⚽ Generating falling circles Let's bring up the `ball` dictionary up again 👇 ```python ball = { "radius": 15, "y": 30, "x": randint(0, display["width"]), "velocity": 20 } ``` What does the `"x"` line do? We're selecting a random x co-ordinate between `0` and `display["width"]` (currently 800) - using the `randint` function we imported right at the start of our code. Add this inside your while loop, right before you draw the paddle to the screen: ```python ball["y"] += ball["velocity"] pygame.draw.circle(win, (0, 0, 255), (ball["x"], ball["y"]), ball["radius"]) ``` We're increasing the y co-ordinate of the ball by its `velocity` and drawing the ball again in every cycle of the loop. ## 🏆 When do you actually score a point, though? The final part of our game would be checking if the ball hits the paddle when it's at the bottom of the screen. Collision detection is going to be essential to most of the games you're going to make in the future, so let's go over it here! ```python if ball["y"] + ball["radius"] >= paddle["y"]: if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"]: score += 1 total += 1 ball["y"] = 0 ball["x"] = randint(0, display["width"]) ``` First up, we're learning if the ball has hit the level of the paddle - by checking if the ball's radius + it's position on the y axis is equal to the position of the paddle. ```python if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"] ``` With this long condition, we're testing if - The ball's position on the X axis is greater than the paddle's position on the X axis AND - The ball's position on the X axis is lesser than the sum of the paddle's position on the X axis and its width If this condition is true, it means that the ball has landed on the paddle, and we increase the score 🙌 Maybe this image helps a bit 🤞 ![](https://tiresome-aunt.surge.sh/-98fcc7ff-0ac4-4a09-8d46-2e06394d73b8untitled) After this, regardless of whether a point has beens scored or not, we add one to the total number of balls landed - and reset the ball's position, setting the ball's y co-ordinate to 0, and generate a random position for the X axis. Lastly, we're going to write the score on the screen 🏅 ```python textsurface = myfont.render("score: {0}/{1}".format(score, total), False, (0, 0, 0)) win.blit(textsurface, (10, 10)) ``` We create a new [surface](https://www.pygame.org/docs/ref/surface.html) where we write the text using python's [format](https://www.programiz.com/python-programming/methods/string/format) function, replacing `{0}` with the socre, and `{1}` with the total. We're writing this in black (`0, 0, 0` RGB). `win.blit(textsurface, (10, 10))` merges the text with the main window, at co-ordinates `10, 10`. And that's the game - the full thing 🤯 ## 🔮 Things to try - Changing the contents of the dictionary and seeing what happens ❓ - Make multiple balls fall at the same time 🔴 🔵 ⚫ - Make the paddle move up and down too 🚀 - Adding poison balls - the game stops when your paddle hits one 😵 Be sure to put down any questions or improvements down in the comments 💬 And here's all the code for you to go over again - I highly recommend going through this to help you understand the flow of the program, and the sequencing of everything if you were even a little confused by this guide 😅 https://repl.it/@jajoosam/paddleBasket
3
posted by jajoosam (525) 3 months ago
23
👾🎉 Announcing Python Play (beta) & a pong game tutorial
# [Python Play](https://github.com/replit/play) is the easiest way to get started coding games and graphics projects. @amasad and the repl.it team asked me to help them make an easy way for new programmers to start making games and graphics projects. As a result, we made [Python Play](https://github.com/replit/play), a code library for Python loosely based on [Scratch](https://scratch.mit.edu). For more information about Python Play, you can [read the documentation here](https://github.com/replit/play). This is a tutorial showing how to use Python Play to make a game. To follow along with the tutorial, you can go to **[this repl](https://repl.it/@glench/Blank-Python-Play-template)** and add code line-by-line. The game we'll be making is a pong game: ![screenshot](https://storage.googleapis.com/replit/images/1553634467413_16e2bdb28bc2c079db661594c57296e8.gi) ## How to make a pong game with Python Play To make this game, first we need a box. Copying and pasting the code below will put a box on the screen: ```python import play # this should always be the first line in your program box = play.new_box(color='black', x=0, y=0, width=30, height=120) play.start_program() # this should always be the last line in your program ``` After you've copied that code, click the "Run" button. You should see a tall black box in the middle of the screen. If you change any of the stuff after `new_box`, it will change what the box looks like and where it shows up on the screen. Change `x=0` to `x=100` and the box moves over to the right: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) ``` (Click the Run button after every code change you make. Also make sure you still have the `import play` and `play.start_program()` lines of code in your program.) Changing `x` changes the horizontal position and changing `y` changes the vertical position of the box. You can try playing with these numbers to see how they work. Don't forget you can do negative numbers i.e. `x=-100` (note the minus symbol in front). Okay cool, a box is on the screen and we can change where it is. But how do we get it to do stuff? Change your code to look like this: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) @play.when_key_pressed('up') async def do(key): box.y += 10 ``` Then try pressing the 'up' arrow on your keyboard. The box moves upward now! The code above is saying "when the up arrow key is pressed, add `10` to the box's `y` position". Adding to the box's `y` position moves the box up on the screen. Can you guess how we could get the box to move down when the down arrow key is pressed? Here's the full code for how you might do that: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 ``` (Remember that your program should still start with `import play` and end with `play.start_program()`.) So now the box moves up and down on the screen when we press the arrow keys. ### Adding a ball Now we need a ball. Add this line below the `new_box` line: ```python ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ``` Now there's a ball but it's not moving. To get it moving, here's the full code to put in your program: ```python ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 # make the ball move @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy ``` This makes the ball move by changing its `x` and `y` position (repeating forever) by the horizontal speed `dx` and the vertical speed `dy`. `ball.dx` and `ball.dy` are two variables we're making up to store the horizontal speed and vertical speed of the ball. The starting horizontal speed (`dx`) is 2 (to the right) and the vertical speed is -1 (down). But the ball doesn't bounce off the paddle, it just goes right through. To fix that, we have to detect when the ball is right next to the paddle and reverse its direction. Add this code to your program: ```python # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and (ball.top >= box.bottom) and (ball.bottom <= box.top) and (ball.left < box.left): ball.dx = -2 ``` Now the ball bounces off the paddle! The code above checks three conditions which are best shown visually: ![if-statement](https://storage.googleapis.com/replit/images/1553634499339_d4182f199889cace97d4b9282f77f84f.pn) If the ball is anywhere over the red line in the grey areas, then the condition written below it becomes `True`. If all three conditions are `True` at the same time, that means the ball hit the paddle and its speed should be reversed (-4) so it goes the other way. (`<=` means "less than or equal" and `>=` means "greater than or equal"). Here's the whole program at this point: ```python import play box = play.new_box(color='black', x=350, y=0, width=30, height=120) ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and (ball.top >= box.bottom) and (ball.bottom <= box.top) and (ball.left < box.left): ball.dx = -2 play.start_program() ``` ### Adding a computer player There should be another player. Let's create another box! Add this code near where you put the code starting with `box = play.new_box`: ```python other_box = play.new_box(color='black', x=-350, y=0, width=30, height=120) other_box.dy = 3 ``` We're making the box have a vertical speed of 2 when it moves, but we haven't made it move yet. To make the computer player follow the ball, we can add this code to our program: ```python # make the computer player follow the ball @play.repeat_forever async def do(): if ball.x < 0 and abs(ball.y-other_box.y) > other_box.dy: if other_box.y < ball.y: other_box.y += other_box.dy elif other_box.y > ball.y: other_box.y -= other_box.dy ``` Now when the ball is on the left side of the screen, the computer player will move toward the ball! We add to the box's `y` if the box is below the ball, otherwise we subtract from the box's `y` if it's above the ball. But oops, the ball doesn't bounce off the computer player's paddle (`other_box`). Let's make it do that by adding this code: ```python # make the ball bounce off the computer player's paddle @play.repeat_forever async def do(): if (ball.left <= other_box.right) and (ball.top >= other_box.bottom) and (ball.bottom <= other_box.top) and (ball.right > other_box.right): other_box.dy = play.random_number(1, 4) ball.dx = 2 ``` This code works just like the collision code from above but in reverse for the left paddle. Also when the ball hits the paddle we change the paddle's speed to a random number between 1 and 4 so the paddle will move either slower or faster. But oops again, now if we get the ball to bounce off the computer player's paddle, it doesn't bounce off the walls. To make the ball bounce off the walls, we add this code that checks that the ball is lower than the top of the screen and higher than the bottom of the screen: ```python # make ball bounce off bottom and top walls @play.repeat_forever async def do(): if ball.bottom <= play.screen.bottom: ball.dy = 1 elif ball.top >= play.screen.top: ball.dy = -1 ``` If the ball hits either the top or the bottom of the screen, the code above will reverse its speed so it bounces. And that's it! A simple pong game in about 50 lines of code! ## The final code Here's all the code in the tutorial in one place: ```python import play box = play.new_box(color='black', x=350, y=0, width=30, height=120) other_box = play.new_box(color='black', x=-350, y=0, width=30, height=120) other_box.dy = 3 ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 # make the ball move @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and (ball.top >= box.bottom) and (ball.bottom <= box.top) and (ball.left < box.left): ball.dx = -2 # make the computer player follow the ball @play.repeat_forever async def do(): if ball.x < 0 and abs(ball.y-other_box.y) > other_box.dy: if other_box.y < ball.y: other_box.y += other_box.dy elif other_box.y > ball.y: other_box.y -= other_box.dy # make the ball bounce off the computer player's paddle @play.repeat_forever async def do(): if (ball.left <= other_box.right) and (ball.top >= other_box.bottom) and (ball.bottom <= other_box.top) and (ball.right > other_box.right): other_box.dy = play.random_number(1, 4) ball.dx = 2 # make ball bounce off bottom and top walls @play.repeat_forever async def do(): if ball.bottom <= play.screen.bottom: ball.dy = 1 elif ball.top >= play.screen.top: ball.dy = -1 play.start_program() ``` And here's a [link to a repl with the code above](https://repl.it/@glench/Python-Play-pong-game-demo). ## More Challenges This game is pretty simple. Can you think of other things to add to make it more fun? Here are some suggestions for things to try: - Can you make the paddles change colors when the ball hits them? - How would you keep track of and show scores in the game? (Hint: look up the `play.new_text()` function.) - Did you find any glitches in the game? How would you try to fix those glitches? - How would you make the ball change speed differently depending on where it hits on the paddle? - Could you add multiple balls to the game? What else would you add to make the game more fun? # Python Play Thanks for reading this tutorial! If you make anything with Python Play, please post it in the comments! Python Play is currently in beta, which means some things may not work quite right. If you find a problem (usually called a "bug"), please send us a link to the repl where you found that bug. To find out more about all the things you can do with Python Play, [read the documentation here](https://github.com/replit/play)! Look for more Python Play features coming soon! Try it out and let us know what you think!
10
posted by glench (31) 3 months ago
Python
Python
23
How to Make a Python Email Bot
# How to Make a Python Email Bot In this tutorial we will be learning how to make a python program that can read emails and respond based on the content. Once you have the fundamentals of the program, you can write your own functions to do anything. I will provide a 2 examples: a weather bot and a remote commands/shell script executor (useful on your own machine rather than repl.it). Sorry for the tutorial being so long. If you just want to get to the bot, skip the "IMAP in Python Basics" section and the "SMTP in Python Basics" sections. ### What is IMAP? IMAP stands for Internet Mail Access Protocol. Almost all email clients, even web based ones, login to your email providers email server using IMAP. With IMAP there are folders to organize emails and emails stay on the server unless explicitly deleted. ### What is SMTP? SMTP stands for Simple Mail Transfer Protocol. It is the standard protocol used for sending emails across the internet. SMTP is used to both send and receive emails, but we will only be sending. ## IMAP in Python Basics To implement IMAP we will be using the third-party module ```imapclient``` (docs [here](https://imapclient.readthedocs.io/en/2.1.0/)). ### Connecting to the Server Most servers can be found with a simple google search of "*your provider* imap settings" or by contacting you email provider, but here are the most common ones: **Gmail:** imap.gmail.com **IMPORTANT:** Gmail users may only check for emails every 10 minutes, or 600 seconds, so make sure to change your config! See this articlefor more information: https://support.google.com/mail/answer/7126229?hl=en **Outlook.com/Hotmail.com:** imap-mail.outlook.com **Yahoo.com:** imap.mail.yahoo.com **AT&T:** imap.mail.att.net **Comcast:** imap.comcast.net **Verizon:** incoming.verizon.net Now you can connect to the server, the ```imapclient``` module makes this easy. All you have to do is initialize an ```imapclient.IMAPClient()``` object using the server name, and it will connect to it on the default IMAP port using SSL. For example: ```python import imapclient i = imapclient.IMAPClient('imap-mail.outlook.com') # i is easy to type ``` ### Logging in Logging in is very simple. ```python i.login('[email protected]', 'mySuperSecretPassw0rd') ``` The ```i.login()``` function is pretty self-explanatory, it logs in using the email and password provided. ### Selecting a folder Next we need to select a folder. ```i.list_folders()``` shows the available folders. You should choose the one you want, usually "INBOX". ```python i.select_folder('INBOX') ``` You can also, for debugging, pass in the keyword argument ```readonly=True``` to select_folder() to make the server not mark the messages you fetch as read. ### Search for messages Now we can search for a message. There are many search criteria, here is [a full list](https://gist.github.com/martinrusev/6121028). Some of the most common ones are ```'ALL'``` which selects all message, ```'UNSEEN'``` which gets all unread messages. The search flags behave differently which each email server, so you should first experiment with them in the shell. You can search through the messages in the folder using ```i.search(['criteria'])```. To get a unread messages, use the following code: ```python i.search(['UNSEEN']) ``` This will not return the emails themselves, but a list of unique IDs or UIDs, for example ```[40032, 40033, 40034]``` which we are about to use. You can also use a special method if you are using Gmail, ```i.gmail_search()``` which behaves like the search box in Gmail. #### Size Limits If your search matches lots of messages, you can get an ```imaplib.erorr: got more than 10000 bytes```. This can be fixed by the following code: ```python import imaplib imaplib._MAXLINE = 1000000 ``` This sets the limit to 10,000,000 bytes instead of 10,000. ### Fetching emails When you fetch an email, you download it from the server. Unless you are using ```readonly=True```, when you fetch an email it will mark it as read. You fetch an email like this: ```python rawmsgs = i.fetch(uids, ['BODY[]']) # uids is the uids returned by search() ``` The object returned by fetch is complicated and hard to parse, so we will be using a second third-party module, ```pyzmail``` to parse them. ** Important: If you are installing pyzmail using pip on python 3.6 or above, you need to install ```pyzmail36``` instead of ```pymail``` or you will get an error in pip. ** This is how you parse a message with pyzmail: ```python import pyzmail msg = pyzmail.PyzMessage.factory(rawmsgs[40041]['BODY[]']) # Be sure to change the uid number ``` Using this object you can get a lot of information on the message. ```python msg.get_subject() msg.get_addresses('from') msg.get_addresses('to') msg.get_addresses('cc') ``` Sample Output: ``` Thanks! [('Alice Doe', '[email protected]')] [('Bob Smith', '[email protected]')] [] ``` These methods get the subject and addresses the message was sent to. ### Reading Messages ```python msg.text_part != None msg.text_part.get_payload().decode(msg.text_part.charset) msg.html_part != None msg.html_part.get_payload().decode(msg.html_part.charset) ``` Sample Output: ``` True 'Thanks for buying lunch yesterday. \r\n\r\n-Alice\r\n' True '<div style="font-family: courier;">Thanks for buying lunch yesterday. <br><br>-Alice</div>' ``` Email messages can have 2 parts: a text part and an HTML part. In pyzmail, they will either be ```None``` if it doesn't exist or if it does exist it will have a ```get_payload()``` method which returns ```bytes``` which can be decoded using ```.decode()``` with the charset stored in either ```msg.text_part.charset``` or ```msg.html_part.charset```. The text part is plaintext, the HTML part is HTML to be rendered for the user. ## SMTP in python basics SMTP is similar to IMAP, but doesn't have as many commands. To implement SMTP, we will be using the python built in library, ```smtplib```. ### Connecting to the server You should first find your providers SMTP settings by finding them in the list below, searching *your provider* smtp settings, or by contacting you email provider. **Gmail:** imap.gmail.com **IMPORTANT:** Gmail users may only check for emails every 10 minutes, or 600 seconds, so make sure to change your config! See this articlefor more information: https://support.google.com/mail/answer/7126229?hl=en **Outlook.com/Hotmail.com:** imap-mail.outlook.com **Yahoo.com:** imap.mail.yahoo.com **AT&T:** imap.mail.att.net **Comcast:** imap.comcast.net **Verizon:** incoming.verizon.net Once you have your settings, you can connect to the server by initializing a new ```smtplib.SMTP()``` object and starting TLS: ```python s = smtplib.SMTP('smtp.example.com', 587) s.starttls() s.ehlo() ``` ### Troubleshooting If you get an error while connecting or if your email provider is listed above as *port 465* then your email provider may not support TLS on port 587. In this case, you should connect using SSL to port 465 like this: ``` s = smtplib.SMTP_SSL('smtp.example.com', 465) s.ehlo() ``` ### Logging in Logging in is similar to IMAP, you call the ```login()``` function of your SMTP connection, using your email and password: **Be careful about leaving passwords in your code!** ``` s.login('[email protected]', 'mySuperSecretPassw0rd') ``` ### Sending emails To send emails, I have found that the ```sendmail()``` function doesn't really work as it can mess with email headers, instead we should use the python built-in module ```email```'s ```email.message.EmailMessage()``` class which makes settings the headers really easy and has many advanced capabilities which are listed in [the docs](https://docs.python.org/3/library/email.message.html#email.message.EmailMessage). Here is an example of how to send a text message: ```python text = """Dear Alice, You are welcome. Think nothing of it! -Bob """ msg = email.message.EmailMessage() msg['from'] = '[email protected]' msg["to"] = '[email protected]' msg["Subject"] = "Re: Thanks! " msg.set_content(text) res = s.send_message(msg) ``` In most email providers, though not required, prefacing the subject with Re: denotes a reply. In this example, Re: Thanks! would show up in the same thread as the original Thanks! message in both email clients. To return value of the ```send_message()``` function is a dictionary of the addresses to which sending failed. If successful, it should return ```{}```. ## Putting it all together: making the bot Using our knowledge, we are going to write the bot. First thing we need to do is store the configuration information. For repl.it, we will use ```input()``` but on your own computer you can hard-code values (not passwords! ). ### Using a configuration file Add a new file in repl.it called ```config.py``` and add the following: ```python import getpass radr = input("Adresses to log in to") # address to check and send from imapserver = input("IMAP server domain: ") # imap server for account smtpserver = input("SMTP server domain: ") # smtp server for account smtpserverport = input("SMTP Server port [587]: ") # smtp server port for starttls if not smtpserverport or smtpserverport == "": smtpserverport = 587 pwd = getpass.getpass("Account password: ") # password for account encoded with base64.b64encode sadr = input("Trusted addresses to receive from: ") # address to receive commands from check_freq = 5 ``` Here we set the config values to be used by the main program. For security, we will set a trusted email that is the only one that commands will be accepted from. This is so that no random people can email us commands. ### Initializing the IMAP connection ```python from config import * def imap_init(): """ Initialize IMAP connection """ print("Initializing IMAP... ", end='') global i i = imapclient.IMAPClient(imapserver) c = i.login(radr, pwd) i.select_folder("INBOX") print("Done. ") ``` Here we initialize the imap connection by import our config file (using ```import *``` is usually a bad idea because you don't know where things came from but we are just importing variables so it is okay). We also define i using ```global i``` so that it is available to the rest of our program. We also login to the server and select the "INBOX" folder. ### Initializing the SMTP connection ```python def smtp_init(): """ Initialize SMTP connection """ print("Initializing SMTP...") global s s = smtplib.SMTP(smtpserver, smtpserverport) c = s.starttls()[0] # The returned status code if c is not 220: raise Exception('Starting tls failed: ' + str(c)) c = s.login(radr, pwd)[0] if c is not 235: raise Exception('SMTP login failed: ' + str(c)) print("Done. ") ``` In this block, we initialize the SMTP connection. We use the same ```global``` technique as with IMAP and connect to the SMTP server and login, but we also check the status codes returned by the server to make sure everything was successful (we can't do this with IMAP). ### Getting unread emails The next step is getting any unread emails. ```python def get_unread(): """ Fetch unread emails """ uids = i.search(['UNSEEN']) if not uids: return None else: print("Found %s unreads" % len(uids)) return i.fetch(uids, ['BODY[]', 'FLAGS']) ``` Here we define a function to get unread emails. This function searches the IMAP object for any unread emails. It returns ```None``` if it didn't find any, or if it did, it fetches them from the server and returns them. ### Defining commands For our bot to work, we have to define some actions for it. To do this, we will define functions in ```config.py``` and add them to a commands ```dict``` which will map the command names to the functions. The functions will take 1 argument: the message split by lines. For now, we will make a command that will return "Hello, World! " every time no matter the message content: ```python def hello_world(lines): return "Hello, World! " commands = {"hello" : hello_world} ``` ### Analyzing the message Now we will analyze the message and determine what to do about it. ```python def analyze_msg(raws, a): """ Analyze message. Determine if sender and command are valid. Return values: None: Sender is invalid or no text part False: Invalid command Otherwise: Array: message split by lines :type raws: dict """ print("Analyzing message with uid " + str(a)) msg = pm.factory(raws[a][b'BODY[]']) frm = msg.get_addresses('from') if frm[0][1] != sadr: print("Unread is from %s <%s> skipping" % (frm[0][0], frm[0][1])) return None global subject if not subject.startswith("Re"): subject = "Re: " + msg.get_subject() print("subject is", subject) if msg.text_part is None: print("No text part, cannot parse") return None text = msg.text_part.get_payload().decode(msg.text_part.charset) cmds = text.replace('\r', '').split('\n') # Remove any \r and split on \n if cmds[0] not in commands: print("Command %s is not in commands" % cmds[0]) return False else: return cmds ``` Let's break this down. First we initialize the message object with the data we are given. Next, we make sure it is from our trusted address. Next we set the subject to start with Re: so that it shows up as a reply in the email thread. Next, we make sure we have a ```text_part``` to parse and split it by lines. We check that the requested command is a valid command, and if so, return the line of the message. ### Defining a mail function Defining a mail function will be useful so that we can see in the logs what was mailed to the user, and it will make the sending mail process as easy as passing the function the mail text. ```python def mail(text): """ Print an email to console, then send it """ print("This email will be sent: ") print(text) msg = email.message.EmailMessage() global subject msg["from"] = radr msg["to"] = sadr msg["Subject"] = subject msg.set_content(text) res = s.send_message(msg) print("Sent, res is", res) ``` ### Writing the event loop We will write the loop our bot goes through as it waits for a message to process. We want our bot to run until we interrupt it, so we will put it in an infinite loop. ```python imap_init() smtp_init() while True: # Main loop try: print() # Blank line for clarity msgs = get_unread() while msgs is None: time.sleep(check_freq) msgs = get_unread() for a in msgs.keys(): if type(a) is not int: continue cmds = analyze_msg(msgs, a) if cmds is None: continue elif cmds is False: # Invalid Command t = "The command is invalid. The commands are: \n" for l in commands.keys(): t = t + str(l) + "\n" mail(t) continue else: print("Command received: \n%s" % cmds) r = commands[cmds[0]](cmds) mail(str(r)) print("Command successfully completed! ") except KeyboardInterrupt: i.logout() s.quit() break except OSError: imap_init() continue except smtplib.SMTPServerDisconnected: smtp_init() continue finally: i.logout() s.quit() ``` This is a long code block, so let's break it down. First we check for unread messages and if there are none, then we wil get into a loop waiting for one. Next we loop over each of the unreads we have retrieved and analyze them. (there are a lot of loops in this portion). We then check the value returned by ```analyze_message()``` and if it was ```False``` meaning an invalid comand we send the user a helpful message detailing the available comands. If it was ```None``` meaning it is not from the trusted sender or has an invalid ```text_part``` we will skip it and continue the loop. Here we check the return value from ```analyze_msg()```. If it is None (meaning it is not from the trusted sender or doesn't have a text part) we skip it and continue to the next message. If it is False, meaning it is an invalid command, we helpfully send the user a message reminding them of the available commands. Otherwise, we assume we got the text to fun so we run the corresponding command. When it finishes, we send back the result and print a message to the console. The bot is complete! ### Testing the bot Now we can run the bot and test it! If you run the bot and send a message to the email it is connected to with the first line being ```hello``` then it should reply back "Hello, World! ". If you get any error, make sure you followed each step and if you think the error is on my part, let me know in the comments and I will fix it. ## Example commands: Weather Checker Here I will provide you with one of two example command: a program that gets the weather using the openweathermap.org API for your local area and emails it back to you! ### Setup Before you can use this program, you need to find a couple of values. To find your city's id, search for it at https://openweathermap.org/find and click on it in the results. The city id is the string of numbers at the end of the URL. To get your API key, follow the steps here: https://openweathermap.org/appid. This requires you to create a free account and wait one hour for you API key to be activated. Keep in mind the limit for calls with a free account is one per 10 minutes, so don't check too often or your account could be suspended. Now that you have your values, replace them in the code below. Also, we have one third-party dependency: the ```requests``` module. Don't forget to install it if you haven't already. ### The code ```python import requests from json.decoder import JSONDecodeError def weather(lines): city_id = str(5391959) url = "https://api.openweathermap.org/data/2.5/forecast?id=" api_key = "your api key here" res = requests.get(url + city_id + "&APPID=" + api_key + "&mode=json") if res.status_code != 200: return "Oops, code was " + code try: j = res.json() except JSONDecodeError: return "JSON decode error: \n" + res.text try: main = j["city"]["list"][0]["weather"][0]["main"] description = j["city"]["list"][0]["weather"][0]["description"] except Exception as e: return str(e) + "\n" + r.text return "The weather is: \n%s: %s" % (main, description) ``` Let's break this down. First we define our config values and get the API page using them. Then, we make sure the request was successful (if the status code was 200) and send a message back if it wasn't. Next we attempt to decode the JSON returned by the API and send back if we can't. Finally, we get the weather and the description of it and catch any error that occurs from it (usually the key not existing because of an error with the call) and send back the error and full content of the request so that we can diagnose the error. Finally, if all was successful, we return the weather to the user! ## Example command: Command and Shell Script executor This command won't be useful on repl.it, but rather on your own server. This is really two commands: one that will run a single command, and one that will write the message contents to a file on disk and execute it. (useful if you want to run commands in the same working directory or with variables because if you only run one command at a time, the shell will be reset each time). ### The code: command executor ```python import subprocess as sub def exec_cmd(cmds): param = cmds[2] """exec_cmd: executes a command with subprocess """ try: p = sub.run(param, shell=True, timeout=20, stdout=sub.PIPE, stderr=sub.PIPE) except sub.TimeoutExpired: return "Command timed out. " return '''Command exited with code %s Stdout: %s Stderr: %s ''' % (p.returncode, p.stdout.decode(), p.stderr.decode()) ``` This command isn't super complicated. We take the command to be executed as the second line and run it using ```subprocess``` with a timeout of 20. If the timeout expires, we inform the user. Otherwise, we send the return code, STDOUT, and STDERR. ### The code: shell script executor ```python def runscript(lines): """ Writes input to disk and executes it. Returns any errors. IMPORTANT: Before running, make sure file 'script' exists and is executable. """ try: f = open("script", "w") count = 0 for i in lines: if count is 0 or i is 1: count = count + 1 continue f.write(i + "\n") count = count + 1 f.close() p = sub.run("./script", shell=True, timeout=timeout, stdout=sub.PIPE, stderr=sub.PIPE) r = """Script finished! Return code: %s Stdout: %s Stderr: %s """ % (p.returncode, p.stdout.decode(), p.stderr.decode()) except Exception as e: return "Error: \n" + str(e) return r ``` This code is extremely similar to the single command runner code, except for it loops through the lines for the message (ignoring lines 1 and 2) and writes them to a file named ```script``` which, as mentioned in the docstring, should exist and be executable before this command runs. ### Adding the commands to the bot To add these commands to the bot, and to define you own, paste the functions into ```emailcmd_config.py``` and update the the ```commands``` dictionary at the bottom by putting the key as the alias for the command and the value as the function object. ``` commands = {"weather":weather, "exec":exec_cmd, "script":runscript} ```
8
posted by Scoder12 (314) 8 months ago
Python (with Turtle)
Python (with Turtle)
23
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**
11
posted by IEATPYTHON (311) 8 months ago
22
How to make Rest Api in Python
## Introduction In today's lesson, we will learn how to build basic `Rest Api` in `Python` and `Flask`. We will specifically focus on two different way of creating apis, both will be using flask. List of two ways. 1. using flask 2. using flask extension called `flask restful` In this Lesson we are going to use `flask restful` to make our final api. But I'm also going to show to how to create one in `flask > `Note!` using flask is not the most official way of creating api. Flask is not efficient, code will look bad and have difficulty managing large files. > `flask restful` flask extension restful is the best way of creating api. Because it handlea big files wasily. Very easy to work with And it was created special for making rest apis. > I recommend you should use `flask restful` >`Here what our final api will look like` ![Api final Result](https://cdn.discordapp.com/attachments/485343377983012864/518852699572273182/restapi_final.gif) It will generate random content from a category and print it out in json format ## What is REST? Representational State Transfer (REST) is a software architectural style that defines a set of constraints to be used for creating web services. Web services that conform to the REST architectural style, termed RESTful web services, provide interoperability between computer systems on the Internet. RESTful web services allow the requesting systems to access and manipulate textual representations of web resources by using a uniform and predefined set of stateless operations. Other kinds of web services, such as SOAP web services, expose their own arbitrary sets of operations. In a RESTful web service, requests made to a resource's URI will elicit a response with a payload formatted in either HTML, XML, JSON, or some other format. For more info [click here](https://en.wikipedia.org/wiki/Representational_state_transfer) > **We will only work with json format** ## Requirements - Basic Python knowledge - Flask - Flask-Restful - Jsonify - json ## Installation Inside your repl, creating an empty file called `requirements.txt`. Once you have to empty txt file ready, copy and paste this **Flask==1.0.2** to your **requirements.txt** to install flask. ![Installation Successful](https://cdn.discordapp.com/attachments/487306993288347649/518847564968361984/unknown.png) If this started to happen, that mean flask have been install, and if not, something is wrong and should re-copy and paste `Flask==1.0.2` To install flask-restful, repeat the same procedure but use this line `Flask-RESTful==0.3.6` ## Creating web server We'll need to create basic web server. We need web server to run our code on [repl.it](https://repl.it/repls) here the basic code for creating basic web server ```python from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return "I'm alive" def run(): app.run(host='0.0.0.0',port=8080) t = Thread(target=run) t.start() ``` >I'm not going to explain this code, as I'm bad when it come to server stuff. But up there we just created a simple server. if you run this code this screen is going to pop up on top right hand right with this text `i'm alive`. Now we have successfully created a web server. ## Rest REST have 4 methods: - GET - PUT - POST - DELETE In this tutorial, we ony going to work with `GET` method. ## Creating api first we need to import another flask extension `jsonify`. ```python from flask import jsonify ``` >we need jsonify to convert data in json and send it out to our server. >Important Note:- we're going only going to work with json data, because json can be used in almost every modern language. ```python from flask import Flask, jsonify from threading import Thread app = Flask('') #make sure you code is between this code t = Thread(target=run) t.start() ``` here's a example of **GET** methods ```python from flask import Flask, jsonify from threading import Thread app = Flask('') @app.route('/') def home(): return "I'm alive" @app.route('/api/add', methods=['GET']) def add(): return jsonify({"2 + 2": 2 + 2}) def run(): app.run(host='0.0.0.0',port=7000) t = Thread(target=run) t.start() ``` ```python @app.route('/api/add', methods=['GET']) ``` **/api/add** is our api endpoint. you can name it what ever you want, im just gonna called it that. we need an endpoint to get to make requests to content, without any endpoint it will give you an error or simply return you home page if available. You also noticed that we in our **@app.route**. we have **methods**. We use methods to tell what kind of `rest option`, we are using. In this case we are `GET`. **ENDPOINT**= your web server url + your app route so my url is `https://rest-api-python.badvillain01.repl.co` + route `/api/add` our endpoint is `https://rest-api-python.badvillain01.repl.co/api/add` > **Note**:- your url name will be different than mine. so put your url name and route together. If you run my example you will get this result. `{"2 + 2":4}` > I recommend running my example first and once you have hold of it, then run you're owns. Now in this example we will take `user input` and convert this to json data. I'm going to use to previous example but add user input. So user will put any number and it will double user input. ```python @app.route('/api/add/<int:num>', methods=['GET']) def add(num): return jsonify({f"{num} + {num}" : num + num}) ``` You may have noticed that our in route we have this `<int:num>`. This is how to take input. `int` is specify what type of content is it. And `num` is the name of variable we will storing our input. Once we have our input. Then we are going to use `jsonify` to convert data into json format and print it out on server. If you run this code now and endpoint `/api/add/<any num you want>` i'll be using 23, json data should look something like that. ```py {"23 + 23" = 46} ``` Now he's another example that takes string as input ```py @app.route('/api/name/<string:name>', methods=['GET']) def get_name(name): return jsonify({"Your name": name}) ``` we bascially did same thing, just change our variable type to string. and if we run this example result show look like this ```json {"Your name": "bad"} ``` _That all i have for flask. If you wanna continued with flask, **Good Luck**, but i'll suggest you checkout `flask-restful`_ # Getting ready for flask-restful Api So, the api i'm creating have two main categories, `facts` and `quote`. And then inside the folder, there are four `json` files, that contain some sort of json content. _I hope this made any sense to you. If not, then i'm sorry_ ![v](https://cdn.discordapp.com/attachments/485343377983012864/518870277812256771/unknown.png) # flask-restful first we need to import two extension from `flask-restful`, We need `Resource`, and `Api`. ```py from flask_restful import Resource, Api ``` Here a simple example of **flask-restful** ```py from flask import Flask, jsonify from threading import Thread from flask_restful import Resource, Api app = Flask('') api = Api(app) class Test(Resource): def get(self): return "Example with Flask-Restful" #creating api endpoint api.add_resource(Test, '/api/restful') def run(): app.run(host='0.0.0.0',port=7210) t = Thread(target=run) t.start() ``` If you compare this with **flask**. You can clearly see this is more readable, official and best. #### How flask-restful works first we need to build `api` on top of `app`. ```py app = Flask('') api = Api(app) ``` We just creating `api`. Now we dont need `app`. And we are going to use `api` to add new content. ```py class Test(Resource): def get(self): return "Example with Flask-Restful" ``` > In `flask-restful`, all content need to be in class with `Resource` as parameters > **Methods** are a little different. You don't assign Methods in route endpoint, instead you add methods directly to class. `def get(self):` or `def post(self)` > Self: becuase we are using `def` inside class, so we need to add `self` as first parameter. To create `endpoint` in flask-restful, it's pretty easy. `api.add_resource(<your class name>, <your endpoint>)` For this example `api.add_resource(Test, '/api/restful')` If you run this now. You should get this `"Example with Flask-Restful"` **NOTE** ```py def get(self): return "Example with Flask-Restful" ``` As you see, we didn't use `jsonify`. **WHY**. Becuase the content we're returning in not `json`. So to return `json` data. Here's an example ```py def get(self): return jsonify({"Type": "flask-restful"}) ``` Output should be `{"Type":"flask-restful"}` ## Creating final Api Becuase i'm gonna be selecting random from json fromat, so i need to import `random` and also need to import `json` ```py import random import json ``` Now we are going to create a class called `Facts`. This class will return a random facts. ```py def get_facts(fact_type): if fact_type == "random": file_address = 'Facts/random.json' elif fact_type == "technology": file_address = 'Facts/technology.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts'])) return fact class Facts(Resource): def get(self, fact_type): return get_facts(fact_type) api.add_resource(Facts, '/api/facts/<string:fact_type>') ``` So what i did that, instead of adding everything to my `Facts` class, i created a new def, outside of class. Now everythime, I'm calling Facts endpoint. It's sending requests back to `get_facts()` and return the data to `def get()`. And then this whole return the data to our server. > Creating new separate data will make your code more readable. you may wonder what this for ```py def get_facts(fact_type): if fact_type == "random": file_address = 'Facts/random.json' elif fact_type == "technology": file_address = 'Facts/technology.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts'])) return fact ``` > **fact_type** is user input. So i only want user to choose from my inputs, so im using `if` statement to check user input. If user input is equal to one of my inputs, I'm creating a new variable called `file_address`. This will contain file address i want to open. ```py with open(file_address, 'r') as factfile: data = json.load(factfile) fact = random.choice(list(data['Facts'])) ``` now once `if else` are done. We need to open the file and select random items from it. Remember, we are storing file address in `file_address`. We are going to called this file `factfile` Once we open the file, we need to load all content to `json` file. `data = json.load(factfile)` and now open we have all content in json file, we need to random select one. `fact = random.choice(list(data['Facts']))` > data:- name of variable which contain our json content > data['Facts]: `Facts` is what we want from our json file. It will randomly select one thing from `Facts` and return to `def get_fact` and this will return everything to `class Facts` and this will return it to our server. Now if you run your code, the output should look like this ![Facts Results](https://cdn.discordapp.com/attachments/485343377983012864/518911100968763392/ezgifcomvideocutter.gif) Now we are going to do the same thing with `Quotes`. We'll create a class and remember to give `Resource` parameter to class. ```py def get_quotes(quote_type): if quote_type == "motivation": file_address = 'Quotes/motivation.json' elif quote_type == "funny": file_address = 'Quotes/funny.json' else: file_address = 'errormsg.json' with open(file_address, 'r') as quotefile: data = json.load(quotefile) quote = random.choice(list(data['Quotes'])) return quote class Quotes(Resource): def get(self, quote_type): return get_quotes(quote_type) api.add_resource(Quotes, '/api/quotes/<string:quote_type>') ``` So we are just doing the same thing we did previously. **Congrats**, you have successfully created your first rest api. >**I hope you learned something today** >**I know it's bad but i try my best to make a great tutorial** _If you have any question dm me on discord, ask in **repl.it official discord server** or comment below_ > If you see any error or mistake. Please notify me. > **Important Note**:- your repl web server won't stay up 24/7. I will die after 60 min. So i suggest using free service `UptimeRobot`. If you never used `UptimeRobot`, then read [this tutorial for help](https://repl.it/talk/learn/How-to-use-and-setup-UptimeRobot/9003) This api was just for tutorial. I'm not working on it anymore. [Please check out of my main api.](https://gold-miners-api.badvillain01.repl.co/docs.html) ### Source code https://repl.it/@badvillain01/rest-api-python
13
posted by badvillain01 (60) 7 months ago
Ruby
Ruby
22
Learn the Basics of Ruby! Interactive Program for Anyone New to Ruby :)
## If you're interested in learning the Ruby programming language, this program might help you out with the basics: **printing/putting, delaying code (sleep), variables, some math/methods (to int and to string), arrays, calling random integers, getting user input, loops, and if/elsif/else statements.** ## Other features: * *Interactivity!* The program asks the user for code after teaching topics to check if the user understands. * *Tips & help!* During any question, the user can input "help" or "h" instead of code in order to receive tips with the specific coding problem. * *The program itself...is coded in Ruby!* So if the user wants to see some Ruby in action, they can check out the IDE. Plus, I recently added comments within the IDE that are meant for the user to read. I highly suggest checking this out. * *Not too much at once!* Seeing a ton of code all at once (or even normal text) can be overwhelming, but this program goes at the user's own pace! Simply press the enter key when ready to move on. ## So if you're looking for a new language--this is a sign to try out Ruby (my own preferred language)! Scroll down to the Repl and click run to start learning! :D ![Ruby (1)](https://storage.googleapis.com/replit/images/1541072105686_2ccb62fa15e59d409b7a15e1690a5f95.pn) **Let me know if there's a topic in Ruby that you consider a "basic" that I should cover but didn't in this tutorial! And *please* leave an upvote if you used it at all or just like it!** If you're using Repl.it with light mode (default), the comments in the IDE will be a pale grey. If you're using Repl.it with dark mode, the comments in the IDE will be green. I explain a lot of things in the comments and it's also a great way to see Ruby color-coded and such.
4
posted by 21Miya (29) 8 months ago
Go
Go
21
Writing a blog in go!
# Preface I started this tutorial before the contest opened, but because of school and other complications I was only able to post it today. I hope you see how much effort I put into it and give it an upvote, even though I'm probably submitting too late to win. ### Note The repl at the bottom might not work, for reasons that will become clear to you if you follow the tutorial. However, don't worry, as the code in it is still functional, and if you follow the tutorial in your own repl you'll be able to make it work! Anyway, without further adieu, here it is! ### If you have trouble viewing this on repl.it, I also have it in a [Github Gist](https://gist.github.com/vityavv/be3d8df8063f21051e8b5bbeb844a4aa) # Writing a blog in go! ## [CODE](https://repl.it/@vityavv/BisqueStickyActivemovie) ## About this tutorial * __Why go?__ - *Go is a really fast and underappreciated programming language. It is surprisingly simple, especially compared to other low-level languages like rust and c++, and it's very very easy to make web servers in it* * __What is this tutorial based on?__ - *This is based on [scms](https://github.com/vityavv/scms), a CMS I wrote a while ago that is extremely simple* * __Will this tutorial cover all of the features in scms?__ - *Since this is only a short, one-part tutorial, it will **not** cover the API, SQL database, Markdown (you can't install go packages yet, anyway), or drafts.* ## Before the tutorial Before the tutorial, you should have a basic understanding of Go. [Tour of Go](https://tour.golang.org/welcome/1) should help you out! ## Getting started - managing articles First, let's make a file to manage our articles. Each article will be a *json* file that looks like this: ```json { "title": "The title of the article", "content": "The content of the article" } ``` So, let's make a *struct* in our new file, `articles.go`, to reflect this: ```go type Page struct { Title string `json:"title"` Content string `json:"content"` } ``` You may be wondering "Why can't we just have `title string` and `content string`? Well, `json.Unmarshal` (we'll talk about this function in a bit) only puts values into capitalizd struct values, so we have to make them capitalized and then use *tags* to tell json.Unmarshal what to put there. Anyway, before we begin making our functions, we have to get one more thing out of the way: ```go var pages map[int]Page = make(map[int]Page) ``` One option when making a blog like this is to load the json file each time you get it. However, we're smarter than that. We can store each article in memory beforewards to make the application much faster, and easier to make. As a downside, the more articles you have, the more memory you're going to use. However, articles are just text, which should not take up that much space. Another concern here is why I used `map[int]Page` instead of `[]Page`. I did this because each article will have an ID as it's name... and if an article gets deleted, or if they're somehow out of order in the next function, it will be harder to compensate. Even if you decided to make a slice and just skip the deleted files, imagine this scenario: someone has three articles, 1.json, 2.json, and 3.json, but they delete 2.json. There's a bunch of links to the third article, but they all break because it gets deleted from the slice! However, if map is used, you can avoid this problem. Finally, we can get to making our first function, and the most important of them all: the `FileInit` function. The `FileInit` function should be run at the beginning to load each article into the pages map we made earlier. Let's break it down to it's basic parts. The first couple of lines are: ```go files, err := ioutil.ReadDir("./articles") if err != nil { log.Fatal(err) } ``` This is a new import! Make sure you have your file set up correctly, with `package main` at the top, and then in your imports add `io/ioutil`, used for reading and writing files. Now, let me explain what these lines do: they get a list of the files inside of the `articles` *directory*, or folder. The next three lines are basic error handling, which also use the `log` package. **For the rest of the tutorial, I will be ommitting error handling for sake of brevity. Every time you see a variable called err, assume that following that line is error handling as shown above**. After we get that list, we do this: ```go //for every file in the articles folder for _, file := range files { //The following line reads the file we are on pageFile, err := ioutil.ReadFile("articles/" + file.Name()) //Notice the err above, which means that in the real code I did error handling after it //This line makes a new page, called page var page Page //This line "Unmarshals" the json found in the file we read into the page. There is error handling after this one too err = json.Unmarshal(pageFile, &page) //In this following line, we get the page number. This includes a new import, "strconv", which I use to convert strings to numbers and vice versa. Here, I get the file name, take away the ".json" at the end, and then convert it to a number (int). pageNum, err := strconv.Atoi(file.Name()[:len(file.Name())-len(".json")]) //finally, I add the page to our map pages[pageNum] = page } ``` I've annotated the code so you can read through it, but basically it reads each file and puts it in the pages map. That's pretty much it, for the `FileInit` function! Our next function will be a function called `GetFrontPage`. The front page of our blog will have our five most recent articles on it. Here it is, annotated: ```go //The function doesn't take anything, but it returns a slice of pages. The reason you see (fpPages []Page) in the return is because it already defines fpPages in the begining of the function, and then I can just type "return", without anything, and it will return the fpPages variable. This is a really cool feature of go func GetFrontPage() (fpPages []Page) { //make a new slice of pages, with the *capacity* to hold 5, but a length of zero. This is some weird memory managament wizzard magic I saw online, but lengths and capacities are covered extensibly in the tour of go (have you read that yet? ;) fpPages = make([]Page, 0, 5) //Woah! Where did this getPageNumbers come from? I'll explain, right after this pageNumbers := getPageNumbers() //this for loop counts down backwards from the last element in the page numbers to the fifth-to-last for i := len(pageNumbers) - 1; i > len(pageNumbers) - 6; i-- { //Sometimes there's less than 5 elements, so we have to make sure that the page actually exists if i >= 0 { //this uses the built-in append to add the new page to the fpPages slice fpPages = append(fpPages, pages[pageNumbers[i]]) } else { //in case it doesn't exist, it just adds an empty page struct, which makes everything the nil value. fpPages = append(fpPages, Page{}) } } //as discussed earlier, I just have to type return, since the computer already knows that I'm returning fpPages return } ``` But where did this function, `getPageNumbers`, come from? Well, as discussed earlier, we don't always have the page numbers as 1, 2, 3, 4, and 5. Sometimes they're out of order, and with gaps in them. So, I wrote a helper function to get me the page numbers. Have a look: ```go //As before, using implicit returning by already defining pageNumbers func getPageNumbers() (pageNumbers []int) { //As before, magic wizzardry. This is actually pretty similar to get front page. I make pageNumbers into a slice of ints, the capacity equal to how many pages are there pageNumbers = make([]int, 0, len(pages)) //when using range with maps, you do "key, value := range <map>". Here, I only need the keys, so I can omit the values. for key := range pages { //Pretty simple: I add the key to the pageNumbers slice pageNumbers = append(pageNumbers, key) } //New import! "sort" sorts stuff, as you can probably guess. This basically sorts the numbers. sort.Ints(pageNumbers) //Implicit return! Yay! return } ``` We only a couple of functions left. An imediately obvious one is the function to get a single article: ```go //here, it takes the id of the article and returns two things: the page, and the error. This is standard practice for how go handles errors func GetArticle(id int) (Page, error) { //make sure the page exists with this one simple trick! page, exists := pages[id] if !exists { //Another part of error handling: if there's an error, return the nil value for the first return and the error for the second. This line also includes a new import - "errors" - to make errors extremely easily return Page{}, errors.New("Page not found!") } //finally, we return the page that exists and nil (the null value for an error) as the error, because there's no error return page, nil } ``` Another obvious one is to get all of them, so we can have links to them! However, this one is blatently obvious. ```go func GetAllArticles() map[int]Page { return pages } ``` And finally, we come to our missing links. This function is called `CreateArticle`, and it creates a new article, writes it to the file, and adds it to our pages array. Here it is, annotated: ```go //This function takes the title and the content of the article func CreateArticle(title, content string) { //Here, we create a new page, with the title and content aptly set newPage := Page{ Title: title, Content: content, } //Here, we make a json string out of our new page. Note the "err", which means that I had error handling after this line but omitted it json, err := json.Marshal(newPage) //Here, we get our page numbers, from before. They're already sorted! pageNumbers := getPageNumbers() //Finally, we get our new page number, by taking the last page number and adding one to it. newPageNumber := pageNumbers[len(pageNumbers)-1] + 1 //We add the page to our pages map pages[newPageNumber] = newPage //Finally, we add the json to our article, converting the page number to a string and putting it in the right format. The 0600 you see there is for permissions. It basically means that the person who made the file can read and write to it, and nobody else. This is the same number that the wiki tutorial uses, by the way. Also, notice the "err" err = ioutil.WriteFile("articles/" + strconv.Itoa(newPageNumber) + ".json", json, 0600) } ``` And our final function, much simpler, is to remove an article. Here it is: ```go //Notice here that we return the error type func DeleteArticle(id int) error { //When you assign <map>[<key>] to two values, the second value will contain a boolean saying whether the first one exists or not. We can use this to check if we have our article, and if not, return a new error saying "Article not found" if _, exists := pages[id]; !exists { return errors.New("Article not found") } //delete is built in to go. It is used to delete things from maps. Our pages variable is a map[int]page, so taking the int id and deleting it from pages would delete the article delete(pages, id) //Here, instead of doing the traditional "err := os.Remove(...)", we can instead return it, since we know that os.Remove returns an error. We can let whoever is using the function (which is going to be us, coincedentally) deal with it instead return os.Remove("articles/" + strconv.Itoa(id) + ".json") } ``` And with that, we are done with our articles file! ## Part two: Serving the pages ### Part 2.1: The templates Go is a wonderful programming language for so many reasons, but one of them is that it has built in HTML templates! With that in mind, I created three different templates for the three main pages that will go into our blog, using Go's `html/template` module. In part 2.2, I'll talk about how I use these, but before I do that. By the way, if you're viewing these files in the GitHub Gist, they are just called `blahblahblah.html`, but in the repl, and the final application, all of them are in the `templates` folder. First, we have the front page. As discussed previously, the front page has the five latest articles on it. To do that, I have this code: ```html <!DOCTYPE html> <html> <head> <title>My blog!</title> </head> <body> <h1>My blog!</h1> <hr> <!-- Here, we use range, because we pass a slice of articles to the template. This basically means that for everything between {{range .}} and {{end}}, "." will be defined as the article that we are on. --> {{range .}} <!-- Here, we make sure that the article exists by making sure it has a title. Previously, if we had less than five articles, we would put null articles in there, so this is to make sure that we don't have a bunch of extra space at the end of our page --> {{if ne .Title ""}} <!-- here, "." is defined as an instance of our Page type, so we can just access its properties like this --> <h2>{{.Title}}</h2> <p>{{.Content}}</p> <hr> {{end}} {{end}} <a href="/archive">See all articles</a> </body> </html> ``` Second, is our archive, which lets us see links to every single article. Since we use GetAllArticles() here, and that returns a map, we can use the map keys to provide links to each article. ```html <!DOCTYPE html> <html> <head> <title>My Blog - Archive</title> </head> <body> <h1>My Blog - Archive</h1> <ul> <!-- Here, we have an unordered list using range. The reason we don't just have {{range .}} is because we need the key too, for the link --> {{range $key, $value := .}} <li><a href="/articles/{{$key}}">{{$value.Title}}</a></li> {{end}} </ul> <a href="/">Back home</a> </body> </html> ``` And finally, our simplest page, the article page, which shouldn't really need annotation: ```html <!DOCTYPE html> <html> <head> <title>My Blog!</title> </head> <body> <h1>{{.Title}}</h1> <p>{{.Content}}</p> <a href="/">Back home</a> </body> </html> ``` That's it for our templates! ### Part 2.2: Serving Now that we have our files, we have to serve them to the user through our webpage! We do this with the help of one very special package, `net/http`! In clasical low-level languages, the default http solution is usually either non-existent or very hard to use. However, with go, it is actually quite easy to use `net/http`, even easier than `express` for node.js in some cases (e.g. built-in form parsing). Anyway, it handles a lot like `express`, but if you don't know `express`, don't worry about it, because I will be going through each line of code, step by step. The file we will be writing to is `main.go`. Our first function will be the simplest and most important---the `main` function ```go func main() { //Initialize our files. Covered in part one, we need to put this at the top so it caches (loads) all of the files FileInit() //We add a *handler*, more on this in a sec, for any url that starts with /articles/. This includes /articles/1, /articles/2, and /articles/abacabadabacaba. The handler is articleFunc, a function which we will also discuss shortly http.HandleFunc("/articles/", articleFunc) //We add a handler for anything starting with "/", that doesn't start with "/articles/", and that handler is httpFunc. http.HandleFunc("/", httpFunc) //finally, we open up the server on port 8080. In a real environment, you'd use 80 for http. However, since we are using repl.it (or if you're simply testing this on your computer), we put any number we want above 1000. 8080 is a common testing number, as are 3000 and 8000. We use log.Fatal here (log is an import!) so that if http.ListenAndServe returns an error, we can stop the program and output the error. log.Fatal(http.ListenAndServe(":8080", nil)) } ``` while this is a simple function, it packs a lot of information. Let's look at `http.HandleFunc`. `http.HandleFunc` will set a function as a handler, meaning that it will call that function when the specified url is encountered. Since we have `"/articles/"` set to `articleFunc`, every time the server gets a request for `/articles/...`, it will call articleFunc with its parameters. If the request doesn't start with `/articles/...`, it will use the next one, which in our case is `/`, the catch-all, and it will call `httpFunc`. Here's the two functions: ```go //this func has to take the http.ResponseWriter (the thing we use to respond to the request) and a pointer to http.Request (the thing with all of the information from the request) as arguments, and returns nothing, as defined by http.HandleFunc func articleFunc(w http.ResponseWriter, r *http.Request) { //first, we get the article number. we do this by getting the URL and taking the "/articles/" part away from it num := r.URL.Path[len("/articles/"):] //Then, we see if the last character is "/", and if so, we remove it. We use single quotes here because when we access a single character of a string, it turns into a uint8, and we can convert single characters to uint8s by using single quotes around them. if num[len(num) - 1] == '/' { //Subtracting the last element, a slash num = num[:len(num) - 1] } //here, we convert the string to a number. If you go to /articles/1, you're fine, but if you go to /articles/abc, the function errors, leading us to the next if statement pageNum, err := strconv.Atoi(num) if err != nil { //I chose not to omit this one because here instead of log.Fatal, we use http.NotFound, giving it our w and r. http.NotFound(w, r) } //Get the article from previous page, err := GetArticle(pageNum) if err != nil { //the only error that returns is "Page not found" so we can safely assume that there's a 404 http.NotFound(w, r) } else { //then, we simply execute the templat---wait a sec, executing templates? We didn't talk about this yet! Well, hang on, and in just a sec I'll show you this wizardry. executeTemplate(w, "article.html", page) } } ``` And here's `httpFunc`, the simpler one: ```go func httpFunc(w http.ResponseWriter, r *http.Request) { //first, we make a switch, a more efficient set of if statements switch r.URL.Path { //"/" and "/index.html" are both the same thing, so we do the same thing for them case "/", "/index.html": //oh, there's that pesky executeTemplate function again! I promise I'll get to it, just hang tight! Anyway, our front page uses the GetFrontPage function. executeTemplate(w, "frontPage.html", GetFrontPage()) //finally, we return out of the case, to end the function. return //pretty much the same thing as above case "/archive", "/archive.html": executeTemplate(w, "archive.html", GetAllArticles()) return } //Finally, if we haven't returned, that means that our thing was not found, so that's exactly what we do: error! http.NotFound(w, r) } ``` Now I've got you hooked---surely, you are wondering "What is this `executeTemplate` function? How does it work?!?"---here, we use another wonderful built-in method of Go: the built in HTML Templates! Wait... we've heard this one before, haven't we? Well here we are, putting our wonderful templates to good use. We start with this line, at the beginnning (after all of the imports, of course) ```go //make sure you import "html/template" var templates = template.Must(template.ParseGlob("./templates/*.html")) ``` Basically, with this line, we make a templates variable and set it to all of the templates in our templates folder (ParseGlob). The `template.Must` part is basically just a convinient wrapper around it saying that if there's an error, the app should exit immediately with that error. Since this happens at the very start and at no other time, this is OK! Anyway, let's look at our `executeTemplates` function to see how we managed to pull this off: This function takes three parameters. It needs the http.ResponseWriter from our http funcs so that it can write the response to them. It also needs to know what template is being executed. Finally, it needs the content. Since the content and template are different each time, we use an "interface{}", meaning we don't really know the type. In fact, we don't have to know the type at all, because ExecuteTemplate takes a "interface{}" for its content, so as long as we match everything up when we call the function, we should be fine. ```go //I was going to put the above paragraph right here as a comment but I realized it was getting too long func executeTemplate(w http.ResponseWriter, templ string, content interface{}) { //We use templates.ExecuteTemplate() to execute the specific template we want out of the ones we loaded. You can see how this is used in the useage of the function in previous functions. err := templates.ExecuteTemplate(w, templ, content) if err != nil { //Here, instead of killing the server, we give them the error, and a 500 internal server error. http.Error(w, err.Error(), http.StatusInternalServerError) } } ``` That's pretty much it for our main.go file... *so far...* # Part 3 - Administration! This is our final and hardest part, and that is being able to delete and create articles without booting into the repl. Since you can't get packages for go yet, you have to do some work arounds, which I spent a lot of time finding out, so you're going to have to carefully follow these steps: * Make yourself an explorer ([how](https://repl.it/talk/announcements/Become-an-Explorer/6180)) * Open the command pallete by making sure the editor is in focus and pressing F1 * Type in shell, press enter * Type in: `go get golang.org/x/crypto/bcrypt` * Press enter. You might get an error, ignore it (unless it leads to further issues) Why are we doing all this? Well, we can't just store our password in plain text! We have to make sure that it is protected securely, and the way to do that is to use the bcrypt library (there are some others you can use too, but bcrypt is pretty much the industry standard). Other than the first step, which you only need to do once, you may have to do this every time you load up your repl, because of how repl.it works, unfortunately. Anyway, with that out of the way, let's look at how we're going to do things. We will have a "/dashboard" page, pretty similar to our "/archive" page, but this time we will add buttons to delete articles and to create new ones. This part is pretty simple, so we can add this case to our switch inside of `httpFunc`: ```go case "/dashboard", "/dashboard.html": executeTemplate(w, "dashboard.html", GetAllArticles()) return ``` The dashboard itself, though, will be a little bit more complicated. It utilizes javascript to make a "DELETE" request to the server when articles are deleted, but you don't have to worry about knowing javascript, because I can walk you through it: ```html <!DOCTYPE html> <html> <head> <title>My Blog - Archive</title> </head> <body> <h1>My Blog - Archive</h1> <!-- Button links to the "/new" page, for making new articles --> <a href="/new">New article</a><br> <!-- same as before, with the article, except... --> <ul> {{range $key, $value := .}} <!-- Here, we have a button element, and when it is clicked, it calls the del function in our javascript with the paramater being our key. --> <li><a href="/articles/{{$key}}">{{$value.Title}}</a> | <button onClick="del({{$key}})">Delete</button></li> {{end}} </ul> </form> <a href="/">Back home</a> <script> //Here's our del function! Javascript doesn't care about types, but the equivalent in go would be "func del(key int) {" function del(key) { //The prompt function creates a dialog box asking for a password password = prompt("Please enter your password"); //We create a new formData object to turn our password into formdata that go can then use let formData = new FormData(); formData.append("password", password) //We use fetch to make the request. The key there will be replaced with whatever the key that's passed to the function is fetch(`/delete/${key}`, { //For our options, we set the method to DELETE (as to be fancy), and our body to the formData from earlier method: "DELETE", body: formData //javascript async mumbo jumbo that translates to "get the text from it" }).then(r => r.text()).then(r => { //if it isn't successful then we alert the error, otherwise we reload the page to reflect the change. if (r !== "Article successfully deleted") { alert(r); } else { location.reload(); } //finally, if something goes wrong, we alert that too }).catch(alert); } </script> </body> </html> ``` See? That wasn't so hard. But wait, how do we handle these requests? Well, let me introduce you to the next function in our `main.go` file, `deleteFunc`. This will also introduce us to how go's `bcrypt` library works. To use this function, put `http.HandleFunc("/delete/", deleteFunc)` in your main function, anywhere above the "/" handler. ```go //The function is formatted like a normal http.HandlerFunc func deleteFunc(w http.ResponseWriter, r *http.Request) { //Here, we get the key by removing "/delete/" from the path. strKey := r.URL.Path[len("/delete/"):] //We use strconv to convert the key to an actual key. key, err := strconv.Atoi(strKey) //If, of course, the key isn't an int, we error with a 400, meaning there was a bad request if err != nil { http.Error(w, "That's not a valid key", http.StatusBadRequest) //And stop executing return } //Now, if the method is DELETE (which it should be)... if r.Method == "DELETE" { //We make sure that the form sent has a password value. If not, we error, again with a 400. if r.FormValue("password") == "" { http.Error(w, "Password is missing", http.StatusBadRequest) //Otherwise... } else { //Remember this line. This is how we use bcrypt to check passwords. Also, remember "pwHash," because we'll talk about that in a second. Anyway, as you can probably guess, this converts the two strings to byte slices before comparing them, because that's what bcrypt uses err := bcrypt.CompareHashAndPassword([]byte(pwHash), []byte(r.FormValue("password"))) //Instead of returning a boolean, bcrypt will return an error if they don't match. http.StatusUnauthorized, yet another constant, is 401. if err != nil { http.Error(w, "Password does not match", http.StatusUnauthorized) } else { //Finally, the user has been authenticated, and we can use our DeleteArticle function from earlier to delete the article with that key err = DeleteArticle(key) if err != nil { //If you look back to our DeleteArticle function, you'll remember that we error with Article not found when an article isn't found. Now, we can check this! if err.Error() == "Article not found" { http.Error(w, "Article not found", http.StatusNotFound) } else { http.Error(w, "Internal Server Error", http.StatusInternalServerError) } } else { fmt.Fprint(w, "Article successfully deleted") } } } } else { http.Redirect(w, r, "/", http.StatusFound) } } ``` If you try running that code in it's current state, you will notice that it errors. In fact, it will say that `pwHash` is not defined! So, let's fix that. * First, go to a website that generates bcrypt hashes, and put in the password you want to do. [Here's a site that does it!](https://www.browserling.com/tools/bcrypt) * Then, make a `.env` file in your repl. * Inside of that file, put `PASSWORD=<your bcrypt hash>`, where `<your bcrypt hash>` is replaced with the hash that the website generated * Last two steps! Put `var pwHash = os.Getenv("PASSWORD")` at the top of your file, and... * Put the following code at top of your *main* function ```go if pwHash == "" { log.Fatal("There is no password set! Please create a file called .env and make the contents \"PASSWORD=asdf\", with your password bcrypt hashed instead of asdf ") } ``` Now, if you've done all of these steps correctly, you should have a working dashboard, where you can delete articles! But, there is *one more thing*. We need to be able to add *new* pages as well! Let's first make a page, called `new.html`, where the user can put in a new article: ```html <!DOCTYPE html> <html> <head> <title>My Blog - New!</title> </head> <body> <h1>New Article</h1> <!-- This <form> tag makes it so that when someone clicks the submit button, it makes a POST request to the /new page with the information in the form --> <form method="POST" action="/new"> <label for="title">Title</label> <!-- Here, we use the required attribute to make sure that the user inputs it. However, this is not enough! We also have some checks on the server side which make sure the title (and password) are sent --> <input name="title" type="text" required><br> <label for="content">Content</label><br> <textarea name="content" rows="20" cols="100" required></textarea><br> <label for="password">Password</label> <input name="password" type="password" required><br> <!-- When the user clicks on the following button, the browser will make a POST request to the server to make the new article! --> <button type="submit">Submit</title> </form> </body> </html> ``` Finally, we have to handle the article. However, you might notice that I made the form make a POST request to `/new`. Isn't the page called `/new.html`? When we handle this, we're going to check the request type. If it's a post request, we process it. If it's any other type of request, including a GET request, we will send the page. Here's how we handle it, the final part to our program: ```go //You may notice that we are indented, and it starts with a case statement. This is because this part goes into our main "httpFunc" from earlier. case "/new", "/new.html": //Here's where we make the aforementioned check if r.Method == "POST" { //We have to make sure that the form actually sent over all of the information. r.FormValue("thing that wasn't sent") returns an empty string, so we can check on that if r.FormValue("content") == "" || r.FormValue("title") == "" || r.FormValue("password") == "" { http.Error(w, "Either the content, title, or password are missing", http.StatusBadRequest) } else { //Assuming it passes, we move on to the next step, checking the password, just like last time in our deleteFunc err := bcrypt.CompareHashAndPassword([]byte(pwHash), []byte(r.FormValue("password"))) if err != nil { http.Error(w, "Password does not match", http.StatusUnauthorized) } else { //Finally, we create our article. CreateArticle(r.FormValue("title"), r.FormValue("content")) //And send the user to the front page http.Redirect(w, r, "/", http.StatusFound) } } } else { //If you hop back up to where that { was opened, you'll see this was right after "if r.Method == "POST" {", so this is the part where we serve the page, as the request was *not* a POST but rather a GET (or something else, we don't care) executeTemplate(w, "new.html", []string{})//this last one doesn't matter, we aren't using anything in the template } return ``` And that's it! We are done with our Blog! ## Next Steps I left a challenge in the tutorial! Take a look at `DeleteArticle` and `GetArticle` in our `articles.go` file, and see how they differ from the other functions in that file. They both return an `error` as their last (or only) return value! Your goal is to reformat all of the other functions to return an `error` as well, instead of using `log.Fatal()`, which kills the blog. Finally, every time these functions are used, make it so that if there was an error, it returns an error to the client with an HTTP code 500 (Internal Server Error), like in our `executeTemplate` function (main.go) or our `deleteFunc` function (main.go).
2
posted by vityavv (30) 8 months ago
21
Build a Neural Network in Python
Hey guys! I built a simple Neural Network from scratch to learn how they work from a fundamental level. I'd love for you to check out the code and tutorial I wrote. Let me know what you think :) repl: https://repl.it/@shamdasani/Enlight-Neural-Network full tutorial: https://enlight.nyc/neural-network
21
posted by shamdasani (21) 10 months ago