Thursday, September 30, 2021

Random walks in Python

 

Random Walks in Python using Matplotlib

In this blog, we’ll use Python to generate data for a random walk, and then use Matplotlib to create a visual representation of that data. A random walk is a path that has no clear direction but is determined by a series of random decisions, each of which is left entirely to chance. Take for example the path a confused ant would take if it took every step in a random direction. Random walk models are used in many real-world situations. Here is a real-world application of random walks.

Importing the modules

For this, we require two modules; Matplotlib and Random

import matplotlib.pyplot as plt

from random import choice

To make random decisions, we’ll store possible moves in a list and use the choice() function, from the random module, to decide which move to make each time a step is taken. Hence the random module.

 The RandomWalk() Function

def RandomWalk(num_points):

    x_values = [0]

    y_values = [0]

When calling the function, we will require to pass in the number of points that the random walk will make. Then, we make two lists to hold the x- and y-values, and we start each walk at the point (0, 0).

def RandomWalk(num_points):

    x_values = [0]

    y_values = [0]

 

    """Keep taking steps until the walk reaches 

the desired length."""

    while len(x_values) < num_points:

 

        """Decide which direction to go and how far 

to go in that direction."""

        x_direction = choice([1-1])

        x_distance = choice([01234])

        x_step = x_direction * x_distance

 

        y_direction = choice([1-1])

        y_distance = choice([0,1,2,3,4])

        y_step = y_direction * y_distance

 

        """Reject a move that goes no-where"""

        if x_step == 0 and y_step == 0:

                continue

 

        x = x_values[-1+ x_step

        y = y_values[-1+ y_step

 

        x_values.append(x)

        y_values.append(y)

 

Next, we set up a loop that runs until the walk is filled with the correct number of points. The main part of the loop tells Python how to simulate four random decisions: will the walk go right or left? How far will it go in that direction? Will it go up or down? How far will it go in that direction? We use choice([1, -1]) to choose a value for x_direction, which returns either 1 for right movement or −1 for left. Next, choice([0, 1, 2, 3, 4]) tells Python how far to move in that direction (x_distance) by randomly selecting an integer between 0 and 4. (The inclusion of a 0 allows us to take steps along the y-axis as well as steps that have moved along both axes.). We need to determine the length of each step in the x and y directions by multiplying the direction of movement by the distance chosen. A positive result for x_step means move right, a negative result means move left, and 0 means move vertically. A positive result for y_step means move up, negative means move down, and 0 means move horizontally. If the value of both x_step and y_step is 0, the walk doesn’t go anywhere, so we continue the loop to ignore this move. To get the next x-value for the walk, we add the value in x_step to the last value stored in x_values and do the same for the y-values. When we have these values, we append them to x_values and y_values.

     x_values.append(x)

     y_values.append(y)

 

    """plot the points in the walk"""

    plt.style.use("classic")

    fig, ax = plt.subplots(figsize=(15,9))

    point_numbers = range(num_points)

    ax.scatter(x_values, y_values, c=point_numbers,

 cmap=plt.cm.Blues, edgecolors       ='none's=15)

    

    """Emphasize the first and last points"""

    ax.scatter(0,0c='green'edgecolors='none's=100)

    ax.scatter(x_values[-1], y_values[-1], c='red'

edgecolors='none's=100)

 

    ax.get_xaxis().set_visible(False)

    ax.get_yaxis().set_visible(False)

 

    plt.show()

We proceed to create a scatter plot using Matplotlib. First, is to specify the style that we will use. The variable fig represents the entire figure or collection of plots that are generated. The variable ax represents a single plot in the figure and is the variable used most of the time. In the ax.scatter function we pass the x and y values to be plotted. We also pass the color maps. Pyplot module includes a set of built-in color maps. To use one of these cmaps, you need to specify how Pyplot should assign a color to each point in the data set. Here is how to assign each point a color based on its y-value.

ax.scatter(x_values, y_values, c=point_numbers, 

cmap=plt.cm.Blues, edgecolors='none's=15)

Pass a list of y-values to c, and then tell pyplot which color map to use using the color map argument. This code colors the points with lower y-values light blue and colors the points with higher y-values dark blue. We also emphasize the starting points and ending points of our plot. Using green for beginning and red for the end of the walk.

RandomWalk(5000)

Finally, we call the function with the number of points we desire to be scattered on our random walk.




 


Labels: , , , , , , , , , , , , , , , ,

Wednesday, September 29, 2021

Web 3.0

 


What is web 3.0?

TechTarget defines web 3.0 as the third generation of internet services for websites and applications that will focus on using a machine-based understanding of data to provide a data-driven and Semantic Web; the ultimate goal of web 3.0 is to create more intelligent, connected and open websites.

But before we talk about web 3.0 further, let's look at the other web technologies.

Web 1.0

This is the first stage of the World Wide Web revolution (WWW) and is also referred to as read-only web. The web began as an informational place for people to broadcast their information and only allowed users to search for information and read it. There are no advertisements while surfing on the web and is mainly used for personal websites. It has static web pages and uses basic Hypertext Mark-Up Language

Web 2.0

This is basically the social web. It contains tools and platforms for people to share their perspectives, opinions, thoughts and experiences. Web 2.0 applications tend to be more interactive with the end-user. “Web 2.0 is the business revolution in the computer industry caused by the move to the internet as a platform, and any attempt to understand the rules for success on that new platform.”– Tim O’Reilly.


Web 3.0 is characterised by some exiting features; 

Semantic Web

The next evolution of the Internet involves the semantic web. The Semantic Web will improve web technologies to generate, share and combine content through search and analysis based on the ability to understand the meaning of words, not keywords or figures.

Artificial Intelligence

By combining this capability with natural language processing computers will understand information just like humans, delivering faster and more relevant results. They are getting smarter to meet the wants of their users.

3D Graphics
More information connection
Ubiquity - Content is accessible by multiple applications

There is no clear definition or unique explanation of web 3.0. I think to really understand what it is we will have to wait a while longer. Then, we shall be able to compare it with web 1.0 and web 2.0 and see the notable differences.

Labels: , , , , , , , , , , , , , , ,

Friday, September 24, 2021

Python Snake Game

 

Snake Game in Python Pygame

If you have a basic beginner’s knowledge about python then creating a snake game in python is fairly easy. This blog is supposed to bring you up to speed with python pygame and help you advance your skills in python and pygame. I am not going to use Object Oriented Programming (OOP) model instead I will be using the procedural method.

                Let’s get into it-:

For our game, we are going to need three modules, i.e. pygame, time, and random. The time and random modules are usually preinstalled but you will have to install pygame manually using the pip install pygame command.  

import pygame

import time

import random

 

We now need to initialize the game using the .init() function.

pygame.init()

Next we declare the variables required for our game. We need variables containing the colors we will use. (Colors are in RGB format). The colors are stored in tuples. We also need the width and height of both our game window and the snake in variables.

white = (255255255)

yellow = (255255102)

black = (000)

red = (2135080)

green = (02550)

blue = (50153213)

 

dis_width = 600

dis_height = 400

 

snake_block = 10

snake_speed = 5

The next step is to set the size of the game window and also the ‘name’ of the game. It is also important that we make sure the game will run smoothly across different computers. Some computers are slow and others are quick so by using the pygame.time.clock() function we make sure that the game will run uniformly across all machines.

dis = pygame.display.set_mode((dis_width, dis_height))

pygame.display.set_caption('Snake Game by Steve')

 

clock = pygame.time.Clock()

 

The next step is to initialize the fonts we are going to use in the game. Pygame has the ability to access system fonts using the pygame. font.Sysfont function.

font_style = pygame.font.SysFont("bahnschrift"25)

score_font = pygame.font.SysFont("comicsansms"35)

In the function, we give the font name as a string followed by its size as an integer.

Methods

A couple of methods are required to make sure the game runs properly.

        1. Score Method

We will need to display the score of the player as they play the game. As always pygame has us sorted out. It’s just a matter of writing down the inbuilt functions. First, we create a method called Your_Score with the parameter score. We then use the font.render() function to display the score in the game window. This creates a new Surface with the specified text rendered on it. Pygame provides no way to directly draw text on an existing Surface: instead, you must use Font.render() to create an image (Surface) of the text, then blit this image onto another surface. To blit the text, we use dis. blit(). It takes in the value(what you want to be displayed on the surface) and the location of the value. In our case, the location is point 0,0. You can change the locations to see how it changes. Note: The location should within 0 to 600 for the width and 0 to 400 for the height.

def Your_score(score):

    value = score_font.render("Your Score: " + str(score)True, yellow)

    dis.blit(value, [00])

2.  Snake Method

Next, we need to draw the snake. It will be a rectangle that increases in length as it ‘eats’. For this, we create an our_snake method. It has two parameters snake_block and snake_list. The snak_list will be expounded in the gameloop method. Inside the method, we loop the snake_list then we draw the snake using pygame.draw.rect() function. It draws a rectangle with the format rect(surface, color, rect). The parameters are as follows

  • surface to draw on
  • color (or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
  • rect -- rectangle to draw, position and dimensions
  • width (int)       

def our_snake(snake_blocksnake_list):

for x in snake_list:

pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) 

                 3. Message Method

This method takes the score method format. We create the message method with two parameters, the message and its color. In the blit function, the width and height are dived into two to make sure that the message appears at the middle of the surface.

def message(msgcolor):

    message = font_style.render(msg, True, color)

    dis.blit(message, [dis_width / 6, dis_height / 3])

   4. Gameloop method

def gameLoop():

    game_over = False

    game_close = False

 

    x1 = dis_width / 2

    y1 = dis_height / 2

 

    x1_change = 0

    y1_change = 0

 

    snake_List = []

    Length_of_snake = 1

 

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0

    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

 

    while not game_over:

 

        while game_close == True:

            dis.fill(blue)

            message("You Lost! Press C-Play Again or Q-Quit", red)

            Your_score(Length_of_snake - 1)

            pygame.display.update()

 

            for event in pygame.event.get():

                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_q:

                        game_over = True

                        game_close = False

                    if event.key == pygame.K_c:

                        gameLoop()

 

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                game_over = True

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_LEFT:

                    x1_change = -snake_block

                    y1_change = 0

                elif event.key == pygame.K_RIGHT:

                    x1_change = snake_block

                    y1_change = 0

                elif event.key == pygame.K_UP:

                    y1_change = -snake_block

                    x1_change = 0

                elif event.key == pygame.K_DOWN:

                    y1_change = snake_block

                    x1_change = 0

 

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:

            game_close = True

        x1 += x1_change

        y1 += y1_change

        dis.fill(blue)

        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])

        snake_Head = []

        snake_Head.append(x1)

        snake_Head.append(y1)

        snake_List.append(snake_Head)

        if len(snake_List) > Length_of_snake:

            del snake_List[0]

 

        for x in snake_List[:-1]:

            if x == snake_Head:

                game_close = True

 

        our_snake(snake_block, snake_List)

        Your_score(Length_of_snake - 1)

 

        pygame.display.update()

 

        if x1 == foodx and y1 == foody:

            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0

            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

            Length_of_snake += 1

 

        clock.tick(snake_speed)

 

    pygame.quit()

    quit()

This method contains the functionality of the game. It is here that we program the snake to move, increase in size after successful collision with the ‘food’ and end the game if the player hits the walls. First, we initialize a couple of variables. The snake_list is initialized in at this point.  We need to create the food particles hence the foodx and foody variables. Next, we work with two while loops. The first one checks whether the game is over and the second checks whether the game is still running. Inside the second for loop, we set the background color of the game. We also work with if statements checking for events within the game. The pygame.event.get () function allows us to use the keyboard in the gameplay. We loop through various keys on the keyboard checking whether they have been pressed (KEYDOWN). If a key has been pressed say the left arrow key, we program the snake to move to the left-hand side of the surface. We do so by increasing the left coordinate location of the snake. The same case applies to other respective keys. It is also in this for loop that we check for successful collision of the snake and the food. If a collision has occurred, we need to increase the snake size, delete the food rectangle from that location and draw it somewhere else in the game surface. The random module comes in handy at this point as it allows us to randomly draw the food. We also call the other methods that we had previously created here. If the player his the walls of the game surface, the game stops and they asked whether they want to continue playing or to quit.

We finally end the game creation by calling the game loop method.

gameLoop()


Useful links

The code on GitHub



 

 

Labels: , , , , , ,