PyDev of the Week: Elizabeth Sander

This week we welcome Elizabeth Sander as our PyDev of the Week! Elizabeth is a data scientist at Civis Analytics. She has her own website where you can learn a lot of interesting background information about her. If you are more interested in her open source projects, then her Github profile may be what you really want to check out. Let’s take a few moments to get to know Elizabeth better!
Can you tell us a little about yourself (hobbies, education, etc):

Link: https://dzone.com/articles/pydev-of-the-week-elizabeth-sander?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

PyDev of the Week: Juan Luis Cano

This week we welcome Juan Luis Cano (@astrojuanlu) as our PyDev of the Week! He is the chair of the Python Spain non-profit and the author of the poliastro project. If you can read Spanish, then you might want to check out his website. Otherwise, you can definitely take a look at his GitHub profile to see what he’s been working on or is interested in. Let’s take some time to learn more about Juan!

Can you tell us a little about yourself (hobbies, education, etc)?:

Link: https://dzone.com/articles/pydev-of-the-week-juan-luis-cano?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

PyDev of the Week: Brian Ray

This week we welcome Brian Ray as our PyDev of the Week! Brian is the author/speaker for Python From Scratch Life Lessons from O’Reilly. He is the founders and the former chair of ChiPy, the Chicago Python users group. Let’s take a few moments to get to know Brian better!
Can you tell us a little about yourself (hobbies, education, etc):

Link: https://dzone.com/articles/pydev-of-the-week-brian-ray?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

PyDev of the Week: Adrian Rosebrock

This week we welcome Adrian Rosebrock (@PyImageSearch) as our PyDev of the Week. Adrian is the author of several books on Python and OpenCV. He is also the author of PyImageSearch.com, a very popular Python blog that focuses on computer vision. Let’s take some time to get to know him a bit better!
Can you tell us about yourself and PyImageSearch?

Link: https://dzone.com/articles/pydev-of-the-week-adrian-rosebrock?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Parsing HTML: Selecting the Right Library (Part 2)

Last time, we looked over the various HTML parsers you can consider when working with Java. This time, we’ll examine a couple of popular C# libraries worth considering as we examine their features, benefits, and drawbacks when processing HTML.
C#
AngleSharp

The ultimate angle brackets parser library parsing HTML5, MathML, SVG and CSS to construct a DOM based on the official W3C specifications.

Link: https://dzone.com/articles/parsing-html-selecting-the-right-library-part-2?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Parsing HTML: Selecting the Right Library (Part 1)

HTML is a markup language with a simple structure. It would be quite easy to build a parser for HTML with a parser generator. Actually, you may not even need to do that if you choose a popular parser generator, like ANTLR. That is because there are already available grammars ready to be used.
HTML is so popular that there is even a better option: using a library. It is easier to use and usually provides more features, such as a way to create an HTML document or support easy navigation through the parsed document. For example, usually, it comes with a CSS/jQuery-like selector to find nodes according to their position in the hierarchy.

Link: https://dzone.com/articles/parsing-html-selecting-the-right-library?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

PyDev of the Week: Jeff Forcier

This week we welcome Jeff Forcier (@bitprophet) as our PyDev of the Week. Jeff is the current maintainer of the popular Fabric and Paramiko packages. He is also the creator of the Invoke package. You can check out other projects that Jeff contributes to on GitHub. He also has a blog that you might find interesting. Let’s take some time to get to know Jeff better!
Can you tell us a little about yourself (hobbies, education, etc):

Link: https://dzone.com/articles/pydev-of-the-week-jeff-forcier?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

How to Build Amazing User Interfaces With React

As you might already know, React has been developed by Facebook. It is an open source JavaScript library which can be used for creating amazing user interfaces. But what makes this library so great for UI development?
It allows developers to make very fast loading UIs and provides a great user experience for their end users. By using React, you can set different views for each component or the entire app, based on its state. React is great because its library changes only the necessary parts instead of reloading the entire app.

Link: https://dzone.com/articles/how-to-build-amazing-user-interfaces-with-react?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Procedurally Generated Game Terrain with React, PHP, and WebSockets

Last time, I began telling you the story of how I wanted to make a game. I described how I set up the async PHP server, the Laravel Mix build chain, the React front end, and WebSockets connecting all this together. Now, let me tell you about what happened when I starting building the game mechanics with this mix of React, PHP, and WebSockets…

The code for this part can be found at github.com/assertchris-tutorials/sitepoint-making-games/tree/part-2. I’ve tested it with PHP 7.1, in a recent version of Google Chrome.

Making a Farm
“Let’s start simple. We have a 10 by 10 grid of tiles, filled with randomly generated stuff."
I decided to represent the farm as a Farm, and each tile as a Patch. From app/Model/FarmModel.pre:
namespace App\Model;

class Farm
{
private $width
{
get { return $this->width; }
}

private $height
{
get { return $this->height; }
}

public function __construct(int $width = 10,
int $height = 10)
{
$this->width = $width;
$this->height = $height;
}
}

I thought it would be a fun time to try out the class accessors macro by declaring private properties with public getters. For this I had to install pre/class-accessors (via composer require).
I then changed the socket code to allow for new farms to be created on request. From app/Socket/GameSocket.pre:
namespace App\Socket;

use Aerys\Request;
use Aerys\Response;
use Aerys\Websocket;
use Aerys\Websocket\Endpoint;
use Aerys\Websocket\Message;
use App\Model\FarmModel;

class GameSocket implements Websocket
{
private $farms = [];

public function onData(int $clientId,
Message $message)
{
$body = yield $message;

if ($body === "new-farm") {
$farm = new FarmModel();

$payload = json_encode([
"farm" => [
"width" => $farm->width,
"height" => $farm->height,
],
]);

yield $this->endpoint->send(
$payload, $clientId
);

$this->farms[$clientId] = $farm;
}
}

public function onClose(int $clientId,
int $code, string $reason)
{
unset($this->connections[$clientId]);
unset($this->farms[$clientId]);
}

// …
}

I noticed how similar this GameSocket was to the previous one I had — except, instead of broadcasting an echo, I was checking for new-farm and sending a message back only to the client that had asked.
"Perhaps it’s a good time to get less generic with the React code. I’m going to rename component.jsx to farm.jsx."
From assets/js/farm.jsx:
import React from "react"

class Farm extends React.Component
{
componentWillMount()
{
this.socket = new WebSocket(
"ws://127.0.0.1:8080/ws"
)

this.socket.addEventListener(
"message", this.onMessage
)

// DEBUG

this.socket.addEventListener("open", () => {
this.socket.send("new-farm")
})
}
}

export default Farm

In fact, the only other thing I changed was sending new-farm instead of hello world. Everything else was the same. I did have to change the app.jsx code though. From assets/js/app.jsx:
import React from "react"
import ReactDOM from "react-dom"
import Farm from "./farm"

ReactDOM.render(
,
document.querySelector(".app")
)

It was far from where I needed to be, but using these changes I could see the class accessors in action, as well as prototype a kind of request/response pattern for future WebSocket interactions. I opened the console, and saw {"farm":{"width":10,"height":10}}.
"Great!"
Then I created a Patch class to represent each tile. I figured this was where a lot of the game’s logic would happen. From app/Model/PatchModel.pre:
namespace App\Model;

class PatchModel
{
private $x
{
get { return $this->x; }
}

private $y
{
get { return $this->y; }
}

public function __construct(int $x, int $y)
{
$this->x = $x;
$this->y = $y;
}
}

I’d need to create as many patches as there are spaces in a new Farm. I could do this as part of FarmModel construction. From app/Model/FarmModel.pre:
namespace App\Model;

class FarmModel
{
private $width
{
get { return $this->width; }
}

private $height
{
get { return $this->height; }
}

private $patches
{
get { return $this->patches; }
}

public function __construct($width = 10, $height = 10)
{
$this->width = $width;
$this->height = $height;

$this->createPatches();
}

private function createPatches()
{
for ($i = 0; $i < $this->width; $i++) {
$this->patches[$i] = [];

for ($j = 0; $j < $this->height; $j++) {
$this->patches[$i][$j] =
new PatchModel($i, $j);
}
}
}
}

For each cell, I created a new PatchModel object. These were pretty simple to begin with, but they needed an element of randomness — a way to grow trees, weeds, flowers … at least to begin with. From app/Model/PatchModel.pre:
public function start(int $width, int $height,
array $patches)
{
if (!$this->started && random_int(0, 10) > 7) {
$this->started = true;
return true;
}

return false;
}

I thought I’d begin just by randomly growing a patch. This didn’t change the external state of the patch, but it did give me a way to test how they were started by the farm. From app/Model/FarmModel.pre:
namespace App\Model;

use Amp;
use Amp\Coroutine;
use Closure;

class FarmModel
{
private $onGrowth
{
get { return $this->onGrowth; }
}

private $patches
{
get { return $this->patches; }
}

public function __construct(int $width = 10,
int $height = 10, Closure $onGrowth)
{
$this->width = $width;
$this->height = $height;
$this->onGrowth = $onGrowth;
}

public async function createPatches()
{
$patches = [];

for ($i = 0; $i < $this->width; $i++) {
$this->patches[$i] = [];

for ($j = 0; $j < $this->height; $j++) {
$this->patches[$i][$j] = $patches[] =
new PatchModel($i, $j);
}
}

foreach ($patches as $patch) {
$growth = $patch->start(
$this->width,
$this->height,
$this->patches
);

if ($growth) {
$closure = $this->onGrowth;
$result = $closure($patch);

if ($result instanceof Coroutine) {
yield $result;
}
}
}
}

// …
}

There was a lot going on here. For starters, I introduced an async function keyword using a macro. You see, Amp handles the yield keyword by resolving Promises. More to the point: when Amp sees the yield keyword, it assumes what is being yielded is a Coroutine (in most cases).
I could have made the createPatches function a normal function, and just returned a Coroutine from it, but that was such a common piece of code that I might as well have created a special macro for it. At the same time, I could replace code I had made in the previous part. From helpers.pre:
async function mix($path) {
$manifest = yield Amp\File\get(
.."/public/mix-manifest.json"
);

$manifest = json_decode($manifest, true);

if (isset($manifest[$path])) {
return $manifest[$path];
}

throw new Exception("{$path} not found");
}

Previously, I had to make a generator, and then wrap it in a new Coroutine:
use Amp\Coroutine;

function mix($path) {
$generator = () => {
$manifest = yield Amp\File\get(
.."/public/mix-manifest.json"
);

$manifest = json_decode($manifest, true);

if (isset($manifest[$path])) {
return $manifest[$path];
}

throw new Exception("{$path} not found");
};

return new Coroutine($generator());
}

I began the createPatches method as before, creating new PatchModel objects for each x and y in the grid. Then I started another loop, to call the start method on each patch. I would have done these in the same step, but I wanted my start method to be able to inspect the surrounding patches. That meant I would have to create all of them first, before working out which patches were around each other.
I also changed FarmModel to accept an onGrowth closure. The idea was that I could call that closure if a patch grew (even during the bootstrapping phase).
Each time a patch grew, I reset the $changes variable. This ensured the patches would keep growing until an entire pass of the farm yielded no changes. I also invoked the onGrowth closure. I wanted to allow onGrowth to be a normal closure, or even to return a Coroutine. That’s why I needed to make createPatches an async function.
Note: Admittedly, allowing onGrowth coroutines complicated things a bit, but I saw it as essential for allowing other async actions when a patch grew. Perhaps later I’d want to send a socket message, and I could only do that if yield worked inside onGrowth. I could only yield onGrowth if createPatches was an async function. And because createPatches was an async function, I would need to yield it inside GameSocket.
"It’s easy to get turned off by all the things that need learning when making one’s first async PHP application. Don’t give up too soon!"
The last bit of code I needed to write to check that this was all working was in GameSocket. From app/Socket/GameSocket.pre:
if ($body === "new-farm") {
$patches = [];

$farm = new FarmModel(10, 10,
function (PatchModel $patch) use (&$patches) {
array_push($patches, [
"x" => $patch->x,
"y" => $patch->y,
]);
}
);

yield $farm->createPatches();

$payload = json_encode([
"farm" => [
"width" => $farm->width,
"height" => $farm->height,
],
"patches" => $patches,
]);

yield $this->endpoint->send(
$payload, $clientId
);

$this->farms[$clientId] = $farm;
}

This was only slightly more complex than the previous code I had. I needed to provide a third parameter to the FarmModel constructor, and yield $farm->createPatches() so that each could have a chance to randomize. After that, I just needed to pass a snapshot of the patches to the socket payload.

Random patches for each farm

"What if I start each patch as dry dirt? Then I could make some patches have weeds, and others have trees …"
I set about customizing the patches. From app/Model/PatchModel.pre:
private $started = false;

private $wet {
get { return $this->wet ?: false; }
};

private $type {
get { return $this->type ?: "dirt"; }
};

public function start(int $width, int $height,
array $patches)
{
if ($this->started) {
return false;
}

if (random_int(0, 100) < 90) {
return false;
}

$this->started = true;
$this->type = "weed";

return true;
}

I changed the order of logic around a bit, exiting early if the patch had already been started. I also reduced the chance of growth. If neither of these early exits happened, the patch type would be changed to weed.
I could then use this type as part of the socket message payload. From app/Socket/GameSocket.pre:
$farm = new FarmModel(10, 10,
function (PatchModel $patch) use (&$patches) {
array_push($patches, [
"x" => $patch->x,
"y" => $patch->y,
"wet" => $patch->wet,
"type" => $patch->type,
]);
}
);

Continue reading %Procedurally Generated Game Terrain with React, PHP, and WebSockets%

Link: https://www.sitepoint.com/procedurally-generated-game-terrain-reactjs-php-websockets/

Game Development with React and PHP: How Compatible Are They?

“I’d like to make a multiplayer, economy-based game. Something like Stardew Valley, but with none of the befriending aspects and a player-based economy."
I started thinking about this the moment I decided to try and build a game using PHP and React. The trouble is, I knew nothing about the dynamics of multiplayer games, or how to think about and implement player-based economies.

I wasn’t even sure I knew enough about React to justify using it. I mean, the initial interface — where I focus heavily on the server and economic aspects of the game — is perfectly suited for React. But what about when I start to make the farming /interaction aspects? I love the idea of building an isometric interface around the economic system.
I once watched a talk by dead_lugosi, where she described building a medieval game in PHP. Margaret inspired me, and that talk was one of the things that led to me writing a book about JS game development. I became determined to write about my experience. Perhaps others could learn from my mistakes in this case, too.

The code for this part can be found at: github.com/assertchris-tutorials/sitepoint-making-games/tree/part-1. I’ve tested it with PHP 7.1 and in a recent version of Google Chrome.

Setting Up the Back End
The first thing I searched for was guidance on building multiplayer economies. I found an excellent Stack Overflow thread in which folks explained various things to think about. I got about halfway through it before realizing I may have been starting from the wrong place.
"First things first: I need a PHP server. I’m going to have a bunch of React clients, so I want something capable of high-concurrency (perhaps even WebSockets). And it needs to be persistent: things must happen even when players aren’t around."
I went to work setting up an async PHP server — to handle high concurrency and support WebSockets. I added my recent work with PHP preprocessors to make things cleaner, and made the first couple of endpoints.
From config.pre:
$host = new Aerys\Host();
$host->expose("*", 8080);

$host->use($router = Aerys\router());
$host->use($root = Aerys\root(.."/public"));

$web = process .."/routes/web.pre";
$web($router);

$api = process .."/routes/api.pre";
$api($router);

I decided to use Aerys for the HTTP and WebSocket portions of the application. This code looked very different from the Aerys docs, but that’s because I had a good idea about what I needed.
The usual process for running an Aerys app was to use a command like this:
vendor/bin/aerys -d -c config.php

That’s a lot of code to keep repeating, and it didn’t handle the fact that I wanted to use PHP preprocessing. I created a loader file.
From loader.php:
return Pre\processAndRequire(__DIR__ . "/config.pre");

I then installed my dependencies. This is from composer.json:
"require": {
"amphp/aerys": "dev-amp_v2",
"amphp/parallel": "dev-master",
"league/container": "^2.2",
"league/plates": "^3.3",
"pre/short-closures": "^0.4.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
},

I wanted to use amphp/parallel, to move blocking code out of the async server, but it wouldn’t install with a stable tag of amphp/aerys. That’s why I went with the dev-amp_v2 branch.
I thought it would be a good idea to include some sort of template engine and service locator. I opted for PHP League versions of each. Finally I added pre/short-closures, both to handle the custom syntax in config.pre and the short closures I planned on using after…
Then I set about creating routes files. From routes/web.pre:
use Aerys\Router;
use App\Action\HomeAction;

return (Router $router) => {
$router->route(
"GET", "/", new HomeAction
);
};

And, from routes/api.pre:
use Aerys\Router;
use App\Action\Api\HomeAction;

return (Router $router) => {
$router->route(
"GET", "/api", new HomeAction
);
};

Though simple routes, these helped me to test the code in config.pre. I decided to make these routes files return closures, so I could pass them a typed $router, to which they could add their own routes. Finally, I created two (similar) actions.
From app/Actions/HomeAction.pre:
namespace App\Action;

use Aerys\Request;
use Aerys\Response;

class HomeAction
{
public function __invoke(Request $request,
Response $response)
{
$response->end("hello world");
}
}

One final touch was to add shortcut scripts, to launch dev and prod versions of the Aerys server.
From composer.json:
"scripts": {
"dev": "vendor/bin/aerys -d -c loader.php",
"prod": "vendor/bin/aerys -c loader.php"
},
"config": {
"process-timeout": 0
},

With all of this done, I could spin up a new server, and visit http://127.0.0.1:8080 just by typing:
composer dev

Continue reading %Game Development with React and PHP: How Compatible Are They?%

Link: https://www.sitepoint.com/game-development-with-reactjs-and-php-how-compatible-are-they/