00
Days
00
Hours
00
Mins
00
Secs
Discord Bots Challenge / Ends November 26
🎁 Prizes: Discord Swag, Hacker Plans, Repl Talk Cycles

Learn to Code via Tutorials on Repl.it

Posts
12
Making a Discord bot in Ruby!
# How to get started ### Step 1: install discordrb The discordrb gem (library) is required to make a discord bot in Ruby. You can install it by typing ``` `gem install discordrb` ``` or by using bundler. Then, in your code put `require "discordrb"` on the first line. ### Step 2: setup your bot Assuming that you have created your bot on Discord already, you need to create a bot by doing the following (of course, you can change the name): ```ruby @my_bot = Discordrb::Bot.new token: <my-token>, client_id: <my-id> @my_bot.run true # commands go here! @my_bot.join ``` And of course, `<my-token>` and `<my-id>` are replaced with your bot's token and id. `@my_bot.run true` and `@my_bot.join` help keep the bot running btw. If you want a predetermined prefix, add `, prefix: "<my-prefix>"` to the end of the first line (and `"<my-token>"` is replaced with your token). ### Step 3: adding commands to your bot #### If you have a prefix Having a prefix makes things easier (though a bit limited). To add a simple command, use the `command` method on your bot, followed by the command name (as a string or symbol), any options (will be described later), and the event block (like an anonymous function that looks like a control structure). Here's an example of a command that takes 2 or more numbers, and adds them up: ```ruby @my_bot.command :sum, min_args: 2 do |event, *args| numbers = args.collect &:to_i # turns each argument into a number sum = numbers.collect &:+ # adds up everything in "numbers" event.respond sum # I could have just done `event.respond args.collect(&:to_i).collect(&:+)` btw end ``` This would be used as `<my-prefix> sum num1 num2 [... num]`. #### If you don't have a prefix Not having a prefix is not a bad thing, it just means that you want your bot to do more. You can get every message by using the `message` command on your bot. For each message, you can specify options like: - `contains: "some text"` (searching for text) - `content: "some text"` (to match entire message) or `content: /some_regex/` (to match a pattern) - `starts_with: "text"` or `ends_with: "text"` (for matching the beginning or end of a message ...and other things. To create something like the previous example: ```ruby @my_bot.message content: /^<my\-prefix>\s+sum\s+.+$/ do |event| args = event.content.split " " # "event.content" is the message numbers = args.collect &:to_i # turns each string in "args" into a number sum = numbers.collect &:+ # adds up everything in "numbers" event.respond sum # I could have just done `event.respond event.content.split(" ").collect(&:to_i).collect(&:+)` btw end ``` This would be used as `<my-prefix> sum num1 num2 [... num]`. # Step 4: profit Because you made your bot in Ruby, everyone will love it. Eventually, your bot turns into a paid subscription service. Good night.
16
posted by theangryepicbanana (125) 8 days ago
46
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! ✨✨✨
11
posted by ArtemLaptiev1 (45) 19 days ago
79
Making a Phaser Game with HTML5 and JavaScript
# Making a Phaser Game with HTML5 and JavaScript Hi guys! Everybody likes to make games, right? And everybody has their own way of doing it. In this tutorial I wanted to share a very simple, yet effective way to make games in your browser! It should be easy enough for most people with javascript knowledge to follow along and, if you want to investigate further, there are endless possibilities out there! ![image](https://storage.googleapis.com/replit/images/1539468462288_75406edb94f04ca097cc5b4705ccbc85.pn) ### Phaser As Phaser describes itself it is a fast, free and fun open source framework for Canvas and WebGL powered browser games. And it really is! It is super simple to use and is quite easy to set up. No super extensive javascript knowledge is necessary and the process of making games is fun and rewarding. It also comes with tons of extra features that you may need in some more complicated games so while it caters to starters as well, it also does not lack depth if you want to look further. Anything from image editing to complex game mechanic mathematics is possible. ##### Sites to use The official Phaser website is [here](https://phaser.io). Additionally, because we are going to use Phaser 3, the latest release, the examples on the site will most probably not work for v3. If you want some examples of v3 features the link is [here](https://labs.phaser.io/). You should not need the examples during this tutorial but if you want to learn further that is where you start. Google works as well but be careful about which version is being discussed. Version 3 is relatively new and v2 has loads more documentation and examples and tutorials on it. However, I would recommend learning v3 because it is generally better in many ways and the knowledge will last you longer and it will be more current. #### Prerequisites (what you need before doing this tutorial) The pre-requisites are: * A basic understanding of HTML, CSS and Javascript. * Knowledge in Javascript about the `this` keyword. * Some time and patience. * 3 rolls of duct tape. * Lots of cardboard * Creativity ### Let's Get Started! The repl.it project that I will be using for this tutorial is [here](https://repl.it/@kaldisberzins/Phaser-Tutorial) and the website for it if you just wanna play the game is [here](https://phaser-tutorial.kaldisberzins.repl.co/). If you ever get stumped on a step that I take in this tutorial just check the repl and see how the code looks in it. If all else fails a bit of copy-paste will solve your issues. Make a new HTML/CSS/JS repl and follow along... So, first of all we need to include the Phaser script into our website. The only piece of HTML in this tutorial will be the following:`<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>`Just paste this into your project's HTML file right above your script tag that links to `script.js`. The order is important and if you get it wrong nothing will work. If your project is not working you should definitely have a look at the order of your scripts. The Phaser script should be first. With that out of the way, let's get into making our game! The first bit of code is a standard template that is in most simple Phaser games (more advanced ones may use a slightly different structure but the idea is the same). The code looks like this: ```javascript let config = { type: Phaser.AUTO, width: 800, height: 500, physics: { default: 'arcade', arcade: { debug: false } }, scene: { preload: preload, create: create, update: update } }; const game = new Phaser.Game(config); function preload(){ } function create(){ } function update(){ } ``` While this may look alien to you, don't stress. To follow along this tutorial you don't need to understand what everything does exactly. The main things you should pay attention to are: * The three functions at the bottom `preload`, `create` and `update`. These we will fill in with the game's code. * The `width` and `height` properties. You can set these to anything you like, I did not make it `window.innerWidth` and `window.innerHeight` because scaling can quickly become messy. It is easier to make it a fixed width for everybody. So now if you run your repl you should see a black square in your browser window. Success! If you do not, make sure you have the Phaser script in the right place and that you have the code in your `script.js` exactly like above. You should also get a message in the console, something like: ```%c %c %c %c %c Phaser v3.14.0 (WebGL | Web Audio) %c https://phaser.io background: #ff0000 background: #ffff00 background: #00ff00 background: #00ffff color: #ffffff; background: #000000 background: #fff``` This may look awful in the repl.it console but if you open it in a new tab and check the console it should be a colorful banner. ### Loading Assets The `preload` function that we are going to use for this section is where you load your assets. If you want some images or audio (Phaser does that as well) in your game you first have to load it here. This way you are loading all the required assets immediately and you can use them throughout the game. I have made some assets for this tutorial so that you do not need to find or make some yourself. Go [here](https://drive.google.com/drive/folders/1TzRicUBL8V0T_9fPMaNCL6M0UEV51irQ?usp=sharing) and click download like so to get the files: ![image](https://storage.googleapis.com/replit/images/1539468612344_eeb16f0a94e74fa401749d11f7b89333.pn) If you get the files in a `.zip` folder just unzip them and drop them into your repl. Once you have them in your repl we have to load them into our game. The following code in the `preload` function will do the trick: ```javascript this.load.atlas("player", "spritesheet.png", "sprites.json"); this.load.image("platform", "platform.png"); this.load.image("spike", "spike.png"); this.load.image("coin", "coin.png"); ``` The first parameter in all of the functions is the "key" for the image. This key you would use when you need to add the image into the game. You can put it as whatever you want but make sure it is descriptive of the image in some way. I suggest you keep them the same as mine so that later code in my tutorial works for you. The second parameter is the path to the image. Because I put the assets in the same folder as the html and js files the path is just the name of the image. If you put your assets in another folder the file path string would look like `"folder_name/file_name.png"`. You may also have noticed that the first command is a bit different. It loads an __atlas__ and not an image. An atlas is a collection of images put together to make a larger image accompanied by a file that states where all the smaller images are. If you open the file `sprites.json` in the assets I gave you you should see that it contains a bunch of named objects that have x, y, width and height properties among others. Each object is an image inside the larger image. In this tutorial we will use the atlas for the player animations. All of the frames for the player (in our case only three) are in the `spritesheet.png` file. The third parameter for the atlas is the path to the `.json` file which we looked at already. If you now run the current code the screen should remain black and no errors should be in the console. If you see a web audio warning that is fine, it does not mean anything important. It's just chrome messing with you. ### Adding Objects to Our Game The `create` function is where the building of our game happens. It is run right after `preload` and is run only once. If you want to add an object to the game, this is where you do it. If you want to repeatedly create some object. Make a function (read below) that creates the object and run that as may times as you like. So we now have loaded some images but we need to have something happen on the screen. Let's add a function in the `create` function that will spawn our player in. Add this code to the `create`function: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); } this.spawnPlayer(); ``` I put this in a seperate function so that we can spawn the player multiple times. We are saving the player to __`this`__ which is the Phaser game object so that we can access it from anywhere. The function itself creates a sprite (image/object) that is in the Phaser physics system. The parameters are: 1. X position 2. Y position 3. Image key 4. (optional) If the image is an atlas, which frame in the atlas. There may be a few more parameters but those are not important for this tutorial. The way we find out which frame is which in the atlas is by looking at the `sprites.json` file. Find an object and look at its x and y properties. For example `sprite_2` has the following object: ```javascript "sprite_2":{"frame":{"x":0,"y":0,"w":48,"h":64}... ``` We can see that the x and y coordinates of the frame are `0, 0`. This means that it will be in the top left corner. If you look at the top left corner of the `spritesheet.png` image you will see which frame is `sprite_2`. Try changing the last parameter in the add function to be `sprite_2`. You will see that it has changed. ##### Adding a Background If the only background color we could have would be black Phaser would look really bad. Luckily enough, Phaser has an easy way to add a background to our game. Just add this code to the top of your `create` function above the `spawnPlayer` function: ```javascript this.cameras.main.setBackgroundColor('#ffffff'); ``` This sets the background color for our main camera to white. If you have not used hex color codes before don't worry about it, just know that `#ffffff` is white. The only problem with that is that now we can't see where our canvas windw starts and ends. We can fix this with a little CSS: ```css canvas{ border: 1px solid black; } ``` Now if you run your code it should look something like this: ![image](https://storage.googleapis.com/replit/images/1539468654218_bf2de4d9dc55069fde105a14f6c9818a.pn) You can see we have our little character in the middle of the screen. The background is now white. You may have noticed that the character is not offset to a side even though we put in the coordinates for the center of the screen. This is because Phaser draws images from their center. This makes it easier to center images. Another simple thing we can add to the game is a camera that follows the player. This is quite easy to do in Phaser: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); this.cameras.main.startFollow(this.player); }; this.spawnPlayer(); ``` The function should be quite self-explanatory and if you run it you should see no change for now. As long as you do not get any errors you are fine. ### Adding Platforms Before we start I wanted to show you the most basic way to add an image to the game. The method used above has a very specific use case (only for sprites). Here is a more general use way of doing it: ```javascript // This goes beneath the spawnPlayer function call this.platform = this.add.image(404, 302, "platform"); ``` This is good for some simple use cases like for example a logo image in your title screen. However it has its shortcomings. Imagine you want to create a map of these platforms. You would have to add `platform1` `platform2` and so on... It would be a nightmare. Let's not get started on collisions. So by now you can see why we are not going to use this to add our platforms. Instead we will have a group. Defining a new group is easy. Remove the above code and add this instead. ```javascript this.platforms = this.physics.add.staticGroup(); ``` Currently we are just defining a new static (non-moving) group and assigning it to the variable `this.platforms`. If you run this now the platform image will disappear. That is because we need to add some platforms to the group. This can be done simply like this: ```javascript //Below the spawnPlayer function this.platforms = this.physics.add.staticGroup(); this.platfroms.create(404, 302, "platform"); ``` There we go! Now we have our platform back! But what is the benefit? In a moment when we deal with collisions you will see why. For now we will leave the platforms and get back to them later. ### Keyboard Inputs As you have probably gathered by now, Phaser has made its own version of everything you may need when developing games. Keyboard inputs are no exception. Phaser even supports many ways to do keyboard inputs. We are going to do the shortest and simplest. We are going to have a bunch of variables, one for each key. And we will check each frame if any of the keys are pressed and set velocities accordingly. The code for the keyboard variables in the `create` function looks like this: ```javascript this.key_W = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W); this.key_A = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A); this.key_D = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D); ``` You do not need to understand this, just get the idea of what is happening. When a player presses a key the variable associated with that key will have `isDown` set to `true`. This makes adding keybinds really easy. Now for the rest of this section we are using the `update` function. `update` is your game loop. This function is run very fast repeatedly all throughout your game. This is where you would handle things like movement and other stuff you would want to check every frame. If you would be coding your own physics this would be where you do it. In the `update` function now let's check if the W key is pressed: ```javascript if(this.key_W.isDown){ this.player.setVelocityY(-50); }else{ this.player.setVelocityY(0); } ``` Instead of incrementing or decrementing the Y property of the player we set its velocity. We do this because it sets a velocity within Phaser which has some benefits. First of all Phaser object velocities take into account the frame rate. If every frame you increase the position X of a player, the higher the frame rate the faster the player moves. However, Phaser counteracts this. We do not need to know how, just that no matter the frame rate the player will always move at the same speed. The value we put into `setVelocityY` is the amount of pixels we want it to move in one second. If you run this now you will see that is you press the W key your character will move up. Success! Now let's add keybinds for A and D. This is only a few more lines of code: ```javascript if(this.key_A.isDown){ this.player.setVelocityX(-50); }else if(this.key_D.isDown){ this.player.setVelocityX(50); }else{ this.player.setVelocityX(0); } ``` We have this in 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]_
17
posted by kaldisberzins (178) about 1 month ago
70
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)
10
posted by jajoosam (120) about 1 month ago
7
Chat on the terminal
# Chat on the terminal ## Build a realtime chat in your terminal 💬 ![](https://i.imgur.com/OqMNLC2.gif) [Demo](https://chat.jajoosam.repl.run) ⏯️ [Code](https://repl.it/@jajoosam/chat) 👨‍💻 This is a quick tutorial which helps you build a realtime chat on your terminal - using [socket.io](https://socket.io) - we can build and test super quick thanks to [repl.it](https://repl.it)'s [repl.run](http://repl.run) platform - which displays a terminal on the web 🌐 👨‍💻 ## ⚙️ Dependencies We're only using one external dependency in this project - [socket.io](http://socket.io), which helps us communicate realtime between several clients and a server. Along with this, we'll be using node's built in `readline` which lets us collect input from the terminal. ## 💁 Setting up the server Because we're using [socket.io](http://socket.io) - we need to spin up a small server to relay messages too! Just fork this, and you'll be all set 👉 [repl.it/@jajoosam/chat-server](https://repl.it/@jajoosam/chat-server) ```javascript io.on('connection', function (socket) { socket.on('message', function(data) { io.emit("msg", data); }); }); ``` This small block of code listens for any `message`s from any user, and then broadcasts that message to all the users - that simple ✨ ## 💬 Let's get chatting Let's start off by forking [this repl](https://repl.it/@jajoosam/chat-starter) - I've already declared dependencies to make things simple. On `line 3`, replace the `url` with that of the server you just created. Whenever a user connects, let's ask them for their name. Put this code inside the `socket.connect` block. ```javascript rl.question(`What's your name? `, (answer) => { socket.emit("message", `👤 : ${answer} has joined the chat`); id = answer; chat(); }); ``` We're sending a message which says a new user has joined the chat, and storing their name for later reference. As you can see - we're also calling the `chat` function, which is currently empty - let's change that! ```javascript rl.question("» ", (answer) => { // "» " Gives a prompt for the user socket.emit("message", buffer); chat(); }); ``` We're prompting for a user to type out a message, then sending it back to the server - also at the end - we're calling `chat` again in case they want to send more messages ⌨️ ## 🖨️ Printing out messages If you try running this code now, you'll see that no message you type is printed in the terminal. Let's create a new event listener inside `socket.connect` to listen for messages 👇 ```javascript socket.on('msg', function(data){ console.log("\n" + data); chat(); }); ``` Whenever the server broadcasts a new message to us, we print it out to the `console` - and call `chat` again - so that our user can keep sending messages! ## 🛠️ Hacking this It was pretty simple to build this chat - but it doesn't seem like a conventional one in many ways. Luckily, you can change that 😄 **Here are some ideas to tinker with this project 👇** - Let everyone know when a user is typing ⌨️ - Don't print out messages sent by the same user repeatedly 🔄 - Add color + formatting to the chat with [chalk](https://github.com/chalk/chalk) 🌈 - Take realtime to the next level by broadcasting every character as it's typed 💡 Check out [this](https://github.com/aviaryan/chattt) open source project for more ideas! Here's the code for the completed project (with a few tweaks!) - feel free to refer to it 👨‍💻 [https://repl.it/@jajoosam/chat](https://repl.it/@jajoosam/chat) Now, go ahead and share what you've built on [repl talk](https://repl.it/talk/share), and tag me - [@jajoosam](https://repl.it/@jajoosam) 👤
0
posted by jajoosam (120) 5 days ago
43
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! :)
9
posted by minermaniac447 (61) about 1 month ago
33
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) `
21
posted by John_WardWard (61) about 1 month ago
25
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!
2
posted by CoolqB (54) 26 days ago
17
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).
1
posted by vityavv (16) 21 days ago
30
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
7
posted by LucHutton (50) about 1 month ago
29
A Quick Guide to Repl.it Talk Markdown
Guys! In this quick tutorial, I'll be showing you how to make your posts pretty using Markdown styling! # Headers First we'll learn about headers. A header starts with a hashtag symbol `#` followed by a space: ```md # A header ``` Output: # A header Headers can be a variety of sizes. A smaller header starts with more hashtags. The number of hashtags can be 1 to 6: ```md #### A header with 4 hashtags ``` Output: #### A header with 4 hashtags Alternatively, you can also "underline" a text with `=` or `-` to produce headers ```md First header (Same as # First header) -------------- Second header (Same as ## Second header) =========== ``` ___ # Text Styles You can make *italic*, **bold** or ~~strikethrough~~ text. Put the text between a pair of `*` or `_` to make it *italic*. ```md *italic text* _also italic_ ``` Output: *italic text* _also italic_ Put two `*` or `_` on both sides of text to make it **bold**. ```md **bold text** __also bold__ ``` Output: **bold text** __also bold__ You can also do a ~~strikethrough~~ by putting two tildes (`~`) on each side: ```md ~~strikethrough~~ ``` Output: ~~strikethrough~~ It's ok to mix up those stylings: ```md **_~~bold, italic and strikethrough~~_** ``` Output: **_~~bold, italic and strikethrough~~_** ___ # Lists There's two kind of lists in Markdown: **unordered** (bulleted) and **ordered** (numbered). Since repl.it talk Markdown doesn't support ordered lists (sadly), we'll only deal with unordered lists. An unordered list item starts with either a `*`, `+` or `-` followed by a space: ```md * this + that - and stuff ``` Output: * this + that - and stuff Use indentations of 2 spaces to make sublists ```md * list item * sublist item * yet another sublist item ``` Output: * list item * sublist item * yet another sublist item ___ # Links Just paste the URL and it'll work: ```md https://repl.it ``` Output: https://repl.it If you want **custom link text**, try this: `[link text](URL)`: ```md [Repl.it](https://repl.it) ``` Output: [Repl.it](https://repl.it) ___ # Images The Markdown syntax for **images** is pretty simple: `![alt text](URL)`: ```md ![Repl.it logo](https://repl.it/public/images/icon-square.png) ``` Output: ![Repl.it logo](https://repl.it/public/images/icon-square.png) **Wait... what if my image is stored in my computer? It doesn't have a URL!** Well, repl.it provided an easy way to upload images. All you need is to click the **select files** button below to upload it. After that, you'll see the Markdown code for your image in the text box. ___ # Code And finally, code!! **Inline code** and **code blocks** are widely used in repl.it talk since repl.it talk is a platform for coders to share. Wrap a pair of **backticks** (`` ` ``) around text to make a span of code (inline code): ```md `$ node index.js` ``` Output: `$ node index.js` To indicate a block of code, put three backticks (` ``` `) at both the start and end of your code: ````md ``` This is a code block. Everything here is monospaced. ``` ```` Output: ``` This is a code block. Everything here is monospaced. ```` Additionally, repl.it supports code block syntax highlighting, which is pretty useful for emphasizing readability. Just put the language name (or its short form) after the three backticks: ````md ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ```` Output: ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ___ # Blockquotes To do blockquotes put a `>` before each line of the block: ```md > Timchen is the greatest and > we should praise him ``` Output: > Timchen is the greatest and > we should praise him Don't forgot to leave a blank line after each blockquote! ___ # Horzontal rules A horzontal rule (a line that separates content) can be made of either three asterisks (`*`) or underscores (`_`): ```md There's a horizontal rule below *** There's a horizontal rule above ``` Output: There's a horizontal rule below *** There's a horizontal rule above That's all what I can teach in this very tutorial. Start using Markdown to style your posts, and find more about it!
6
posted by JSer (894) about 1 month ago
28
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 (570) about 1 month ago
12
How to create a fairly basic game using Python w/ Turtle Graphics
# How to make a simple game with Python + Turtle ___ Hello! If you're reading this, I can only assume you want to learn about **how to make a fairly basic game using Python with Turtle Graphics**. If that's not the case, why are you here? Go do something else. If you're still here, I'm going to assume you have some basic knowledge of Python (syntax, how to use variables, etc.) and some more in-depth of Turtle Graphics. If you don't, please at least read the first 4 chapters or so of [this](http://interactivepython.org/runestone/static/thinkcspy/index.html) resource. If you need to find more about turtle functions (which you likely will), see [these](https://docs.python.org/3.3/library/turtle.html?highlight=turtle) docs. I know this is long, but if you want to do this right, it's **VERY IMPORTANT** to read through each section!!! If you miss even one thing, your code may not work! ## I - Creating your repl & basic setup ___ OK, so the first thing you need to do is create a Python with Turtle Graphics Repl. If you already have an account, you can do this by clicking the big red plus button, click Search All Languages, searching for Python, and selecting Python (with Turtle). Alternatively, (and anyone can do it this way), you can just click on [this link](https://repl.it/languages/python_turtle)! Now, the next thing you should do is import the turtle graphics module. To import the turtle graphics module, include the following lines at the top of your code: ```python #Import statements import turtle ``` It's as simple as that! The first line a comment - it is very useful in keeping your code organized and readable. The second line is called an import statement, and it does just what it sounds like it does. ## II - Creating the window ___ Now that we have imported the turtle module, we can get started. To make a Python w/ Turtle repl work, we need to have something for the turtle to draw **on**. Now, technically this isn't necessary at this stage, it will be if you want to set a background color, and it will be for later things. To create a window, add a blank line, then the following code: ``` #Creating the window window = turtle.Screen() ``` If you would like to have a background color for the window, also include this line after the following lines: `window.bgcolor("#UVWXYZ")`, where UVWXYZ is the hexadecimal color code of the color you want for the background color. (To get a hex color code, just Google 'color code picker'.) The hex color code has to be surrounded in quotes because it is a string and must be read as such. So, just to recap, your code should now look like this (I have included my own hex color code, feel free to use it or choose your own): ```python #Import statements import turtle #Creating the window window = turtle.Screen() window.bgcolor("#444444") ``` Now comes the fun part - you can press the green 'Run' button and see something visibly happen! Up in the top left corner of the right side of your screen (under the section labeled 'result'), you should see the word "center". If you choose a background color, you should also see that area turn that color. If this worked, great! Continue to step 3. If not - double-check you have entered the code correctly. ## III - Creating the game box ___ ### Part 1 - Creating the turtle Now, we're going to draw the area that the game will be played in. This will also define the grid we're going to use for the game. For this example, I'm going to be using a box size of 500x500 (-250 to 250 on each axis), with a grid size of 50. To do this, we need to do a few things. First, in a new section (separated from the previous sections by an empty line), we need to create a turtle to use to create the box. So, we're going to create a comment detailing what this section of code does, then we're going to create our first turtle. Let's add the following lines of code: ```python #Initializing turtles outer = turtle.Turtle() ``` The second line, `outer = turtle.Turtle()`, creates a new turtle object and calls it `outer`. We will be doing a lot more of this later, so remember this. ___ ### Part 2 - Setting up the turtle Now, we're going to create our play area. First of all, let's make a new section. The first line we're going to do is set `outer`'s speed. To set the speed of a turtle, you use the function `turtle.speed(x)`, where turtle is the name of the turtle object you're using and x is a number from 0 to 10. Speed increases from 1 to 10, and 0 is the maximum speed - going as fast as python can handle. This is what we want to use, because it will keep the user from having to wait as long to start. So, to set the speed of `outer` to the fastest possible, we're going to use `outer.speed(0)`. Next, let's set a border color and fill color for the area. This uses the `turtle.color()` function, which takes up to 2 arguments (the things in the parenthesis). The first is the pen color, or the color that it will draw with. The second is the fill color, which is exactly what it sounds like - the color that is filled in when using fill. For this example, let's use #000000 (black) for the pen color and #FFFFFF (white) for the fill color. So, underneath the outer.speed, we're going to have the following line: `outer.color("#000000","#FFFFFF")`. ___ ### Part 3 - Drawing the area **DISCLAIMER:** From this point on, I won't be explaining in as much detail how each command works, though I will continue giving examples. Please see the docs if you want more info. The first thing to do when drawing the area of the game is to decide how big you want the area to be. In this example, I will be using **500x500**, but you can easily change that. Since your turtle's pen defaults to down, if you want to move it without drawing, you have to send `outer.up()`. Next, you need to go to the coordinates of whatever point you want to be one of the corners of your area - the easiest way to get this is to have your turtle go to (x,y), where x is half of the width of your area and y is half of the height. Since our area is 500x500, use `outer.goto(250,250)`. Next, do start being able to draw, we need to use `outer.down()`. To begin filling the play area, we need to add `outer.begin_fill()`, which will continue tracking the inner area of what you have drawn until you tell it to end the fill. Now, we're finally ready to start drawing. While you can do this with individual turns and forwards, it's much better to use a loop. To make a loop that loops 4 times that will draw us a square of side length 500, we need to use this code: ```python for i in range(4): outer.rt(90) outer.fd(500) ``` This will tell the turtle to make a 90-degree right turn, then go forward 500 pixels 4 times, creating a square. Finally, we need to end the fill by sending `outer.end_fill()`. If you press run now, you should get a full square drawn and filled in. If it doesn't work, check your code against this: ```python #Making the outer border of the game outer.speed(0) outer.color("#000000","#FFFFFF") outer.up() outer.goto(250,250) outer.down() outer.begin_fill() for z in range(4): outer.rt(90) outer.fd(500) outer.end_fill() ``` ## IV - Hiding turtles ___ When you press run, you'll see it the play area, but you'll also see the turtles - the little arrows pointing towards the right. Well, if we're making a game, we can't have that! Let's hide those turtles so that they aren't visible to the user. To do this, we need to make a new section - preferably as close to the top as possible, while still below the section where you initialized the turtles. To hide a turtle, you use `turtle.ht()`, where turtle is the name of the turtle. So, let's quickly make a section and hide the `outer` turtle. Now, if you run it, you won't see the little arrow after the drawing is finished! ## IV.V - Drawing a grid (Optional!) ___ Now, this whole section is **OPTIONAL**! You do **NOT** need to include this section, but I find it helpful especially when creating the game. Now that that's out of the way... ___ ### Part 1 - Creating an array To create a grid for the game, we need to do a few things. First, we need to keep track of each gridline's position. We can do that fairly easily with an **array**. This array should go in its own section, since we're going to be using more arrays later. The increments and decrements from 0 for each value in the array depend on how big you want each grid box to be - for this example, I'm going to use **50x50**. So, we're going to create an array - let's call it `gridpos` - by doing the following: `gridpos = []`. We now have an empty array. Now, to get the values for each grid position, we're going to go from the x position of the bottom left corner of your box - if you're using my numbers, it will be -250 - and add the side length of a grid square - in my case, 50 - to it. This is our first value. Continue until you reach the positive version of the first number. Mine looks like this: `gridpos = [-200, -150, -100, -50, 0, 50, 100, 150, 200]`. Now, we can start to draw it. ___ ### Part 2 - Drawing the grid We're going to need another turtle for the grid, so let's call it... wait for it... `grid`. We're going to want to hide this turtle, so in the hiding turtles section, let's add a line to hide it. Then, set its speed to 0 and its color to whatever you like - for this example, I used #888888. Then, we're going to need to make a loop, and have it loop for 1 fewer times than the number of grid squares you want for the height or the length. So, if you want a 10x10 grid, then it needs to loop 9 times. Inside that loop, we want it to do the following: Go to the leftmost edge of the box and draw a horizontal line for each value in `gridpos`, and go to the bottommost edge of the box and draw a vertical line for each value in `gridpos`. The easiest way to do this is with a large loop. You'll want to loop as many times as items you have in `gridpos` - in my case, 9 times. Let's break this down into 2 parts - **Horizontal Lines** and **Vertical Lines**. ___ #### Part 2A - Horizontal lines Since your turtle will be starting at (0,0), and we want it to draw a horizontal line at each y position in `gridpos`, we need to get it to go to each without drawing off the lines. We can do this by telling it to pick up the pen, then goto the far-left x value and the y value corresponding to the iterator's value in `gridpos`. This is a little hard to explain, so let me show it: ```python for p in range(9): grid.up() grid.goto(-250,gridpos[p]) ``` What this will do is go to (-250, the value of the p'th item in `gridpos`), whatever that may be. From there, it's as simple as putting the pen down and going forward the side length of the area, then turning left 90 degrees. So, your current code for the grid should look like this (Initializing of the grid turtle and gridpos array not shown): ```python #Making the grid grid.speed(0) grid.color("#888888") for p in range(9): grid.up() grid.goto(-250,gridpos[p]) grid.down() grid.fd(500) grid.lt(90) ``` ___ #### Part 2B - Vertical lines Now, it's time to make the vertical lines. Luckily, this part is much easier since we have the first part. All you need to do is copy/paste the code from `grid.up()` to `grid.fd(500)` to immediately below itself, switch -250 and gridpos[p] in the `grid.goto()` statement, and switch the left turn to a right turn. Now, you should have this inside the loop: ```python grid.up() grid.goto(-250,gridpos[p]) grid.down() grid.fd(500) grid.lt(90) grid.up() grid.goto(gridpos[p],-250) grid.down() grid.fd(500) grid.rt(90) ``` If you run it now, you should see it create a complete grid in your play area. ## V - Initializing the boxes ___ Now, the whole point of this game is to collect boxes - you can decide how many. In the example I used 7, but I only am going to detail 3 because it's a very simple, repetitive process to make more. First, we're going to need to create a turtle for each box. Let's go back up to the turtle initialization section, and create 3 turtles - `box1`, `box2`, and `box3` using `x = turtle.Turtle()` and hide them. Now, we probably want some margin between each box and the gridlines - for this example, I'm using a margin of 5 on each side. To make this easier, let's make 2 arrays - an `xlist` and a `ylist`. Each **x value** is going to be 5 **above** the 50 - so -45, 5, 55, 105, etc. Each **y value** is going to be 5 **below** the 50 - so -55, -5, 45, 95, etc. These arrays should go in the same section as the `gridpos` array, for organization's sake. We also need to declare a whole ton of variables - 4 for each box - which will be used later. For each box, we need `boxZx`, `boxZy`, `boxZgridx`, and `boxZgridy`, where Z is the number of each box. We can do that just below the array initialization section. So, to make it simple, for `box1` we can just use `box1x = box1y = box1gridx = box1gridy = 0`, so that each of those variables has been initialized but is equal to 0. This saves line space and some time. ## VI - Placing the boxes ___ This is the part where things start getting repetitive. Each section to place a box is almost exactly the same as the last. First, make a new section for `box1`. First, we want to set its speed to 0 so that it draws as fast as possible. Then, we're going to set its color - in this example, I'm using #8B4513, because it's a nice brownish color. Then, we're going to go up to pick up the pen and go to a set coordinate. For now, let's just go to the top right grid square. To do this, we need to tell `box1` to goto `xlist[9],ylist[9]`. Next, we're going to put down the pen and begin the fill. After that, we need to draw a square of side length 40, because our grid squares are side 50 and we have a margin of 5 on each side. This can be done with the same loop we used to draw the area, but instead of going forward 500 we go forward 40. Finally, we need to end the fill. If you run it now, you should see a brown box appear in the top right corner. That means it's worked! If it hasn't, see this code: ```python #Making the first box box1.speed(0) box1.color("#8B4513") box1.up() box1.goto(xlist[9],ylist[9]) box1.down() box1.begin_fill() for z in range(4): box1.fd(40) box1.rt(90) box1.end_fill() ``` Now, you just need to do the same thing for boxes 2 and 3, but with a different value in the xlist[] and ylist[]. See what experimenting with it does to the position! ## VII - Randomly placing the boxes ___ #### Part 1 - Basic randomization Now, I know what you're thinking. *"We already placed the boxes!"*, you'll say. *"Why do we need to do another section on placing boxes?!"* Well, you don't want to have it be the same position every single game, do you? That takes away some of the fun! Let's make a randomization aspect. First, up in the import section, we need to `import random`. This will let us use a very important function - `random.randint()`. Now, we need to create a new section above the drawing of box1 - let's do it directly below the grid section. This is where we're going to start using those variables we created. First, we need to assign `box1gridx`. So, we're going to use `box1gridx = random.randint(0,9)`. This will tell `box1gridx` to become a random integer between 0 and 9, so that it encompasses the whole of the array. Then, do the same for `box1gridy`. Now, we need to assign `box1x` to a number in `xlist[]` based on `box1gridx`, and the same for `box1y`. This is simple, based on what we know about arrays. Just use `box1x = xlist[box1gridx]`, and do the same for `box1y`. Now, just for debug purposes, let's print the x and y positions to the console using `print(box1x,box1y)`. Finally, we need to change the goto positions when drawing box1 from `xlist[9],ylist[9]` to `box1x,box1y`. If you did the randomization right, it should look like this: ```python #Getting coordinates for box1 box1gridx = random.randint(0,9) box1gridy = random.randint(0,9) box1x = xlist[box1gridx] box1y = ylist[box1gridy] print(box1x,box1y) ``` If you run it now, it should go to a completely different spot each time. ___ #### Part 2 - Specialized randomization Something you may see come up - very rarely, but it could happen - is multiple boxes in the same spot. Now, while this is technically OK, we don't want it because it limits the game's potential. So, for `box2`, we're going to use the same code as for `box1` (slightly modified to apply to `box2`), but we're going to add something to it. We need to check to see if `box2x` is the same as `box1x` and if `box2y` is the same as `box1y`. If they are the same, then we need to give `box2` a new position. We can do this by putting the whole of the randomization code for `box2` in a `while True:` loop (There are better ways to do this, but this is a simple way - you **do NOT** want to run this until you have put a `break` into it), then putting in an if statement. Since we need to check if `box2x` is `box1x` and `box2y` is `box1y`, `if (box2x == box1x and box2y == box1y):` should do the trick. Note that we need to check for both, because just one being the same is OK. Then, under that if it doesn't really matter what we put, so I just put a print statement saying that the placement of this box failed. What is very important is the else. We need to make sure we have an else after the if that contains the line `break`. Otherwise, we will be stuck in this loop forever. So, before running, double check that you have this code for `box2`'s randomization: ```python #Getting coordinates for box2 while True: box2gridx = random.randint(0,9) box2gridy = random.randint(0,9) box2x = xlist[box2gridx] box2y = ylist[box2gridy] print(box2x,box2y) if (box2x == box1x and box2y == box1y): print("Box 2 placement failed, retrying...") else: break ``` Finally, let's fix `box2`'s goto so that it goes to `box2x`, `box2y`. Now, to do this for more boxes it's very similar, but you need to check the position against every single previous box's position. So, for box3, you would need the conditional `(box3x == box1x and box3y == box1y) or (box3x == box2x and box3y == box2y)`. Fill in that randomization and its corresponding goto, and then press run. You should see all 3 boxes go to completely random spots each time! # VIII - Drawing the player ___ Now, it's time to draw our player. This will eventually be moving around on the grid and collecting the boxes, but for now let's just try and draw it. To make it simple and easily distinguishable from the boxes, we're going to choose a different color and shape. In this tutorial, I'm using a circle of diameter 40 and color #ABCDEF (a nice light blue.) To draw the circle, you *could* use `turtle.circle()`, but I'm going to use the more obscure `turtle.dot()`, which draws a dot based on the turtle's position as the center of the circle. Because of this, we need a new array called `playerposlist`. The values in this will be 25 away from each value in `gridpos`, because our grid boxes are 50x50. So, we'll start at -225, then -175, -125, etc. Next, we need to actually create our `player` turtle and hide it, both in their respective sections. Now, we need to create 2 variables to track `player`'s x position and y position in relation to the grid - `playerx` and `playery`. Let's set both of them to 4 for now. Since we're going to need to draw the character a LOT, let's put the drawing code into a function - `drawplayer()`. Since this will be called multiple times, we want our first line to clear any previous drawings using `player.clear()`. Then, set the speed to 0 and have the turtle pick up the pen. Now, we're going to `player.goto(playerposlist[playerx],playerposlist[playery])`. Finally, we need a dot of radius 20 and color #ABCDEF. We can do this with `player.dot(20,"#ABCDEF")`. It should now look like this: ```python player.clear() player.speed(0) player.up() player.goto(playerposlist[playerx],playerposlist[playery]) player.dot(20,"#ABCDEF") ``` Now, just put a call to drawplayer() below the drawplayer() function. If you press play, the boxes should draw and the player should go to the spot that is 4 up and 4 left from the bottom left corner. # IX - Boxcheck ___ Now, if our player has spawned on or moves onto a box, we want it to be collected and disappear. To do that, we're going to need to create a variable tracking the number of `boxes`. Since we have 3 boxes in this example, `boxes` should equal 3. Now, it's time to create a function for checking the boxes called `boxcheck`. The very first line needs to declare that we are using the global versions of `boxes` and of each box's grid coordinate variables (`boxZgridx`, `boxZgridy`). Then, we just need to repeat 5 lines of code for each box (replacing Z with the proper box number): ```python if playerx == boxZgridx and playery == boxZgridy: boxZ.clear() boxes -= 1 boxZgridx = boxZgridy = -1 ``` What this will do is check the player's position against the box's position, and if it's the same it will remove the box and decrement the number of boxes remaining, and then 'put' the box somewhere it can't be counted again. We need to put a call for `boxcheck()` in the beginning of the `drawplayer()` function. After you have this code block for each box, we just need to check `if boxes == 0`, and if it does, then we need to call a new function: # X - `win()` ___ Now, to make our win function, we need one more global variable - `haswon`. Declare it to be 0. Then, create a new turtle called `winner` and hide it. When the player wins, we're going to tell them they won and move their player out of bounds so they stop moving. So, now create the `win()` function. Inside this function, we need to access the global variables `haswon`, `playerx`, and `playery`. Then, we should print something to the console telling the player they have won - something like `"You won!!"`. Then, we need an if to check if the win() function has already run. We do this by checking `if haswon == 0`. Inside this if, we need to first set `haswon` to 1. This prevents it from running this section of the code again if `win()` is called again. Next, we need to set `winner`'s speed to 0 and have it pick up the pen. Then, we're going to draw our 'YOU WIN!' message. To do that, we're going to need an array called `winlist[]`. In it, we need to have one string for each character (we can ignore the leading or ending spaces). Since we want to say 'YOU WIN!', we need 8 strings, each with a character from that in it (so "Y", "O", "U", etc.). Then, we will need a loop that loops 8 times, and each iteration will draw one character. For my loop, I used o as the iterator. Now, let's create the code to draw each letter. We're going to have `winner` goto `xlist[o+1]` (because it's 8 characters on a 10 square grid) for the x position, and `xlist[5]` for the y position. Then, we need to draw each character using `winner.write()`. This function recieves 4 arguments - what to write (`winlist[o]`), whether or not to move (leave this on `False`), the alignment of the text (`align="left"`), and the font information (`font=("Arial",40,"Normal")`). So, the final write command should look like this: ``` winner.write(winlist[o], False, align="left", font=("Arial",40," ``` Finally, out of the loop, we need to set `playerx` and `playery` to 10 and redraw the player. Now, if you run this, if you won, you'd see that Y and W are not centered. The simple fix to this is to put the `winner.goto()` statement inside an else, and have 2 if statements before: one `if o == 0:`, and one `if o == 4:`. Inside the first, we're going to use `winner.goto(xlist[o+1]+2,xlist[5])`, and inside the second, we're going to use `winner.goto(xlist[o+1]-5,xlist[5])`. Now, if you run it and won, you'd see that the Y and W ARE centered. However, we should probably make it so that you can actually... play the game. # XI - User input ___ To get user input, we're going to need to create 4 basic functions. Each one will be very similar, except for a few number changes. The first is `up()`. This will need to declare the `global playery`. Then, you just have a simple if: `if playery < 9:`, which will check to make sure the player isn't at the top of the map. Inside the if, we just need to add one to `playery` and call `drawplayer()` again. The same will be done for all three other methods, with slight changes. `down()` will still `global playery`, but will instead check `if playery > 0 and playery < 10:`. This is because the player gets put at playerx and playery position (10,10) at the end of the game, and we want them to no longer be able to move. Inside the if, we're going to decrement instead of increment the `playery` value, and we're still going to `drawplayer()`. For `left()`, we need to `global playerx` instead of `playery`, and the if will reflect this change. In fact, `left()` is the same as `down()` except you have to replace each occurance of `playery` with `playerx` and the name is changed. The same can be done for `right()`, where you can just copy `up()` and replace every occurance with `playery` with `playerx` and change the name. After you have done this, you still need a way to intercept the user input. We need to add keylisteners for 8 keys: Up, Down, Left, Right, W, A, S, and D. This will be done using the `window.onkey()` function, which takes 2 parameters: the function to call, and the key to listen for. The latter has to be passed to the function as a string. So, we're going to have 8 different onkey statements. To save time explaining, I will just paste them here: ``` window.onkey(up, "Up") window.onkey(up, "W") window.onkey(down, "Down") window.onkey(down, "S") window.onkey(left, "Left") window.onkey(left, "A") window.onkey(right, "Right") window.onkey(right, "D") ``` This will call the appropriate function for each keypress. Finally, to make this work, we just need to add 2 lines to the bottom of the code: `window.listen()` and `windown.mainloop()`. # XII - Conclusion And with that, you should be done! If you press play, you should now have a functioning game. Now, if you want to, you can apply the principle learned in **X - `win()`** to add in an introduction to the game, like in my example, but that is not necesary. If you enjoyed this tutorial, be sure to upvote it. If you want to make a fairly simple random spiral generator with python, go [here](https://repl.it/talk/challenge/Python-Turtle-Graphics-Random-Spirals/7651). If you want to check out my crash course on LOLCODE, go and click on this cat head [(or here)](https://repl.it/talk/challenge/A-Crash-Course-in-LOLCODE/7714) [🐱](https://repl.it/talk/challenge/A-Crash-Course-in-LOLCODE/7714)
0
posted by minermaniac447 (61) 18 days ago
21
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**
10
posted by IEATPYTHON (133) about 1 month ago
10
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 **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 **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} ```
3
posted by Scoder12 (9) 17 days ago
16
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. #### 👩‍💻 Acknowledgements * Thanks to everyone who helped to test this (both you guys and a few of the members of the Programming Club at my high school). * Also, Kode W/ Klossy for teaching me the basics of Ruby myself! KWK is honestly the reason I like Ruby so much. * Finally--the Repl.it Discord server! I know, I know--Stack Overflow exists--but the Discord server has helped me out of plenty of coding mistakes and other bugs while being incredibly supportive despite my sometimes silly errors. Thank you!
4
posted by 21Miya (21) 30 days ago
39
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)!
5
posted by MikeShi42 (85) 2 months ago
54
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!
24
posted by ericqweinstein (100) 3 months ago
10
Making a Loot Box Calculator using Python (Rocket League)
If you currently play any number of well-known video games today, you are likely familiar with the idea of loot boxes. For those who may be unaware, a loot box is an in-game chest that will randomly give you one or more items that can only be acquired through those means. It honestly acts very similarly a pack of trading cards and like trading card packs, the main way to receive these loot boxes, (or at least open them) is buy paying for them with real money. However, unlike trading card packs, which tend to have at least one card of the highest or second highest rarity in each pack, most loot boxes don’t, if any do at all. This can lead to frustration as the most rare items are often the most sought after, meaning they most likely require more and more money to be spent if you hope to get it and if you don’t know how likely you are to get it, you may end up spending more money then you’d probably want to. However, for at least some loot boxes, we can figure out the odds of getting specific items, and in turn, find out around how much we would spend if we kept going for it. That is what we’re going to do today. We’re going to create a calculator that factors in all the statistical odds of getting the loot box item that you want. And while every loot box is different, most of the same principles can be applied regardless of what game you’re trying to calculate for. So, let’s get started. For my example I am going to be using the game Rocket League and their loot box: “Crates.” # Step 1: Getting the Odds In order to even begin you need to be able to know the odds of each specific factor that may have an effect on the final calculation. That means that some research is required on our part. Fortunately for our example, Psyonix, the makers of Rocket League, have released almost all of the information we need, and for the rest, we can easily find that out on our own. So, what are these odds? First, each item has one of 5 rarities. These are: Rare, Very Rare, Import, Exotic, and Black Market. Second most of the items can be “painted.” This simply means that it can have a different color scheme then the item would normally have otherwise, and this spectrum has a maximum of 13 different colors. Not all items can get every color, but for our equation that factor is not that big of a deal. Third, the item can be “certified.” Each item in the game will track one of serval stats that you gain with that item, but certification means that the item will track a stat it wouldn’t normally track, and like the paint colors, it comes in a maximum of 15 certifications, and not all items can have every one. However, the game’s community has determined, overall, that some certifications are better than others, and have put them into a list of 5 tiers, with Tier 1 having one certification, Tiers 2-3 having 3 each and Tiers 4-5 having 4 each. This is how we’ll divide this portion of our equation once we get there. Finally, we need to know how many items of matching rarity to the item the player wants exists in that crate. Luckily for us, we can make the person using our calculator enter that all by themselves. Now, I know that is a lot of info for anyone who is unfamiliar with Rocket League or how their loot boxes work, but we can now apply the odds Psyonix has given to us, and the ones we find ourselves. # Step 2: Doing the Math Since we have all this info now, we can simplify this info into an algebraic equation. The equation would go like this: ``` final = (rare * paint * specific * certified * tier)/quantity ``` Let’s quickly break down each variable: final: The final number we are looking to get before we turn the number into a percentage or use it to find the total “cost” of getting the item. rare: The rarity of the item we’re looking for. paint: Is the item “painted”? Yes or no? That’s it. specific: How many specific colors is the person looking for if the item is painted? 1? Any of the 13? Or anything in between? certified: Like paint, we just want to know if the item is or isn’t certified. tier: Which of the 5 tiers does our certified item fall into. and finally, quantity: How many items of like rareness exist in the crate. Now that we have our equation, we need to know the what the exact odds for each variable is. For the items rarity, the spread of percentages goes like this: 55%, 28%, 12%, 4%, 1%. The 55% is for the least valuable “Rare” items, while the 1% is the most valuable “Black Market” items. These percentages represent the likeliness of getting an item of that specific value regardless of what the actual item is. For the chance of an item being painted or certified, it’s a 25% chance for both, there are a max of 13 different colors for painted items, and 5 different tiers for certified ones. Lastly, the quantity of items of matching rarity change from crate to crate, so that number must be added by whomever is using our calculator. At this point we have both our equation and the numbers needed to fill in the variables, so we have the ability to calculate these odds on our own. That means the next step is actually making our calculator. # Step 3: Programming the Calculator Since we have all the info we need to get started, the programming of this calculator is actually a lot simpler than it may seem. For this example I’ll be using the Python language, but this can be done using other languages like Javascript. We are going to use 3 main components for this calculator: (1) Lists, (2) Dictionaries, and (3) User inputs, but the first thing we want to add to our code is this: ```python import Math ``` We want to do this, so that at our end product is a little bit cleaner than it might otherwise be, as we’ll be rounding a couple of numbers at the end. Our next step is to create lists with all the possible percentages for each variable, excluding quantity, as again, that is inputed by the user of the calculator. While these aren’t the best names to use for variables, I used the first letter of each variable in our final equation to store the percentages in a list, r for rare, p for paint, s for specific, etc. We also want to store each percentage in its decimal form, so instead of storing 55% in the list, we would store .55. Our lists should end up looking like this: ```python r = [.55, .28, .12, .04, .01] p = [.25, 1] s = [.08, .15, .23, .31, .38, .46, .54, .62, .69, .77, .85, .92, 1] c = [.25, 1] t = [.07, .2, .2, .27, .27, 1] ``` You’ll notice that most of the lists’ final value is 1. This is so that if there is nothing specific in done to that variable it won’t mess up our equation. For example, if the item they want is painted, but they don’t care which color, the specific variable will fill-in 1 in its place to make sure that the final number is correct. You may also notice that the lists s and t have percentages in them, but we never found those numbers specifically. These numbers were found through divided up one number by the maximum possible results. For example, if someone wants only one specific color for their painted item, the percentage of getting that number would be 1/13 (with 13 being the max number of colors) which equals .08 or 8% if they wanted 2 it’d be 2/13 = .15, and so on. Similarly, as discussed earlier, each tier either has 1, 3, or 4, certifications in them out of the maximum 15, so each tiers percent is based on how many certifications were in the tier divided by 15. Again, the 1s exist in case they are fine with all colors (which would be 13/13) or they didn’t care about the certification tier (15/15). Now that we have all our lists, we can make our first dictionary. Since we already have our equation in a certain order, it makes sense, that we start with a dictionary for rareness, and end with our one for tiers. Now, making each dictionary is actually pretty simple. All we need to do is assign each possible user answer with the correct index of the matching list. For example, if the user inputs “Exotic” as the rarity, we want it to index our “r” list so that it comes up with the result of .04 or 4%. Remember, the indexes start with the first value being 0, so our result for the “Exotic” input should be r[3]. Filling everything in, our dictionary looks like this: ```python rarity = { "Rare": r[0], "Very Rare": r[1], "Import": r[2], "Exotic": r[3], "Black Market": r[4], } ``` Each of our following dictionaries will look very similar, with the only differences being what the user is able to input, (like numbers for how many colors/tiers, of Y/N for any Yes or No question) and how many possible results there will need to be (like 13 for colors which would be indexed as s[12]). Before we can add the rest of the dictionaries, we need to make it so that our calculator can correctly access the part of the list that we need it to for our rarity. Luckily, it only takes 2 lines of code to do that. ```python rareness = input("Choose rarity: ") rare = rarity[rareness] ``` This allows us to easily access our dictionary and grab the correct result before it replaces the rare variable in the final equation. We can now do the same thing with our next variable of paint. ```python is_it = { "Y": p[0], "N": p[1], } painted = input("Is this item painted? Y/N?") paint = is_it[painted] ``` Personally, since we want our input to be either Y for yes or N for no, it should be specified in the question itself so that our user doesn’t input something incorrect and break our calculator before they get halfway through. We’ll end up doing the same thing when we ask if the item if certified or not. Now, our next variable is color and while we will and the dictionary like normal, to get the correct number for our variable, we’re actually going to use and if-then statement. Why? Well, if the item they want is not painted, our calculator should skip the question of color entirely. If it doesn’t, our final result will be incorrect. So, how would we do this? Well, if the item is painted, (meaning the result indexed in our paint variable was p[0]) we want it to as the question and get its result as normal, otherwise, we want it to make the variable simply equal 1. It would look like this: ```python color = { "1": s[0], "2": s[1], "3": s[2], "4": s[3], "5": s[4], "6": s[5], "7": s[6], "8": s[7], "9": s[8], "10": s[9], "11": s[10], "12": s[11], "13": s[12], } if paint == p[0]: specifics = input("Are you looking for any specific colors? How many? (Max:13)") specific = color[specifics] else: specific = 1 ``` (Again, not the best variable names, I know) Running this code, the computer will ignore the question of color if our item is not painted, and we do that same thing if our item is not certified, making sure that it doesn’t ask for a specific tier. ```python certification = { "Y": c[0], "N": c[1], } item = input("Is the item certified? Y/N?") certified = certification[item] skills = { "1": t[0], "2": t[1], "3": t[2], "4": t[3], "5": t[4], "Any": t[5], } if certified == c[0]: tiers = input("What type of certification? (For Tiers 1-5 enter that number, if any tier write Any)") tier = skills[tiers] else: tier = 1 ``` And that’s it for our dictionaries, the last things we need to do is get the quantity of the items of matching rarity, put our equation from the beginning into our code, and printing the result both in percentage form, while also telling them how many crates need to be opened, on average, before they get their item. Since you earn crates in Rocket League, but open them by buying an item call “keys,” we’ll tell them how many keys they would need to buy on average. First, the quantity. To get the quantity, we simply use the same input function as we’ve been using throughout, but if we just do that, it will recognize the number as a string, rather then a number. To fix this, we simply put our input function inside of an int() function changing the number from a string to an integer. Next with just add our final equation into the code. The resulting code should look like this: ```python quantity = int(input("How many items of matching rarity are in your crate?")) final = (rare * paint * specific * certified * tier)/quantity ``` Last but not least, we need to print out the result to our user. We use a simple print statement for this, while also using string concatenation to add our results into a nice looking sentence. Here’s how my last line of code looks. `print("There is a " + str(round(final*100, 2)) + "% chance that you will get your desired item. On average, it'll take " + str(math.ceil(1/final)) + " keys to get the item you are looking for.”)` You’ll notice that the first number is rounded, and after the *100 (in order to make our result a proper percent) there is a 2. This makes it so that our number doesn’t ever go past the second decimal point. This is done so that it gives off a cleaner look. You’ll see that the second number has “math.ceil” before it. This rounds the number up, no matter how small the decimal point may be, so the we get a full round number for the number of keys the person would need. And that’s it! We have made a functioning calculator that determines the odds of getting specific items from crates in Rocket League. Try out the end product of what was made down below. Play a game that also uses loot boxes? Why not try to make a calculator for it? # Tips for Making Your Own Calculator 1. Remember that many of the principles behind the calculator will be the same no matter what game you are using it for. So long as you can get all the numbers that you need, and can create an equation that will provide the correct answer, you pretty much have everything you need to be able to make a calculator yourself. 2. Use better variable names than I did. I know that my variable names were not very good as many of them were too similar to each other. I recommend avoiding doing what I did in this regard as it could end up causing errors if you make just a simple typo. 3. Keep it simple! I spent months trying to get this calculator to work, and I just couldn’t do it. The problem? I was trying to make it too complex. I was trying to do something that was way above my current skill level. It wasn’t until about a week ago that I realized I could simplify it way down and actually make a working end product. So don’t overcomplicate it. That is it for this tutorial. I want to thank everyone who read this, as this is my first time entering a competition like this, so I don’t have a real gauge to know how well I did with it. So again, thank you for sticking through until the end, and I hope that you all enjoyed and could use this information in one way or another. -Aloeb83
6
posted by Aloeb83 (25) 28 days ago
14
Infinite Sine Wave in Python (really simple)
In my university they made engineers write a program in C (programming language) that prints out the **sine wave**. Many of my friends do engineering and they all told me about their "beloved" assignment. It was about 8 p.m. and I was really bored... so I decided to do it myself but in Python (because I'm a lazy @ss). If you are interested, I am going to walk you through the process of this creation. First of all, we have to `import` 3 useful functions from Python's standard library. ```python from math import sin, radians from time import sleep ``` + `sin()` function returns the numerical (float) value of any angle **in radians**. We don't want to deal with those nasty radians (or at least I don't), so we import... + ...`radians()` function that converts normal angles like 45°, 90°, 180° etc. into **radians**. As you may have guessed already, we are going to feed this value in radians to the `sin()` function. + `sleep()` function allows us to slow down the printing of our sine wave by **halting** the program for a given amount of seconds. Computer calculates those values too fast and so we need to make it pause for a few milliseconds in order to see what it's printing. Now that we have all those necessary functions, we can start coding for real. Python prints data into the Terminal line by line, so our graph will be vertical, top-to-bottom in direction. ![demo1](https://storage.googleapis.com/replit/images/1539534227150_13d2481795ad20410ed9e1cff5610113.pn) We also want our wave to be infinite so we are going to write a function `wave()` that prints out just one cycle of a sine wave -180 to 180 degrees and then we'll put it into the `while True` loop to make it repeat itself forever (or until you stop it by closing the Terminal window or pressing `Ctrl + C` known as *Keyboard Interrupt*). Therefore, this is the layout of our script: ```python from math import sin, radians from time import sleep def wave(): # PLEASE IMPLEMENT ME! while True: # let the FUN last FOREVER wave() ``` > And we are almost there! Only 5 additional lines of code to go. One cycle of our sine wave includes all the angles starting at -180° and finishing at 180°. All those angles will have to be processed one by one. When I say these words, they instantly remind me of a `for` loop and it is exactly what we need here. ```python # concentrating on the wave() function now: def wave(): for a in range(-180, 180): # 'a' stands for 'angle' # 1. process angle somehow # 2. print angle at the beginning of line # 3. print some spaces ending with * # 4. sleep() for some time to slow down the printing ``` That's all we've got to do now. The first line is objectively the hardest bit here. It took me quite a bit of time to figure it out. Basically, our idea is that Terminal's space is divided into many lines and each line has many rectangles **equal in size**, each rectangle can hold one symbol; in our case we are only interested in spaces `_` and asterisks `*`. Sine wave ranges from -1 to 1 on the `y` axis. We will set this graph's maximum value to be 100 rectangles wide *excluding the angle value at the beginning of every line* (it is going to be the rightmost asterisk in our graph). Its 0 value will be right in the middle of the line and its -1 value will be the leftmost rectangle. ![demo2](https://storage.googleapis.com/replit/images/1539534199016_bc89403a39140f578414c775d3149150.pn) What we are really calculating here is the number of spaces in every line before the asterisk. This number of spaces increases and decreases with the sine value of the angle. Long story short, let's write this line already. Line 1: We've got to find the `sin()` for the angle `a` that is given by the `for` loop. This value we will store in a variable called `s` for `sine`. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = sin( radians(a) ) ``` Line 1: If we open the Terminal, run Python interpreter, import `sin()` and `radians()` functions, we can see the format of output. ```powershell Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from math import sin, radians >>> sin(radians(45)) 0.7071067811865475 ``` Line 1: We need to convert this value into an integer between 0 and 100 that is going to represent the number of spaces for each specific line. To do this, we multiply this ridiculous `float` by a 100 and display the result to 2 decimal places. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = "{:.02f}".format( sin( radians(a) ) * 100 ) ``` Line 1: Now, `s` is a `str` that looks like a `float`, but we want the `float` so we wrap all this into `float()` function. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ``` Line 1: However, we actually need an integer, not a `float`, so we wrap it all again into the `round()` function. ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) ``` Line 1: And the last thing for this line (I promise) is we need to divide this number by 2 because we have negative values as well, so both positive and negative side will be 50 spaces wide. Here we are, the first line is ready! ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 ``` > Now we simply need to use this value to print out the graph. Line 2: First things first, we want to know what angle each line represents, so... ```python def wave(): for a in range(-180, 180): # 'a' stands for 'angle' s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") # for those who aren't familiar with this syntax # this line is equivalent of # print( "{} degrees:".format(a), end="\t" ) ``` Line 3: Print `(s + 50)` spaces. The idea behind `s + 50` is that our `0` point must be in the middle and negative numbers must take up first 50 spaces, so we push every `s` by 50 spaces to the right. Note that negative numbers simply subtract from 50 and are therefore going to be placed left-of-center. ```python def wave(): for a in range(-180, 180): s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") print( (s + 50) * " ", end="*\n" ) ``` Line 4: Last one and the easiest one. Just halt the process for 0.01 seconds to slow it down a bit. ```python def wave(): for a in range(-180, 180): s = round( float( "{:.02f}".format( sin( radians(a) ) * 100 ) ) ) // 2 print(f"{a} degrees:", end="\t") print( (s + 50) * " ", end="*\n" ) sleep(0.01) ``` Voila! Our `wave()` function is ready and the script is now complete.
5
posted by sharpvik (29) about 1 month ago
12
Beginner Guide to Creating a Website Using Python!
Hey everyone, check out my tutorial [here](https://aryaboudaie.com/python/technical/educational/web/flask/2018/10/17/flask.html) on how you can make a website using beginner Python knowledge, using the web framework Flask! Please take a look and let me know what you think :) Here is the end product websites! Next time I'll make something more exciting as well: https://repl.it/@misingnoglic/session-flask-test https://repl.it/@misingnoglic/factors-with-Jinja2-Template
2
posted by misingnoglic (12) about 1 month ago
4
Quicksort tutorial: Python implementation with line by line explanation
Hey all, I wrote a tutorial to help you understand the Quicksort algorithm. https://www.codementor.io/garethdwyer/quicksort-tutorial-python-implementation-with-line-by-line-explanation-p9h7jd3r6 Would love to hear any feedback or requests for more tutorials. Drop a comment below.
0
posted by GarethDwyer1 (45) 6 days ago
7
Coin Flipper with Sound using HTML and JavaScript
This tutorial will teach you how to make a very simple Coin Flipper using HTML and Javascript. This program is so simple to make, it can be completed in around 5-10 minutes at most. The first obvious step is to open a HTML/CSS/JavaScript Repl. Doing so will mean that about *90% or more* of the HTML is already done for us, meaning we only have to add two simple lines inside the body of the HTML file to add a couple of buttons. Before we do that, however, we want all needed files and folders to be in the right place. Now, again, the Repl will really already have this done for us, but personally I like to put the CSS and JavaScript file into a static folder, as that is how I was taught, though you shouldn't need it. If you choose to do this, simply add a folder called "static", move the CSS and JavaScript files into that folder and then make sure that the paths to both files is correct by adding "static/" before style.css in the href on line 7, as well as before script.js in the src of line 12. We also want to add a "sounds" folder to our Repl making sure it's in our static folder if we have one created. With that out of the way, let's get to the coding. We'll start with the HTML as it is by far the simplest. For the HTML, we simply need to add two button tags inside the body tag. One will flip the coin, while the other will remove the coin image, so we can flip it again. The code will look like this: ```html <button id='coin-flip'>Flip Coin</button> <button id='reset'>Reset</button> ``` It is important that each button has a unique id so that we can link these buttons to our JavaScript. Besides that, that's it for our HTML. We just need to add the JavaScript logic, so let's do that. We'll first add this line of code: ```js let coinFlipper = { 'coinSide': ['H', 'T'], } ``` This will allow the computer to pick whether the coin lands on heads or tails and will randomize it a little later on. For now, we want to add the sound next. Before we can do that, we need to get a sound file. I found a simple file called coinfilp.mp3, downloaded it, and dragged the file into the sounds folder on my Repl. We can now use a "let" function to "create" a new Audio variable and associate the sound file with it so we can use it later in the Flip Coin button's function. ```js let coinFlipSound = new Audio('static/sounds/coinflip.mp3') ``` Next we add two Event Listeners, so that the proper functions take place when we click either button. For this program, I named the functions "coinFlip" and "reset." ```js document.querySelector('#coin-flip').addEventListener('click', coinFlip); document.querySelector('#reset').addEventListener('click', reset); ``` We now can create the two functions for our buttons, as well as one we'll need to make the result random. First, the reset function. It's very simple and only serves one purpose, removing the coin image so that our screen doesn't become flooded with them if we flip the coin multiple times. This function is still tied to a button, remember, so we will have to click it before we flip a second time. ```js function reset() { document.querySelector('img').remove(); } ``` All this line of code does is look for an Image and removes the image it finds if it finds one. The next function we'll create is the one that will randomize the result. It'll end up looking like this. ```js function randomCoin() { let randomIndex = Math.floor(Math.random() * 2); return coinFlipper['coinSide'][randomIndex]; } ``` That first line allows the computer of either 0 and 1. We do this because arrays are indexed starting with the value of 0 for the first item, and then 1 for the second, and so on. By using Math.floor, we also make it so that the number is not a decimal and Math.random is how it picks the result. We then make sure that the value it chose is returned to us when we run the function later. Last but not least, the actual coin flip function. I'm going to go over the function line by line, as it is the longest one. It looks like this: ```js function coinFlip() { coinFlipSound.play(); let coin = randomCoin(); let coinImage = document.createElement('img'); if (coin === 'H') { coinImage.src = 'https://random-ize.com/coin-flip/us-half-dollar/us-half-dollar-front.jpg' setTimeout(function() { document.querySelector('body').appendChild(coinImage); }, 1000); }else if (coin === 'T') { coinImage.src = 'https://random-ize.com/coin-flip/us-half-dollar/us-half-dollar-back.jpg' setTimeout(function() { document.querySelector('body').appendChild(coinImage); }, 1000); } } ``` The first line simply plays back the audio we set earlier regardless of what the result is. The next line allows us to set our random function as a variable to use in an if statement, while the third allows us to add an image tag to our HTML when the button is clicked. Next is our if statement. It simply tells the computer that if our random result equals "H" or heads, to set the image source to a picture of a coin with heads side facing up. The images I used we're simply found online, with the image address used so that the computer can locate the image. If the result isn't heads, however, the else if statement kicks in and posts a picture of the tails side instead. To actually post the image, we are using this line of code, to tell the computer to put the image inside the body tag. ```js document.querySelector('body').appendChild(coinImage); ``` However, instead of posting just that line, you'll see it's inside of a setTimeout function. This allows us to prevent the picture from showing up, until the time we want it to show up (in milliseconds). The time of the audio clip is about a second, so having it wait 1000 ms does the trick for us. # **And that's it!** You could of course do more with this, like using CSS to style the buttons, make the image a certain size, or add a background. However, we were able to make this program with only *two* lines of HTML that we wrote ourselves, *three* JavaScript functions, and only *five* additional lines outside the functions themselves. Thank you so much for reading this tutorial, I hope you enjoyed it. If you have any sort of feedback on it, please leave it in the comments, I'd love to hear it. -Aloeb83
4
posted by Aloeb83 (25) 23 days ago
18
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!
0
posted by ericqweinstein (100) about 2 months ago
11
Solve any Quadratic Equation (HTML, CSS, JS)
If you are lazy like me, it won't hurt you to just create this little app and solve all the quadratics with it instead of factorizing every damn time... so let's begin. First things first, let's prepare our basic HTML backbone: ```html <!-- This file is: index.html --> <!DOCTYPE html> <html> <head> <title>Quad</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <!-- HTML elements go here --> <script src="script.js"></script> </body> </html> ``` Now, we'll need a header `h1`, few `input` fields, submit `button`, and `div`s to display answers. ```html <!-- This file is: index.html --> <!DOCTYPE html> <html> <head> <title>Quad</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <h1>Solve Any Quadratic Equation</h1> <div id="input"> <input id="a"> x<sup>2</sup> <input id="b"> x <input id="c"> = 0 </div> <button id="submit">Solve</button> <div id="answers"> <p id="DIS"></p> <p id="NOS">No solutions</p> <p id="S1"></p> <p id="S2"></p> </div> <script src="script.js"></script> </body> </html> ``` I put them in `div`s so it's easier to manipulate their CSS styles. Our `input`s are going to be filled with the **coefficients** for the quadratic, `#DIS` is going to display the **discriminant**, `#NOS` is a single line that says "No solutions" (we are going to only make it visible when there are no real roots), `#S1` & `#S2` are going to hold the answers. > The HTML portion of our code is now complete. Let's add some styles now: ```css /* This file is: style.css */ h1 { font-family: Arial, Calibry, sans-serif; margin-bottom: 30px; } body { font-family: Georgia, serif; text-align: center; } input { text-align: center; width: 80px; font-size: 28px; } #input { font-size: 28px; } button { margin: 30px auto; padding: 10px 15px; background-color: blue; border: none; color: white; cursor: pointer; } #NOS { display: none; } ``` I recon I don't need to explain anything here since these are just styles. You can change these as you like. I didn't make it too fancy because why would I, but if you want to, you can "sweat" a bit. > The only important part is to make `#NOS` `display: none` since we only want to display this one when there are no real roots. The last and the main thing we need is some JavaScript magic to make it work. I am not going to use JQuery just because this app is too small and we can actually deal with it without any external help, so first of all I'll write 2 functions to replace some of the JQuery's functionality. ```javascript /* This file is: script.js */ function getID(i) { return document.getElementById(i); } function getVal(i) { return getID(i).value; } ``` Now that we have `getID()` and `getVal()` in place, we can code for real. What we want is this: whenever user would press the `#submit` button, we want to do execute some function `solve()`. To do so, we are going to add an event listener to the button and also let's declare an empty (for now) function `solve()`. ```javascript /* This file is: script.js */ function getID(i) { return document.getElementById(i); } function getVal(i) { return getID(i).value; } function solve() { // IMPLEMENT ME, PLEASE! } var submitButton = document.getElementById("submit"); submitButton.onclick = function() { solve(); }; ``` > This is the backbone of our JS. Now let's `solve()` it. Before anything else, we have to fetch those coefficients, so let's get to it: ```javascript /* Focusing on the solve() function */ function solve() { var a = parseInt( getVal("a") ), b = parseInt( getVal("b") ), c = parseInt( getVal("c") ); if ( isNaN(a) ) { a = 1; } if ( isNaN(b) ) { b = 0; } if ( isNaN(c) ) { c = 0; } } ``` Last 3 lines with `if ( isNaN(x) ) { x = ... }` ensure that we don't have a `NaN` type inside `a`, `b`, or `c`. The next thing to do is calculating the discriminant. Discriminant is always equal to `D = b*b - 4ac` ```javascript /* Focusing on the solve() fucntion */ function solve() { var a = parseInt( getVal("a") ), b = parseInt( getVal("b") ), c = parseInt( getVal("c") ); if ( isNaN(a) ) { a = 1; } if ( isNaN(b) ) { b = 0; } if ( isNaN(c) ) { c = 0; } var D = b*b - 4 * a * c; } ``` Let's declare some more variables and set everything to its initial state (e.g. `#S1` & `#S2` must be empty before we display any solutions and `#NOS` must be reset to `display: none` every time the `#submit` button is pressed): ```javascript /* Focusing on the solve() fucntion */ function solve() { var a = parseInt( getVal("a") ), b = parseInt( getVal("b") ), c = parseInt( getVal("c") ); if ( isNaN(a) ) { a = 1; } if ( isNaN(b) ) { b = 0; } if ( isNaN(c) ) { c = 0; } var D = b*b - 4 * a * c; var dis = getID("DIS"), nos = getID("NOS"), s1 = getID("S1"), s2 = getID("S2"); nos.style.display = "none"; s1.innerHTML = ""; s2.innerHTML = ""; dis.innerHTML = 'Discriminant = <span id="D"></span>'; var d = getID("D"); } ``` Now that all the helper variables are put in place, we can start displaying the answer. First of all, let's display the discriminant. After we do that, we have three options depending on its value: + D is smaller than 0 --> no real roots + D is equal to 0 --> one root + D is greater than 0 --> two roots ```javascript /* Focusing on the solve() function */ function solve() { var a = parseInt( getVal("a") ), b = parseInt( getVal("b") ), c = parseInt( getVal("c") ); if ( isNaN(a) ) { a = 1; } if ( isNaN(b) ) { b = 0; } if ( isNaN(c) ) { c = 0; } var D = b*b - 4 * a * c; var dis = getID("DIS"), nos = getID("NOS"), s1 = getID("S1"), s2 = getID("S2"); nos.style.display = "none"; s1.innerHTML = ""; s2.innerHTML = ""; dis.innerHTML = 'Discriminant = <span id="D"></span>'; var d = getID("D"); d.innerHTML = D.toString(); if (D < 0) { // no real roots // display #NOS } else if (D == 0) { // one root equal to // S = -b / (2a) } else { // two roots equal to // S1 = (-b + √D) / (2a) // S2 = (-b - √D) / (2a) } } ``` > Last step and we are all set! Let's just replace comments with real code! ```javascript /* Focusing on the solve() function */ function solve() { var a = parseInt( getVal("a") ), b = parseInt( getVal("b") ), c = parseInt( getVal("c") ); if ( isNaN(a) ) { a = 1; } if ( isNaN(b) ) { b = 0; } if ( isNaN(c) ) { c = 0; } var D = b*b - 4 * a * c; var dis = getID("DIS"), nos = getID("NOS"), s1 = getID("S1"), s2 = getID("S2"); nos.style.display = "none"; s1.innerHTML = ""; s2.innerHTML = ""; dis.innerHTML = 'Discriminant = <span id="D"></span>'; var d = getID("D"); d.innerHTML = D.toString(); if (D < 0) { nos.style.display = "block"; } else if (D == 0) { var S = -b / (2 * a); s1.innerHTML = S.toString(); } else { var S1 = ( -b + Math.sqrt(D) ) / (2 * a), S2 = ( -b - Math.sqrt(D) ) / (2 * a); s1.innerHTML = S1.toString(); s2.innerHTML = S2.toString(); } } ``` > Our script is now finally ready. We can now solve any quadratic equation using this simple web app! Enjoy.
2
posted by sharpvik (29) about 1 month ago
17
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
7
posted by GarethDwyer1 (45) 2 months ago
6
Space shooter with HTML5 and Node.js
## Introduction Welcome to my first web game tutorial! My name is Rafael and I'm gonna guide you in this amazing code journey. First of all I'd like to say that I'm not an english native speaker, so if you happen to find typos or grammar errors, please feel free correct me ([[email protected]](https://twitter.com/racascou)). This tutorial content is stored inside the repl.it code. I suggest forking the code to save your changes. Click the "files" button for the next lessons, it's the one on the top left. Just follow each file and have fun! https://repl.it/@rafaelcastrocouto/Web-Game-Tutorial
0
posted by rafaelcastrocouto (29) 15 days ago
4
Less
# Less Less stands for Leaner CSS, and for good reason. If you know anything about CSS, this will make your life easier. First, we have to create a stylesheet. I am naming mine `style.less`. Next, we have to link the stylesheet to our webpage. Here is how we do that: ``` html <link rel="stylesheet/less" type="text/css" href="style.less"/> ``` Now that we have linked our stylesheet, we have to include some JS. Don't worry! This script is already made for us, and is readily available. All we have to do is paste the following in the `<body>`. ``` html <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.7.1/less.min.js" ></script> ``` If you happened to rename your stylesheet, just do this: ``` html <link rel="stylesheet/less" type="text/css" href="your-stylesheet.less"/> ``` # Now we are ready to start using Less! Open your stylesheet. Let's start by making our body's background a dark grey. Type the following: ``` less @bgcolor: #333; body { background-color: @bgcolor; } ``` You may be wondering > Hold on now, what's up with that there @ symbol up there? I would tell you that is a variable! Yes, a variable in CSS. Change once change everywhere. Since we have variables, could we possibly have... functions??? I would say... > __Heck yes, brother.__ # Anyway... Back to the point. That variable up there is a placeholder for #333. Or any color for that matter. Change it once up there, and it changes it __everywhere__ in the document. You should now have a fairly basic concept of variables now. They don't get much harder than that. Oh yeah, comments are made like this: ``` less // Single line /* Multiline */ ``` Say we have a `<div>`. In this `<div>`, we want to store links for a navigation bar. Watch this: ``` less .navigation-bar { max-width: 1100px; background-color: #555; a { color: white; } } ``` # Notice I put the style for the links INSIDE of the style for the `.navigation-bar`! Isn't that awesome?! It will only change the style of the links inside of that nav bar. Say I wanted all links on the page to be white, and not underlined. But on one particular instance, I wanted to add another style. Wouldn't it be awesome if there was an easy way to do that? Think no more because I have it right here: ``` less .link { color: white; text-decoration: none; } .nav-bar { .link; // Imports all style from the .link font-size: 20px; // Adds font size that was not in .link that we needed } ``` With this wealth of knowledge I have granted you, this should come easily. It should be pretty self explanatory. Now... *functions*. ``` less .link-setup (@color, @size) { color: @color; font-size: @size; text-decoration: none; } a { .link (blue, 15px); } ``` We made a function to set up links. We pass through a color for the link, and a size for the links. That's all the time I have. Any questions? Ask me in the comments. Clarification? Ask for it. Bored and wanna talk? Do it. # Goodbye.
6
posted by ChandlerMorell (56) 19 days ago
16
LISP Tutorial: Write a Language with JavaScript
Hi everyone, I wrote a little LISP in JavaScript (https://repl.it/@ericqweinstein/Lisplet) and an accompanying tutorial (https://medium.com/@eric.q.weinstein/lisp-repl-it-tutorial-9a8f2d7d7584). I hope you like it!
4
posted by ericqweinstein (100) 2 months ago
12
Beginner web scraping with Python and Repl.it
Hey all, I wrote a beginner's tutorial on web scraping using Python on Repl. You can find it here https://www.codementor.io/garethdwyer/beginner-web-scraping-with-python-and-repl-it-nzr27jvnq I'll be working on a more advanced one soon if this one is too easy!
3
posted by GarethDwyer1 (45) about 2 months ago
Load more