Monday, October 30, 2023

Importance of GitHub to coders

Importance of GitHub to coders

Introduction

In the ever-evolving world of software development, tools and platforms come and go. However, one platform has not only stood the test of time but has become an integral part of a coder's life: GitHub. GitHub is more than just a version control system; it's a hub for collaboration, a showcase of skills, and a testament to the power of open-source development. In this blog post, we'll explore the importance of GitHub for coders and why it's considered a must-have tool in their arsenal.


Version Control

At the heart of GitHub's importance lies its powerful version control system. Coders use version control systems to track changes in their code, making it easier to collaborate with others, fix bugs, and roll back to previous versions when needed. GitHub employs Git, a distributed version control system, making it a versatile platform for developers. Here's how GitHub's version control benefits coders:

a. Collaboration: GitHub allows multiple developers to work on the same project simultaneously. It promotes collaboration and coordination by providing a common repository where team members can push, pull, and merge code seamlessly.

b. Code History: GitHub tracks every change made to a project. This detailed history ensures that coders can understand when, how, and why specific changes were made, which is invaluable for troubleshooting and improving code quality.

c. Branching and Merging: GitHub enables developers to create branches, allowing them to experiment with new features or fixes without affecting the main codebase. Once the changes are tested and approved, they can be merged back into the main branch.


Portfolio and Resume

GitHub serves as an online portfolio for coders. A well-maintained GitHub profile can showcase your skills and experience to potential employers, collaborators, and the wider tech community. Here are some ways GitHub contributes to your professional growth:

a. Display Your Work: Your GitHub repositories are a visual representation of your coding abilities. Share your projects, contributions to open-source software, and personal coding experiments to demonstrate your expertise.

b. Contributions to Open Source: Participating in open-source projects on GitHub allows you to collaborate with experienced developers, learn from their code, and contribute to meaningful projects. These contributions can be highlighted on your profile, demonstrating your dedication to the community

c. Resume Enhancement: Many recruiters and hiring managers consider a strong GitHub profile a plus when evaluating job candidates. It provides tangible evidence of your coding skills, teamwork, and commitment to the field.


Learning and Knowledge Sharing

GitHub is not just about sharing code; it's also a platform for learning and knowledge sharing. Here's how GitHub promotes the growth of coders.

a. Access to Open Source: GitHub hosts a vast array of open-source projects in different programming languages. This means that coders can access high-quality codebases, study them, and even contribute to projects that align with their interests.

b. Code Reviews: GitHub's pull request feature encourages code reviews, where experienced developers can provide feedback on your code. These reviews are invaluable for improving your skills and coding practices.

c. Documentation: Good documentation is essential for any project. GitHub's wiki and readme files allow coders to provide clear, concise explanations of their projects, making it easier for others to understand and use the code.


Job Opportunities

GitHub is a valuable resource for finding job opportunities and networking with potential employers. Here's how it helps coders on their career path:

a. Job Listings: GitHub Jobs is a platform where companies post job listings specifically tailored to developers. You can search for job opportunities that match your skills, experience, and interests.

b. Networking: GitHub's social features enable coders to follow and connect with others in the tech community. This can lead to valuable connections, recommendations, and job referrals.


Conclusion

GitHub is not just a code repository; it's a vibrant ecosystem that empowers coders, from beginners to seasoned professionals. Its significance lies in its ability to facilitate version control, showcase your skills, support learning and knowledge sharing, and provide job opportunities. By embracing GitHub and incorporating it into your coding journey, you tap into a world of collaborative, open-source development that can significantly advance your career and skills. If you haven't already, it's time to create your GitHub account and start your coding journey on this invaluable platform.

Labels: ,

Thursday, June 22, 2023

Video Viewer with JavaScript: Enhancing Your HTML Video Player

Video viewer with JS.✌

 Have you ever wanted to create a custom video player for your website? With the power of JavaScript, you can take your HTML video player to the next level. In this tutorial, we'll walk you through the process of building an interactive video viewer using JavaScript

First, let's take a look at the HTML code that sets up our video player:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>HTML Video Player</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="player">
      <video class="player__video viewer"
src="652333414.mp4"></video>

      <div class="player__controls">
        <div class="progress">
          <div class="progress__filled"></div>
        </div>
        <button class="player__button toggle"
            title="Toggle Play"></button>
        <input
          type="range"
          name="volume"
          class="player__slider"
          min="0"
          max="1"
          step="0.05"
          value="1"
        />
        <input
          type="range"
          name="playbackRate"
          class="player__slider"
          min="0.5"
          max="2"
          step="0.1"
          value="1"
        />
        <button data-skip="-10"
class="player__button">« 10s</button>
        <button data-skip="25"
class="player__button">25s »</button>
      </div>
    </div>

    <script src="./script.js"></script>
  </body>
</html>


This HTML structure sets up a video player with controls such as play/pause button, volume slider, playback speed slider, skip buttons, and a progress bar. Now, let's dive into the JavaScript code that brings this video player to life:

/* Get Our Elements */
const player = document.
        querySelector('.player');
const video = player.
        querySelector('.viewer');
const progress = player.
        querySelector('.progress');
const progressBar = player.
        querySelector('.progress__filled');
const toggle = player.
        querySelector('.toggle');
const skipButtons = player.
        querySelectorAll('[data-skip]');
const ranges = player.
        querySelectorAll('.player__slider');

/* Build out functions */
function togglePlay() {
  const method = video.paused
? 'play' : 'pause';
  video[method]();
}

function updateButton() {
  const icon = this.paused ?
'' : '❚ ❚';
  console.log(icon);
  toggle.textContent = icon;
}

function skip() {
  video.currentTime += parseF
loat(this.dataset.skip);
}

function handleRangeUpdate() {
  video[this.name] = this.value;
}

function handleProgress() {
  const percent = (video.curren
tTime / video.duration) * 100;
  progressBar.style.flexBasis = `${percent}%`;
}

function scrub(e) {
  const scrubTime = (e.offsetX
/ progress.offsetWidth) * video.duration;
  video.currentTime = scrubTime;
}

/* Hook up the event listeners */
video.addEventListener('click',
togglePlay);
video.addEventListener('play',
updateButton);
video.addEventListener('pause',
updateButton);
video.addEventListener('timeupdate',
handleProgress);

toggle.addEventListener('click',
togglePlay);
skipButtons.forEach((button) =>
button.addEventListener('click', skip));
ranges.forEach((range) => range.
addEventListener('change',
     handleRangeUpdate));
ranges.forEach((range) =>
  range.addEventListener('mousemo
ve', handleRangeUpdate)
);

let mousedown = false;
progress.addEventListener('click'
, scrub);
progress.addEventListener('mousemo
ve', (e) => mousedown && scrub(e));
progress.addEventListener('mousedo
wn', () => (mousedown = true));
progress.addEventListener('mouseup
', () => (mousedown = false));


In the above code, we add event listeners to the progress bar to enable scrubbing functionality. When the progress bar is clicked, the scrub function is called to update the video's current time based on the click position. The mousedown flag is used to determine whether the mouse button is being held down, allowing continuous scrubbing as the mouse moves.

That's it! With this JavaScript code, you now have an enhanced HTML video player with interactive controls and a progress bar that updates as the video plays. Users can toggle play/pause, adjust volume and playback speed, skip forward or backward, and scrub through the video using the progress bar.

Feel free to customize the styling and behavior of the video player to match your website's design and requirements - or you could use mine!. Enjoy building your own video viewer with JavaScript! 

Querying DOM Elements: The code starts by selecting various elements from the DOM (Document Object Model) using document.querySelector and querySelectorAll. These elements include the main video player container, the video element itself, progress bar elements, toggle button, skip buttons, and range sliders.


Defining Functions:

togglePlay(): This function toggles the video play/pause state by checking if the video is currently paused or playing and calling the appropriate method (play() or pause()) on the video element.

updateButton(): This function updates the toggle button's icon based on whether the video is currently paused or playing.

skip(): This function allows the user to skip forward or backward in the video by adjusting the currentTime property of the video element based on the data-skip attribute of the clicked button.

handleRangeUpdate(): This function updates the video's volume and playback rate based on the value of the range sliders.

handleProgress(): This function updates the progress bar's filled width based on the current time and duration of the video, giving a visual representation of the progress.

scrub(e): This function allows the user to scrub through the video by calculating the scrub time based on the click position on the progress bar and updating the currentTime property accordingly.

Hooking up Event Listeners:

The video element has event listeners for the following events:

click: Calls the togglePlay() function to toggle the play/pause state of the video.play: Calls the updateButton() function to update the toggle button's icon when the video starts playing.

pause: Calls the updateButton() function to update the toggle button's icon when the video is paused.

timeupdate: Calls the handleProgress() function to update the progress bar as the video plays.The toggle button has a click event listener that calls the togglePlay() function to toggle the video play/pause state.The skip buttons have click event listeners that call the skip() function to allow skipping forward or backward in the video.

The range sliders have event listeners for both change and mousemove events. When the value of a range slider changes, the handleRangeUpdate() function is called to update the corresponding video property (volume or playback rate). Additional Functionality:

The mousedown flag is used in conjunction with the progress bar's mousemove event listener to enable continuous scrubbing. When the progress bar is clicked and the mouse button is held down, the scrub() function is called continuously as the mouse moves, allowing the user to scrub through the video seamlessly.

By combining these functions and event listeners, the JavaScript code enables interactive functionality for the HTML video player. Users can play/pause the video, adjust volume and playback speed, skip forward or backward, and scrub through the video using the progress bar.

Remember to include the JavaScript file in your HTML code using the <script> tag and provide the correct file path.

I hope this provides a more elaborate understanding of the JavaScript code and its functionality within the HTML video player. Happy coding!

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

Tuesday, October 26, 2021

Two squares and circle game

 SIMPLE GAME IN PYGAME: TWO SQUARES AND A RECTANGLE



In this blog, we shall create a simple python game that involves two enemy squares and a player circle. The code is not the cleanest but as long as the game plays we are good to go!

A.    Importing the modules

For this game to run, we require two modules; pygame and math. It is here that we also initialise the pygame module. After initialising the module we need to set the window size and the caption.

import pygame

import math

 

pygame.init()

 

modex, modey = 700, 600

window = pygame.display.set_caption("GAME!!")

window = pygame.display.set_mode((modex, modey))

 

B.     Variables

We require a couple of variables for this game to run. Read the comments to understand the purpose of each variable.

#setting the font we will use in the game

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

#setting the x, y coordinates, radius and velocity of the circle

x, y, radius, vel = modex/2, modey, 30, 15

#setting the colors we will use

green, blue = (0, 255, 0), (0, 0, 128)

#setting the length and width of the rectangle - it becomes a square since length = width

rectx, recty , rectx1, recty1 = 50, 50, 50, 50

#setting the x-y coordinates and velocity of each square

rect, rect1 = [700, 600, 1], [0, 500, 1.3]

#Boolean values required for the game-play

run, jump, move_right, move_left, move_right1, move_left1 = True, False, False, True, True, False

#initalizing the clock method in pygame

clock = pygame.time.Clock()

 

 

C.     Function to check collision

To check if the circle has collided with either of the two squares, we use the formula
for checking the distance between two coordinates. i.e The distance, d, between two points whose coordinates are (x1,y1)(x1,y1) and (x2,y2(x2,y2) is: d = √[(x2x2 − x1x1)2 + (y2y2 − y1y1)2]. If the distance is less than the radius of the circle then a collision has happened.


def HasCollided(rx, ry, cx, cy):

    if cx > rx:

        cx -= rectx                          

    distance = math.sqrt((math.pow(rx-cx,2)) + (math.pow(ry-cy,2)))

    if distance < (radius+2):

        return True

    else:

        return False

 

D.    Gameplay

In the gameplay loop, several things happen;

1.     Time delay – We delay the time using the clock method we initialised. The reason for this is to make sure that the game runs smoothly across all devices regardless of their speed.

while run:

    pygame.time.delay(40)

2.     Quitting the game – We use a for loop to check if an event that could lead to the closing of the game has occurred. (in this case the pressing x button at the right-top of the game window)

while run:

pygame.time.delay(40)

for the event in pygame.event.get():

        if event.type == pygame.QUIT:

            run = False

3.     Moving the circle – To move the circle we use left and right arrow keys on our keyboard. We, therefore, need to check whether a certain key has been pressed and if so move the circle accordingly. To move the circle we subtract the velocity of the circle from its initial location.

keys = pygame.key.get_pressed()

if keys[pygame.K_RIGHT] and x < modex - radius:

x += 10

    if keys[pygame.K_LEFT] and x > radius:

        x -= 10

3.1  Jump – To make the circle ‘jump’ the player will have to press the up arrow key. When they do so the y coordinate of the circle reduces making the circle move up and sets the condition jump to false to prevent jumping while ‘jumping’. It reaches a certain point where the circle starts moving downward. This is achieved by multiplying the velocity of the circle by 2 and then subtracting the result from its coordinate. At some point the velocity becomes negative hence subtracting it from the y coordinate of the circle would result in an increase in the value of the coordinate

#Jump

if jump is False and keys[pygame.K_UP]:

jump = True

if jump is True:

y -= vel * 2

vel -= 2

if vel < -15:

   jump = False

   vel = 15

4.     Moving the squares

The ‘computer’ will be moving the rectangles. We work with move_left and move_right Boolean values. The idea is to prevent the squares from going beyond the game window. The square should be within points 0 and 700. If their x-value goes beyond that scope we prompt them to move in the opposite direction while increasing their speed.

#Moving the square 1

    if move_left is True:

        rect[0] -= rect[2]

        if rect[0] < 0:

            move_left = False

            move_right = True

    if move_right is True:

        rect[0] += rect[2]

        if rect[0] > modex-rectx:

            move_left = True

            move_right = False

    rect[2] += .005

    #Moving the square 2

    if move_left1 is True:

        rect1[0] -= rect1[2]

        if rect1[0] < 0:

            move_left1 = False

            move_right1 = True

    if move_right1 is True:

        rect1[0] += rect1[2]

        if rect1[0] > modex-rectx1:

            move_left1 = True

            move_right1 = False

    rect1[2] += .005

5.     Drawing the shapes – Pygame makes it possible for us to draw shapes using its inbuilt methods. We also fill the background of the game window with an RGB color

pygame.draw.circle(window, (0, 0, 0), (int(x), int(y - radius)), radius)

pygame.draw.rect(window, (255, 0, 0), (rect[0], rect[1]-recty, rectx,recty))

pygame.draw.rect(window, (20, 100, 0), (rect1[0], rect1[1]-recty, rectx, recty))

window.fill ((25, 30, 100))

pygame.display.update()

6.     Checking for collisions – We first need to run the collision function and if it returns true then a collision has happened. So if a collision has occurred the game needs to be stopped and display the game over text or something. To display the text, we use pygames’ blit method.

 

Collision = HasCollided(rect[0], rect[1], x, y)  

    if Collision == True:

        text = font.render('Game Over Bitch!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

Our game loop now looks like this;

while run:

    pygame.time.delay(40)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT] and x < modex - radius:

        x += 10

    if keys[pygame.K_LEFT] and x > radius:

        x -= 10

        #Jump

    if jump is False and keys[pygame.K_UP]:

        jump = True

    if jump is True:

        y -= vel * 2

        vel -= 2

        if vel < -15:

            jump = False

            vel = 15  

    #Moving the square 1

    if move_left is True:

        rect[0] -= rect[2]

        if rect[0] < 0:

            move_left = False

            move_right = True

    if move_right is True:

        rect[0] += rect[2]

        if rect[0] > modex-rectx:

            move_left = True

            move_right = False

    rect[2] += .005

    #Moving the square 2

    if move_left1 is True:

        rect1[0] -= rect1[2]

        if rect1[0] < 0:

            move_left1 = False

            move_right1 = True

    if move_right1 is True:

        rect1[0] += rect1[2]

        if rect1[0] > modex-rectx1:

            move_left1 = True

            move_right1 = False

    rect1[2] += .005

 

    window.fill ((2530100))

    pygame.draw.circle(window, (0, 0, 0), (int(x), int(y - radius)), radius)

    pygame.draw.rect(window, (255, 0, 0), (rect[0], rect[1]-recty, rectx, recty))

    pygame.draw.rect(window, (20, 100, 0), (rect1[0], rect1[1]-recty, rectx, recty))

    pygame.display.update()

   

    Collision = HasCollided(rect[0], rect[1], x, y)  

    if Collision == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

We finally end the game using pygames’ quit method

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

pygame.quit()


Click here to view the full code