<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: cmleary</title>
    <description>The latest articles on DEV Community by cmleary (@cmleary).</description>
    <link>https://dev.to/cmleary</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1133073%2F16b3e028-6d17-4c60-bcdb-c9de75674bfd.png</url>
      <title>DEV Community: cmleary</title>
      <link>https://dev.to/cmleary</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/cmleary"/>
    <language>en</language>
    <item>
      <title>The Way to Surpass CoolMathGames</title>
      <dc:creator>cmleary</dc:creator>
      <pubDate>Thu, 09 Nov 2023 02:53:19 +0000</pubDate>
      <link>https://dev.to/cmleary/the-way-to-surpass-coolmathgames-3hff</link>
      <guid>https://dev.to/cmleary/the-way-to-surpass-coolmathgames-3hff</guid>
      <description>&lt;p&gt;Have you ever taken a break after a 8-hour grind from coolmathgames.com and thought to yourself “Wow that was a lot of fun but maybe I can make an even better game”. Well with various game engines out and about on the web these days you too can make your own cooler math game. &lt;br&gt;
For this blog I’ll talk about a well known game engine called Phaser. Phaser is a JavaScript oriented game engine that possesses various modules to help web developers create games in html-5. It has also been regularly updated since April, 2013. As with all web based programs they have to be up to date to stay relevant and phaser has been keeping up with its development and usability to make it one of the leading game engines used for JavaScript. As with other game engines, Phaser can be split into a renderer to manipulate and present game assets and a module provider to allow methods to create the methods for your game. &lt;br&gt;
The preview below is the is essentially the main tool of Phaser, the canvas:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hJSSGrNR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mxftk18rji9xglq9eq3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hJSSGrNR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mxftk18rji9xglq9eq3.jpg" alt="Image description" width="361" height="360"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Beautiful ain’t it? The canvas will be where we will throw all of our renderings to go from this untapped possibility to wherever your imagination can go. The code below is from my own project where the center of it ends up on the canvas:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Phaser from './lib/phaser.js';
import { SCENE_KEYS } from './scenes/scene-keys.js';
import { PreloadScene } from './scenes/preload-scene.js';
import { BattleScene } from './scenes/battle-scene.js';
import { StoryScene } from './scenes/story-scene.js';


const game = new Phaser.Game({
  type: Phaser.CANVAS,
  pixelArt: false,
  scale: {
    parent: 'game-container',
    width: 1024,
    height: 576,
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
  backgroundColor: '#000000',
});


game.scene.add(SCENE_KEYS.PRELOAD_SCENE, PreloadScene);
game.scene.add(SCENE_KEYS.BATTLE_SCENE, BattleScene);
game.scene.add(SCENE_KEYS.STORY_SCENE, StoryScene)


game.scene.start(SCENE_KEYS.PRELOAD_SCENE);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we set up the Phaser object and set the dimensions for the canvas. Towards the bottom of the snippet we add the &lt;code&gt;Scenes&lt;/code&gt; to the game. The scenes are the different containers we would use for different scenarios and such. To help visualize it for you here are some images that we can break down. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--u1eX9i4g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x35j90dfsjw1fb79fngx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--u1eX9i4g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x35j90dfsjw1fb79fngx.jpg" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we can imagine the pokemon battle as a scene that contains the general logic regarding battling pokemon that you would only use here. If you think about it the battle scene structure doesn’t change at all throughout the entire game except for the pokemon you and the opponent possess.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--eQJk2axB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v69x82vhl9teoqk0nkhc.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eQJk2axB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v69x82vhl9teoqk0nkhc.jpg" alt="Image description" width="800" height="547"&gt;&lt;/a&gt;&lt;br&gt;
Here the scene is the overworld that has the player run along a tile map, staying at the center of the camera yet moving along the x and y coordinates while occasionally interacting with the map. Essentially the tiles may change from a forest, to a desert, or a city but the movement and interactions will not vary that much regardless of where you are in the game.&lt;br&gt;
Depending on what you plan on making, the canvas will be switching from one scene to another based on how you want the flow to go. &lt;br&gt;
To keep it simple a &lt;code&gt;Scene&lt;/code&gt; can be broken down in several different parts.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class PreloadScene extends Phaser.Scene {
  constructor() {
    super({key: SCENE_EXAMPLE,});
   }
//where we load the assets
preload() {
this.load.spritesheet(“player”, `/assets/spritesheets/player.png`)
this.load.spritesheet(“explode”, `/assets/spritesheets/explode.png`)
}
//where we add objects and properties to the canvas
create(){
this.player = this.add.image(x,y, “player”)
}
//Typically how the game will adjust itself depending on user input
//here if you click the a gameObject, like the player, it would swap out the //spritesheet for the “explode” one and visually you would see the player explode

update(){
destroyPlayer(pointer,gameObject){
    gameObect.setTexture(“explode”)
    gameObect.play(“explode”)
}
}





&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First the Scene you are making is made to be exported to the main canvas, otherwise nothing would happen. Then you would set up a &lt;code&gt;preload()&lt;/code&gt; which gathers all of your assets that you want to use and prepares them but does not do anything with them just yet. The &lt;code&gt;create()&lt;/code&gt; is where you would add and adjust the assets for use and set up the calls for objects and interactions for the player to play the game. And the &lt;code&gt;update()&lt;/code&gt; is the way the game rerenders itself constantly depending on user input or actions the game would perform that change the in-game status. Outside of those three you can place methods that will affect the general run of the game such as checks for events that happen within the game or the scene transitions.&lt;/p&gt;

&lt;p&gt;And this has been a brief introduction to what you can expect within Phaser, I hope you can find your way with it and create whatever your imagination calls for and just maybe you can surpass coolmathgames!&lt;/p&gt;

&lt;p&gt;More to be found at:&lt;br&gt;
&lt;a href="https://phaser.io/"&gt;https://phaser.io/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>gamedev</category>
      <category>beginners</category>
      <category>javascript</category>
      <category>phaser</category>
    </item>
    <item>
      <title>Checking out under the hood</title>
      <dc:creator>cmleary</dc:creator>
      <pubDate>Fri, 20 Oct 2023 13:50:27 +0000</pubDate>
      <link>https://dev.to/cmleary/checking-out-under-the-hood-4cnk</link>
      <guid>https://dev.to/cmleary/checking-out-under-the-hood-4cnk</guid>
      <description>&lt;p&gt;If you’re reading this that would mean you most likely have some understanding of python and are beginning to look into web development. When a person wants to set up their web application they typically set up a client and server for a full-application. The client is the web browser that the user would interact with and depending on the interactions, requests would go through to the server, or backend, to manipulate the data. Here the server processes a request from the client, creates a response, and finally sends the response back to the client. This summarizes the goal for what a server should do. If you have come here, you want to understand a bit more in regards to flask. Flask is one of the go-to options to set up the backend of an application to handle the business you want. Here we’ll have a simple overview regarding flask and what you should prepare for.&lt;br&gt;
    For flask you’re just focusing on the server so there won’t be any need for glamor or presentation, you’re just handling data so for those that are not too keen on their art skills back-end programming is for you. Let’s start off with the basic structure of models:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from sqlalchemy.orm import validates
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy_serializer import SerializerMixin
import string, datetime


metadata = MetaData(
    naming_convention={
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    }
)
db = SQLAlchemy(metadata=metadata)




class Patient(db.Model, SerializerMixin):
    __tablename__ = "patient_table"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)


    # -list.object
    serialize_rules = ("-appointments.patient_object",)
    appointments = db.relationship(
        "Appointment", back_populates="patient_object", cascade="all, delete-orphan"
    )
    doctors = association_proxy("appointments", "doctor_object")




class Appointment(db.Model, SerializerMixin):
    __tablename__ = "appointment_table"


    # -object1.list -object2.list
    serialize_rules = ("-patient_object.appointments", "-doctor_object.appointments")


    id = db.Column(db.Integer, primary_key=True)
    day = db.Column(db.String)


    patient_id = db.Column(
        db.Integer, db.ForeignKey("patient_table.id"), nullable=False
    )
    doctor_id = db.Column(db.Integer, db.ForeignKey("doctor_table.id"), nullable=False)


    patient_object = db.relationship("Patient", back_populates="appointments")
    doctor_object = db.relationship("Doctor", back_populates="appointments")


    @validates("day")
    def validate_date(self, key, day):
        if day not in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
            raise ValueError("appointments must be on a weekday")
        return day




class Doctor(db.Model, SerializerMixin):
    __tablename__ = "doctor_table"
    serialize_rules = ("-appointments.doctor_object",)
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    specialty = db.Column(db.String, nullable=False)


    appointments = db.relationship(
        "Appointment", back_populates="doctor_object", cascade="all, delete-orphan"
    )
    patients = association_proxy("appointments", "patient_object")


    @validates("name")
    def validate_name(self, key, name):
        if not name.startswith("Dr."):
            raise ValueError("You can't hire a quack!")
        return name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the code that revolves around a scenario of a patient, appointments and doctors. Here we set up sql tables that possess relationships with one another for us to interact with. Depending on the relationships it could vary on how you want the interactions to play out. One interaction is that a patient can have many appointments, this means that the patient can have appointments with one or many doctors. The columns are set up for the primary id and the name of the patient. We carry over the primary id of the patient to keep track of what appointment they would have and what doctors they may interact with. The &lt;code&gt;db.relationship&lt;/code&gt; we see creates the bridge from one model to the next. While the &lt;code&gt;association_proxy&lt;/code&gt; sets up the “endpoints” between interactions removing some excess “middle” information if you called for this relationship instead of the &lt;code&gt;db.relationship&lt;/code&gt;. So the bridge here heads to Appointments while the endpoint of the relationship is Doctors. Doctors here is similar to Patients as they are both the endpoints of the relationship except for an additional attribute called “specialty” however this is just an additional attribute so it will not affect the relationships between the models. And for the middle man of this scenario Appointment not only possesses the specific ids of patients and doctors but also the day which will typically be something done on the front end. The objects here &lt;code&gt;patient_object&lt;/code&gt; and &lt;code&gt;doctor_object&lt;/code&gt; will be the bridges that hold the data that interact with the endpoints of this relationship. You also see this code called &lt;code&gt;serialize_rules&lt;/code&gt; which acts as a way to reduce unnecessary data from being sent for manipulation and to prevent recursion errors as the relationships would keep iterating themselves. The &lt;code&gt;validates(attribute)&lt;/code&gt; will show an error message if some incorrect entry is attempting to pass. For the doctor it has a validate that checks the name parameter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@validates("name")
    def validate_name(self, key, name):
        if not name.startswith("Dr."):
            raise ValueError("You can't hire a quack!")
        return name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here it checks to see if the name starts with a string that possesses “Dr.” If the name entered does not start with that check it will return the error message.&lt;/p&gt;

&lt;p&gt;That will be the intro to models and here the app.py is where the magic happens&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, make_response, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import datetime
from models import db, Doctor, Patient, Appointment

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.json.compact = False

migrate = Migrate(app, db)

db.init_app(app)


@app.get("/")
def index():
    return "doctor/patient"


@app.get("/doctors")
def get_doctors():
    doctors = Doctor.query.all()
    data = [doctor.to_dict(rules=("-appointments",)) for doctor in doctors]
    return make_response(jsonify(data), 200)


@app.get("/doctors/&amp;lt;int:id&amp;gt;")
def get_doctor_by_id(id):
    doctor = Doctor.query.filter(Doctor.id == id).first()
    if not doctor:
        make_response(jsonify({"error": "that is a quack"}), 404)
    doctor_dict = doctor.to_dict()
    return make_response(jsonify(doctor_dict), 200)


@app.get("/patients/&amp;lt;int:id&amp;gt;")
def get_patients(id):
    patient = db.session.get(Patient, id)
    doctors = [d.to_dict(rules=("-appointments",)) for d in patient.doctors]
    patient_dict = patient.to_dict(rules=("-appointments",))
    patient_dict["doctors"] = doctors
    return make_response(jsonify(patient_dict), 200)


@app.post("/doctors")
def post_doctor():
    data = request.get_json()

    try:
        doc = Doctor(name=data["name"], specialty=data["specialty"])
        db.session.add(doc)
        db.session.commit()
        return make_response(jsonify(doc.to_dict()), 201)
    except ValueError:
        return make_response(jsonify({"error": "that's a quack!"}), 405)


@app.patch("/patients/&amp;lt;int:id&amp;gt;")
def patch_patients(id):
    data = request.get_json()
    patient = Patient.query.filter(Patient.id == id).first()
    if not patient:
        make_response(jsonify({"error": "no such patient"}), 404)
    try:
        for key in data:
            setattr(patient, key, data[key])
        db.session.add(patient)
        db.session.commit()
        return make_response(jsonify(patient.to_dict()), 201)
    except:
        return make_response(jsonify({"error": "could not update patient"}), 405)


@app.post("/appointments")
def post_appointment():
    data = request.json
    try:
        appointment = Appointment(
            patient_id=data.get("patient_id"),
            doctor_id=data.get("doctor_id"),
            day=data.get("day"),
        )
        db.session.add(appointment)
        db.session.commit()
        return make_response(
            jsonify(appointment.to_dict(rules=("-patient_id", "-doctor_id"))), 201
        )
    except Exception as e:
        return make_response(jsonify({"error": str(e)}), 405)


if __name__ == "__main__":
    app.run(port=5555, debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the app processes the requests and manipulates the data according to the request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.get("/doctors")
def get_doctors():
    doctors = Doctor.query.all()
    data = [doctor.to_dict(rules=("-appointments",)) for doctor in doctors]
    return make_response(jsonify(data), 200)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this ‘Get’ request the request calls for the data of all the doctors stored within the database and the data returned will be set based on the &lt;code&gt;serialize_rules&lt;/code&gt; along with the &lt;code&gt;to_dict(rules = “-***”)&lt;/code&gt; here the ‘Get’ also removes the appointments object so you basically just receive the doctors with their specialties and ids.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.post("/doctors")
def post_doctor():
    data = request.get_json()

    try:
        doc = Doctor(name=data["name"], specialty=data["specialty"])
        db.session.add(doc)
        db.session.commit()
        return make_response(jsonify(doc.to_dict()), 201)
    except ValueError:
        return make_response(jsonify({"error": "that's a quack!"}), 405)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here a post request is made and the user enters the data for a doctor. However, you may receive an error if you forget about the validation rule set in the model. So if you’re post request forgets the rules no data will be entered into the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == "__main__":
    app.run(port=5555, debug=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally this code should run the server for the user to interact with. Hopefully, this piece will give you an idea to prepare for when using flask.&lt;/p&gt;

&lt;p&gt;Example code from &lt;a href="https://github.com/d-gaston/tours/tree/master/flask/cc/appointments/solution"&gt;github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>flask</category>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Coding to Gaming</title>
      <dc:creator>cmleary</dc:creator>
      <pubDate>Tue, 26 Sep 2023 15:41:54 +0000</pubDate>
      <link>https://dev.to/cmleary/coding-to-gaming-2623</link>
      <guid>https://dev.to/cmleary/coding-to-gaming-2623</guid>
      <description>&lt;p&gt;When people look at the python coding language they will typically refer to it as a backend specialized code and not expect to see an active interface regarding it. Well typically that is correct, however, but installing pygame may make those views change. Pygame is a set of modules that provides basic tools for beginner coders to learn how to program a game themselves. Within pygame it comes with various functions, sprites, sounds, and much more to assist with game development. Here I’ll give a short introduction to what pygame is capable of.&lt;br&gt;
Ranging from adventure games, platforms, to simple clicking games pygame can cover a decent amount of ground based on the capabilities of the coder. However, despite being a quite welcome tool, if you look from high end (triple A companies) to indie developers (single to small group) it is quite unlikely you will find any games made with python. As I’ve said, pygame gives access to basic level tools, looking at that statement in another way, there’s nothing truly special about it. This setup does encourage programmers to learn the nuance of the game elements themselves which could help their development, rather than focusing on one highly specialized game engine that will unlikely provide meaningful experience. &lt;br&gt;
Take a look at the code below, it belongs to a simple pygame example called “Aliens”&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random, os.path

#import basic pygame modules
import pygame
from pygame.locals import *

#see if we can load more than standard BMP
if not pygame.image.get_extended():
    raise SystemExit("Sorry, extended image module required")


#game constants
MAX_SHOTS      = 2      #most player bullets onscreen
ALIEN_ODDS     = 22     #chances a new alien appears
BOMB_ODDS      = 60    #chances a new bomb will drop
ALIEN_RELOAD   = 12     #frames between new aliens
SCREENRECT     = Rect(0, 0, 640, 480)
SCORE          = 0

main_dir = os.path.split(os.path.abspath(__file__))[0]

def load_image(file):
    "loads an image, prepares it for play"
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()

def load_images(*files):
    imgs = []
    for file in files:
        imgs.append(load_image(file))
    return imgs


class dummysound:
    def play(self): pass

def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join(main_dir, 'data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print ('Warning, unable to load, %s' % file)
    return dummysound()



# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard


class Player(pygame.sprite.Sprite):
    speed = 10
    bounce = 24
    gun_offset = -11
    images = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
        self.reloading = 0
        self.origtop = self.rect.top
        self.facing = -1

    def move(self, direction):
        if direction: self.facing = direction
        self.rect.move_ip(direction*self.speed, 0)
        self.rect = self.rect.clamp(SCREENRECT)
        if direction &amp;lt; 0:
            self.image = self.images[0]
        elif direction &amp;gt; 0:
            self.image = self.images[1]
        self.rect.top = self.origtop - (self.rect.left//self.bounce%2)

    def gunpos(self):
        pos = self.facing*self.gun_offset + self.rect.centerx
        return pos, self.rect.top


class Alien(pygame.sprite.Sprite):
    speed = 13
    animcycle = 12
    images = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.facing = random.choice((-1,1)) * Alien.speed
        self.frame = 0
        if self.facing &amp;lt; 0:
            self.rect.right = SCREENRECT.right

    def update(self):
        self.rect.move_ip(self.facing, 0)
        if not SCREENRECT.contains(self.rect):
            self.facing = -self.facing;
            self.rect.top = self.rect.bottom + 1
            self.rect = self.rect.clamp(SCREENRECT)
        self.frame = self.frame + 1
        self.image = self.images[self.frame//self.animcycle%3]


class Explosion(pygame.sprite.Sprite):
    defaultlife = 12
    animcycle = 3
    images = []
    def __init__(self, actor):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect(center=actor.rect.center)
        self.life = self.defaultlife

    def update(self):
        self.life = self.life - 1
        self.image = self.images[self.life//self.animcycle%2]
        if self.life &amp;lt;= 0: self.kill()


class Shot(pygame.sprite.Sprite):
    speed = -11
    images = []
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom=pos)

    def update(self):
        self.rect.move_ip(0, self.speed)
        if self.rect.top &amp;lt;= 0:
            self.kill()


class Bomb(pygame.sprite.Sprite):
    speed = 9
    images = []
    def __init__(self, alien):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom=
                    alien.rect.move(0,5).midbottom)

    def update(self):
        self.rect.move_ip(0, self.speed)
        if self.rect.bottom &amp;gt;= 470:
            Explosion(self)
            self.kill()


class Score(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.font = pygame.font.Font(None, 20)
        self.font.set_italic(1)
        self.color = Color('white')
        self.lastscore = -1
        self.update()
        self.rect = self.image.get_rect().move(10, 450)

    def update(self):
        if SCORE != self.lastscore:
            self.lastscore = SCORE
            msg = "Score: %d" % SCORE
            self.image = self.font.render(msg, 0, self.color)



def main(winstyle = 0):
    # Initialize pygame
    pygame.init()
    if pygame.mixer and not pygame.mixer.get_init():
        print ('Warning, no sound')
        pygame.mixer = None

    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    #Load images, assign to sprite classes
    #(do this before the classes are used, after screen setup)
    img = load_image('player1.gif')
    Player.images = [img, pygame.transform.flip(img, 1, 0)]
    img = load_image('explosion1.gif')
    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
    Alien.images = load_images('alien1.gif', 'alien2.gif', 'alien3.gif')
    Bomb.images = [load_image('bomb.gif')]
    Shot.images = [load_image('shot.gif')]

    #decorate the game window
    icon = pygame.transform.scale(Alien.images[0], (32, 32))
    pygame.display.set_icon(icon)
    pygame.display.set_caption('Pygame Aliens')
    pygame.mouse.set_visible(0)

    #create the background, tile the bgd image
    bgdtile = load_image('background.gif')
    background = pygame.Surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(background, (0,0))
    pygame.display.flip()

    #load the sound effects
    boom_sound = load_sound('boom.wav')
    shoot_sound = load_sound('car_door.wav')
    if pygame.mixer:
        music = os.path.join(main_dir, 'data', 'house_lo.wav')
        pygame.mixer.music.load(music)
        pygame.mixer.music.play(-1)

    # Initialize Game Groups
    aliens = pygame.sprite.Group()
    shots = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()
    lastalien = pygame.sprite.GroupSingle()

    #assign default groups to each sprite class
    Player.containers = all
    Alien.containers = aliens, all, lastalien
    Shot.containers = shots, all
    Bomb.containers = bombs, all
    Explosion.containers = all
    Score.containers = all

    #Create Some Starting Values
    global score
    alienreload = ALIEN_RELOAD
    kills = 0
    clock = pygame.time.Clock()

    #initialize our starting sprites
    global SCORE
    player = Player()
    Alien() #note, this 'lives' because it goes into a sprite group
    if pygame.font:
        all.add(Score())


    while player.alive():

        #get input
        for event in pygame.event.get():
            if event.type == QUIT or \
                (event.type == KEYDOWN and event.key == K_ESCAPE):
                    return
        keystate = pygame.key.get_pressed()

        # clear/erase the last drawn sprites
        all.clear(screen, background)

        #update all the sprites
        all.update()

        #handle player input
        direction = keystate[K_RIGHT] - keystate[K_LEFT]
        player.move(direction)
        firing = keystate[K_SPACE]
        if not player.reloading and firing and len(shots) &amp;lt; MAX_SHOTS:
            Shot(player.gunpos())
            shoot_sound.play()
        player.reloading = firing

        # Create new alien
        if alienreload:
            alienreload = alienreload - 1
        elif not int(random.random() * ALIEN_ODDS):
            Alien()
            alienreload = ALIEN_RELOAD

        # Drop bombs
        if lastalien and not int(random.random() * BOMB_ODDS):
            Bomb(lastalien.sprite)

        # Detect collisions
        for alien in pygame.sprite.spritecollide(player, aliens, 1):
            boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
            boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        for bomb in pygame.sprite.spritecollide(player, bombs, 1):
            boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()

        #draw the scene
        dirty = all.draw(screen)
        pygame.display.update(dirty)

        #cap the framerate
        clock.tick(40)

    if pygame.mixer:
        pygame.mixer.music.fadeout(1000)
    pygame.time.wait(1000)
    pygame.quit()



#call the "main" function if running this script
if __name__ == '__main__': main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ijUXWSLE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c84manrp74vq7l2ednpu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ijUXWSLE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c84manrp74vq7l2ednpu.png" alt="Image description" width="650" height="513"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When you run the code a new window appears containing the game “Aliens”. This game has simple controls along with a simple objective. The user controls the military vehicle with the left and right arrow keys for movement and the spacebar to shoot a missile to attack the UFOs gaining points. Going under the hood we see the above code declaring the aspects of the game from the player vehicle, UFOs, missiles, explosions, and so on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Player(pygame.sprite.Sprite):
    speed = 10
    bounce = 24
    gun_offset = -11
    images = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
        self.reloading = 0
        self.origtop = self.rect.top
        self.facing = -1

    def move(self, direction):
        if direction: self.facing = direction
        self.rect.move_ip(direction*self.speed, 0)
        self.rect = self.rect.clamp(SCREENRECT)
        if direction &amp;lt; 0:
            self.image = self.images[0]
        elif direction &amp;gt; 0:
            self.image = self.images[1]
        self.rect.top = self.origtop - (self.rect.left//self.bounce%2)

    def gunpos(self):
        pos = self.facing*self.gun_offset + self.rect.centerx
        return pos, self.rect.top
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class sets the attributes of the player and uses those values later to interact with the program as a whole. There are also classes that cover the Bomb, Shot, Explosion, and of course the Alien. And in some of these classes they share similar attributes such as speed, in this context speed will decide how quickly objects can move within the game. .&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Alien(pygame.sprite.Sprite):
    speed = 13
    animcycle = 12
    images = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.facing = random.choice((-1,1)) * Alien.speed
        self.frame = 0
        if self.facing &amp;lt; 0:
            self.rect.right = SCREENRECT.right

    def update(self):
        self.rect.move_ip(self.facing, 0)
        if not SCREENRECT.contains(self.rect):
            self.facing = -self.facing;
            self.rect.top = self.rect.bottom + 1
            self.rect = self.rect.clamp(SCREENRECT)
        self.frame = self.frame + 1
        self.image = self.images[self.frame//self.animcycle%3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the Alien class that sets the attributes for the endlessly spawning enemies in the game. Now let’s look at this line  &lt;code&gt;self.rect = self.image.get_rect()&lt;/code&gt; here a method to give Alien a rectangle, now what does it mean to give a rectangle to a flying disc dropping bombs? It’s to allow easier ways for the game aspects to interact with each other. We can manipulate the collisions between the missiles and the player utilizing rectangles to help adjust hitboxes and sprite movement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; # Detect collisions
        for alien in pygame.sprite.spritecollide(player, aliens, 1):
            boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
            boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        for bomb in pygame.sprite.spritecollide(player, bombs, 1):
            boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In these lines of code they cover different scenarios of collisions within the game. From top to bottom, what happens if a UFO and the player collide, what happens if a missile and a UFO collide, and what happens if a bomb and the player collide. These outcomes decide if the score rises or the game ends with the player’s death.&lt;/p&gt;

&lt;p&gt;After various information is laid out for us you may notice that the actual gameplay of this code is all written within a while loop. The loop essentially runs making aliens endlessly spawning at set increments and reads the player input keys to control the vehicle. And if we look at the condition for the while loop &lt;code&gt;while player.alive()&lt;/code&gt; The loop will end when the player is “dead” and the conditions to cause this are essentially when the player collides with a bomb or a UFO. When the player status changes the loop essentially ends and the last two lines of the "main" function code run.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; pygame.time.wait(1000)
 pygame.quit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The program will wait one second and the game will quit, closing the window and ending the code.&lt;br&gt;
Hopefully this brief introduction to pygame can provide some insight to future game developers that want to experiment around within python.&lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Github of '&lt;a href="https://github.com/xamox/pygame/blob/master/examples/aliens.py"&gt;Aliens&lt;/a&gt;'&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Installing &lt;a href="https://www.pygame.org/wiki/GettingStarted"&gt;Pygame&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To simply play 'Aliens' after installing pygame you can enter &lt;code&gt;python3 -m pygame.examples.aliens&lt;/code&gt; into your terminal and it'll launch the game.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;About &lt;a href="https://www.pygame.org/wiki/about?parent="&gt;Pygame&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>gamedev</category>
      <category>beginners</category>
      <category>python</category>
    </item>
    <item>
      <title>Nothing Small about Components</title>
      <dc:creator>cmleary</dc:creator>
      <pubDate>Wed, 06 Sep 2023 16:27:18 +0000</pubDate>
      <link>https://dev.to/cmleary/nothing-small-about-components-1f3j</link>
      <guid>https://dev.to/cmleary/nothing-small-about-components-1f3j</guid>
      <description>&lt;p&gt;If you are going to be learning about React you will certainly be going into components. When setting up your application we can take apart the page based on what "role" each part serves. These “roles” can range from displaying a title, writing out data, a list to display and so on. By utilizing components we can keep our code dry and organized in a simple to understand manner. &lt;br&gt;
When using components in a standard manner, we basically use them to perform some type of function and then return a specified output to have it rendered within the DOM. Let us look at an example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Blog from “./Blog”;
Import Comment from “./Comment”


function App() {
const blogData = {
  title: "Nothing Small about Components",
  about: "A blog about learning components",
  likes: 5
};


  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Blog blogData = {blogData}/&amp;gt;
      &amp;lt;Comment /&amp;gt;
    &amp;lt;
    &amp;lt;/div&amp;gt;
  );

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Blog({blogData}) {

let text = "";

function displayStars({blogData.likes}){
    for (let star = 0; star &amp;lt; {blogData.likes}; star++) {

    text += "*"
  }
  console.log(text)
}

 return (
    &amp;lt;article&amp;gt;
        &amp;lt;h3&amp;gt;{blogData.title}&amp;lt;/h3&amp;gt;
        &amp;lt;small&amp;gt;{displayStars()}&amp;lt;/small&amp;gt;
        &amp;lt;p&amp;gt;{blogData.about}&amp;lt;/p&amp;gt;
    &amp;lt;/article&amp;gt;
)
export default Blog;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Comment (){
    return(
       &amp;lt;small&amp;gt;
          &amp;lt;ul&amp;gt;
        &amp;lt;li&amp;gt;This is cool! -AmusedReader234&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Wow! -FasinatedGuy3&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Need more of this! -Leeroy J.&amp;lt;/li&amp;gt;
          &amp;lt;/ul&amp;gt;  
       &amp;lt;/small&amp;gt;
     )
}

export default Comment;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s go through this step-by-step, when you create a new file in your code editing software it is standard practice to have the main body of your application to be written in a particular component called   this is where all the components typically come together to make the main page. In this  we first see it declared as a function, the syntax and functionality are similar but for components the name of it is always upper case and the return will be in the form of html elements. For the return of  it will present the html elements that belong to components  and  respectively. Here these two components are referred to as ‘child’ components of  as their returns will be presented onto  directly. &lt;br&gt;
Now, what do   and  display? Let’s look at the order and go from there, the code will display the result of  first so whatever is happening there is run and presented before . So we go to the  component first and see what it does. In the code we see that the component has a function that will impact the return of the html and see that it takes blogData from somewhere. Well blogData originally comes from  and it is passed down to the ‘child’ component  through the use of props. In the code for  it will return   the blogData there is the prop to be used within . In the file for  it will be written like  however it also has a prop where a parameter would be, function Blog({blogData}), Now  has the information of the object declared in  and can make use of it.   now will display the title, run the function written within the component and finally the about. So  can receive and manipulate the data to display it and then export it back to  so that it can present the html. &lt;br&gt;
In  we are not passing down any props so it will basically present what it possesses without outside influence. Here it will simply return the list of comments by readers and again export it back to . &lt;/p&gt;

&lt;p&gt;In the end our code will look something like this : &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Sng1IpPT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuwse0rd43nuosohcmvn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Sng1IpPT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuwse0rd43nuosohcmvn.png" alt="Image description" width="280" height="166"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From the title, to the function displaying the likes in the form of '*', the description, and finally to the list of comments all of the 'roles' we were talking about all gathered to form this piece.  Hopefully, this has shown that components will become major parts of organizing and presenting code in an understanding manner on your path as a programmer.&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>The Reality of Functions</title>
      <dc:creator>cmleary</dc:creator>
      <pubDate>Tue, 15 Aug 2023 18:41:42 +0000</pubDate>
      <link>https://dev.to/cmleary/the-reality-of-functions-2l7k</link>
      <guid>https://dev.to/cmleary/the-reality-of-functions-2l7k</guid>
      <description>&lt;p&gt;If you are going to code you are going to learn and get used to utilizing functions. Functions are a major part of how you as a programmer will have the labor to be cut down to possess as little of excess as it needs to be. In the majority of our work as programmers there will most certainly be times when we have one task repeating and writing the same lines of code is simply inefficient. This is where functions will shine as you simply need to write the task to be completed once and if the task needs to be repeated then all you have to do is call the function again to repeat. &lt;br&gt;
When it is broken down a function is a set of code that does not act until it is called upon, whether it be to do simple arithmetic or to create elements in a DOM as long as it is properly set up the function will complete the task as many times as needed. Without using functions our code will be oversaturated with repetitive lines and similar variables that will most likely create a program that is a headache to maintain and just unappealing to look at.&lt;br&gt;
         For a basic show of what a function can do let’s look at a function that receives parameters that are numbers to go through several  forms of operations and prints out the results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arithmetic(num1,num2){
  let sum = num1 + num2
  console.log(sum)
  let product = num1 * num2
  console.log(product)
  let difference = num1 - num2
  console.log(difference)
  let quotient = num1 / num2
  console.log(quotient)
}

let a = 7
let b = 5
let c = 4

arithmetic(a,b)
arithmetic(b,a)
arithmetic(c)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s break down what is happening here to understand the basics. As programmers one of the first things we are taught is that code runs top down meaning the first line of code should run as if one was reading a book. However, here the first line read is the declaration of a function that performs several tasks but ultimately won’t perform them until the function is called which happens later on. So we skip the function and its contents and get to the variable declarations which we then enter into the function. The first time the function is called we set the parameters as variable a and b, the order here affects how the function performs the operations so entering the parameters correctly affects the entire process. So for arithmetic(a, b) parameter ‘a’ becomes ‘num1’ and parameter ‘b’ becomes ‘num2’. Then the code as it normally would and in the background it looks like this with the commented parts showing what would appear in the console log (also as written above variable a = 7 and variable b = 5):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arithmetic(a,b){
  let sum = a + b           
  console.log(sum)                      //12
  let product = a * b
  console.log(product)                  //35
  let difference = a - b
  console.log(difference)               //2
  let quotient = a / b
  console.log(quotient)                 //1.4
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next line of code in the example is arithmetic(b,a) similar as the first however the arguments are switched. In turn this would lead to the outputs as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arithmetic(b,a){
  let sum = b + a           
  console.log(sum)                      //12
  let product = b * a
  console.log(product)                  //35
  let difference = b - a
  console.log(difference)               //-2
  let quotient = b / a
  console.log(quotient)                 //0.71428571428
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When it comes to sum and product the result won’t particularly change however when we processed the difference and quotient due to the parameter change we received different results. &lt;br&gt;
Now what would happen if we enter in only one parameter in this function even though it requires 2? In the next line of code we have arithmetic(c), where c is 4 in this example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arithmetic(c,num2){
  let sum = c + num2            
  console.log(sum)                      //NaN
  let product = c * num2    
  console.log(product)                  //NaN
  let difference = c - num2
  console.log(difference)               //NaN
  let quotient = c / num2
  console.log(quotient)                 //NaN
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see we did not receive any proper results because there was no ‘num2’ for this entry. We only received ‘NaN’ which means ‘Not a number’ to show how we need to make certain we enter in the right amount of parameters.&lt;br&gt;
And this will conclude a brief introduction to the usefulness of functions. In this case the function was set up to receive numbers and perform some simple arithmetic, however functions can also receive objects and arrays to manipulate them. These other manipulations can help order data and manipulate elements within a DOM. So as programmers it is important to take advantage of these tools to make our code perform all of its tasks in a concise manner.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>coding</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
