Lateo.net - Flux RSS en pagaille (pour en ajouter : @ moi)

🔒
❌ À propos de FreshRSS
Il y a de nouveaux articles disponibles, cliquez pour rafraîchir la page.
À partir d’avant-hierInformatique & geek

Midscroll - Le clic-molette de Windows débarque sous Linux

Par : Korben ✨

Si vous ne connaissez pas Linux, il faut savoir que sur ce système d'exploitation, le clic milieu colle la sélection. Moi, c'est un truc que j'aime bien, mais c'est surtout un héritage de X11 qui se marche complètement dessus avec l'autoscroll . Du coup Firefox désactive le sien par défaut sur Linux, et Chromium ne l'active nativement que sous Windows. Mais c'était sans compter sur Grant Hendricks qui a décidé de faire autrement avec midscroll .

Midscroll ne s'accroche à aucun toolkit, et se branche sur l'entrée du noyau. Ensuite, il capte chaque souris en evdev , la re-émet dans un clone uinput , et glisse ses événements de molette au passage. Rien au-dessus n'a donc besoin de coopérer, donc Wayland et X11 s'en fichent, et vos applis Qt, GTK ou Electron ne voient qu'une molette ordinaire.

Les gens sous Windows qui utilisent l'autoscroll savent que la vitesse dépend de l'écart. Un centimètre sous le point d'appui et la page descend au ralenti, la moitié de l'écran ou plus bas et elle défile à toute berzingue. Et tant que la molette reste enfoncée, ça scroll sans s'arrêter. C'est super pratique quand on est face à des pages web ultra longues.

Alors pour Midscroll, la courbe d'accélération qu'a mise au point Grant, n'a pas été bricolée au feeling. En fait, c'est la même courbe que celle de Chromium, reprise telle quelle : 0,000008 × distance^2,2 en pixels par milliseconde, avec une zone morte de 15 px histoire de ne pas déclencher sur un clic simple...

Et comme le middle-drag, ça sert déjà dans un logiciel de CAO ou dans Minecraft, il y a une liste d'exclusion pour FreeCAD, OrcaSlicer et Minecraft dedans. Comme ça, tant que ces fenêtres sont au premier plan, midscroll se retire en silence.

Et si tenir le bouton vous gonfle parce que vous êtes trop faible, le mode toggle inverse la logique : le pointeur circule librement une fois le défilement lancé d'un clic, et le premier clic venu remet tout à l'arrêt. C'est le fonctionnement de l'explorateur Windows ET de Firefox, et c'est une fonctionnalité qui a été beaucoup réclamée, même si on perd la faculté de coller du texte qui a été surligné.

Bien sûr, toutes les valeurs sont paramétrables. On peut régler la vitesse à laquelle ça part, la cadence des événements et dans quel sens ça défile.

Côté installation, des paquets pour Arch, Debian/Ubuntu et Fedora sont dispo, plus un install.sh pour le reste. Le flatpak, lui, est hors jeu car son bac à sable ferme totalement l'accès à uinput.

Le projet est hyper jeune, donc traitez-le comme tel et n'hésitez pas à contribuer pour soutenir le dev. Dans le registre confort Windows sous Linux, j'avais parlé de Wubuntu qui va beaucoup plus loin dans le mimétisme, et côté Wayland je vous avais montré niri et son défilement infini de fenêtres.

À tester et si ça vous gonfle, un sudo systemctl stop midscroll et on n'en parle plus.

PyPI verrouille vos vieilles releases contre les tokens volés

Par : Korben ✨

Bonne nouvelle pour tous ceux qui balancent du code sur PyPI. L'index officiel des paquets Python refuse désormais tout nouveau fichier ajouté à une release qui a plus de 14 jours. Le correctif vient de Seth Larson, développeur sécurité en résidence à la Python Software Foundation, et il colmate un trou que personne n'avait encore exploité sur PyPI... mais qui traînait là, grand ouvert.

Jusqu'ici, un mainteneur pouvait ajouter un fichier à n'importe quelle release, même sortie il y a 3 ans. Pratique pour livrer une nouvelle wheel, dangereux si un token de publication se fait voler. Un attaquant avec vos clés pouvait glisser un binaire vérolé dans une version stable que tout le monde télécharge depuis des lustres, sans déclencher la moindre alerte. Larson le dit sans détour : si ça n'a pas encore été abusé, c'est juste que les pirates n'avaient pas réalisé que c'était possible.

Le déclencheur, c'est l'affaire LiteLLM et Telnyx, deux paquets populaires compromis en mars dernier via une "référence mutable" dans leur usage de la GitHub Action Trivy. Encore une compromission de la chaîne d'appro, dans la lignée de Shai-Hulud sur npm dont je vous ai déjà parlé avec son scanner dédié , même si le mécanisme n'est pas le même. Le sujet mijotait depuis janvier 2024 dans les discussions autour de PEP 740, sauf qu'il coinçait sur un cas d'usage bien réel. En effet, certains projets ajoutent le support d'une nouvelle version de Python, genre les wheels cp314 pour Python 3.14, à d'anciennes releases longtemps après leur sortie.

Sauf que les chiffres ont tranché. En interrogeant la base PyPI sur les 15 000 paquets les plus populaires, seuls 56 avaient publié une wheel compatible 3.14 plus de 14 jours après une release. 56 sur 15 000, autant dire une poignée. Mike Fiedler, l'ingénieur sécurité de PyPI, a donc porté le débat au Packaging Summit de la PyCon US 2026, et le consensus est tombé. Il est maintenant demandé à ces projets de bumper vers une nouvelle version.

Après ne prenez pas cette nouvelle mesure de sécurité comme une garantie. Il n'existe aucune API pour vérifier qu'une release est "fermée", et les vraies règles du jeu ne seront gravées dans le marbre qu'avec l'API Upload 2.0 et les Staged Previews prévus par PEP 694. Donc pour l'instant, c'est un verrou qui protège, mais pas un vrai contrat de confiance sur lequel bâtir (De quoi Darty ??).

N'empêche que le bénéfice est immédiat car ça fait moins de ménage pour les admins PyPI quand un projet se fait trouer, et s'en est fini de l'état schizophrène où une release est à moitié compromise, à moitié saine, avec quelques fichiers vérolés planqués au milieu. Une vieille release devient un bloc figé, et voilà !

GitHub avait déjà dégainé la même idée avec ses releases immuables , qui rendent vos versions intouchables même par le mainteneur du projet.

Bref, une porte de moins pour les attaquants supply chain. Sympa non ?

Source (repéré chez Simon Willison)

BMASS - Bootez direct votre PC sur une IA locale

Par : Korben ✨

Balaji Bikshandi avait un rêve ! Il voulait booter sa machine directement sur un LLM sans avoir à passer par le moindre environnement de bureau ! Et il y est parvenu avec son outil BMASS , qui s'installe sur une clé USB de 8 Go, et qui embarque Alpine Linux, llama.cpp et un modèle Qwen3 0.6B évidemment quantisé.

Vous allumez l'ordi portable, Alpine démarre depuis la clé et vous tombez sur un prompt BMASS>. Et voilà à partir de là, vous pouvez causer à votre ordinateur en langage naturel. Ensuite, quand vous demandez à BMASS de faire des trucs, celui-ci injecte la commande qui va bien dans une balise et le runtime l'exécute pour de vrai sous un compte Linux non privilégié. Et ensuite, le LLM récupère la sortie brute, pour répondre, à partir de cette "preuve".

Operator: Which operating system is this?
Assistant: <shell>cat /etc/os-release</shell>

Tout le code de BMASS tient en 399 lignes de Python, et nécessite de faire tourner un llama-server en background sur le port 8080 avec 2048 tokens de contexte et 2 threads. Et ensuite lui fait le pont entre le modèle et le shell. Y'a rien de sorcier donc mais comme ça tourne sur du CPU, que c'est hors-ligne, et que ça peut se mettre sur des vieilles machines, c'est plutôt cool...

Voilà je vous laisse avec la vidéo que Balaji a filmée, ça montre le démarrage complet de son IA bootable :

Voir cette vidéo sur YouTube

Ah et petite subtilité qui va vous plaire, le code de BMASS contient une regex baptisée FALSE_EXECUTION_CLAIM dont le boulot est de détecter quand le modèle prétend avoir exécuté une commande alors qu'il n'a rien lancé du tout. Le runtime lui renvoie alors une correction pour lui dire qu'aucune commande n'a été exécutée lors de ce tour. Faut dire que la 0.6B de Qwen hallucine tellement parfois, qu'il lui fallait obligatoirement un garde-fou.

Donc, voilà, côté sécu c'est super léger... y'a juste une regex qui bloque les sudo, doas, pkexec et autres su, mais c'est tout. Pas de conteneur, encore moins de namespace et surtout pas de liste blanche, donc si vous vous lancez, ce sera à déployer uniquement pour rigoler sur une vieille machine sans importance, parce que si demain, le modèle décide de lancer un rm -rf, faudra pas venir chialer ^^.

Petit service au passage si vous voulez tester, la doc d'installation vous fait copier le prompt système dans /opt/bmass/config/system-prompt.txt, sauf que le launcher le cherche dans /opt/bmass/system-prompt.txt.

Dans le genre modèle local qui tient dans presque rien, j'en ai parlé avec Llamafile qui fait tourner un LLM depuis un fichier unique. Et si les bidouilles minimalistes vous amusent, il y a aussi ce mini-PC Linux piloté entièrement en morse .

Perso, je doute que ça serve à grand-chose. Mais le concept est marrant !

Un compteur de visiteurs sur votre site, sans payer un centime

Par : Korben ✨

Vous avez peut-être remarqué un petit point rouge tout en bas de mon site, avec un nombre à côté. Il s'agit du nombre de personnes passées sur le site durant la dernière heure.

Je voulais remettre ce truc depuis un bail, bien à l'ancienne comme dans les années 2000 mais sur un site statique, qui plus est sans tracker de stats JS type Google Analytics ou Matomo, et sans cookies de tracking, c'était pas franchement une option... jusqu'à maintenant !

Le compteur, en vrai, tout en bas de korben.info.

La solution évidente sur des sites statiques, c'est souvent un petit Worker Cloudflare qui compte les visiteurs et servirait le chiffre, mais ça se facture à chaque requête. À 390 000 pages vues par jour, ça grimpe vite à des dizaines de millions d'invocations par mois, soit dans les 6 à 7 dollars. C'est pas super cher mais pour un compteur qui n'est utile qu'à satisfaire mon égo tout en sachant s'il y a du monde aujourd'hui, ça ne sert strictement à rien ! Donc le Worker, je l'ai écarté direct.

Du coup j'ai fait ça à l'ancienne. Un petit script Python tourne sur la machine qui héberge le site, une fois par minute. Il pose une seule question à Cloudflare, à savoir combien d'adresses IP distinctes ont chargé une page durant la dernière heure (ou demi-heure, ou quart d'heure ou 5 min, c'est vous qui paramétrez), il écrit la réponse dans un minuscule fichier live.json de quelques centaines d'octets, et c'est tout. Ce fichier, Cloudflare le sert ensuite depuis son cache comme il servirait une image, gratuitement. Zéro Worker, zéro base de données, zéro abonnement, j'ai exactement le même résultat sans dépenser une thune.

Maintenant, faut que je sois clair sur ce que ce chiffre raconte. C'est le nombre de navigateurs distincts ayant chargé une page durant la dernière heure, hors trafic interne de Cloudflare. C'est un "*combien de monde est passé récemment *", pas un "combien lisent là tout de suite".

Et les bots là-dedans ?

En fait, les bots pourris , ceux qui scrapent en boucle, se font bloquer en amont par le Super Bot Fight Mode de Cloudflare, donc ils n'arrivent même pas jusqu'à mon site. Restent les gentils bots, du genre de Googlebot et compagnie, que je laisse passer exprès, parce que les bloquer reviendrait à me flinguer mon référencement. Sur les 7 derniers jours, Cloudflare classe à peine 4% comme bots vérifiés. Donc c'est une goutte d'eau, surtout qu'ils tournent sur une poignée d'IP. Donc oui, mon compteur avale deux ou trois crawlers au passage, mais je ne voulais pas vous mentir en écrivant "zéro bot". Mais l'essentiel c'est que les nuisibles, eux, ne soient pas comptabilisés.

J'ai aussi dû gérer un petit piège car l'API de Cloudflare plafonne sa réponse à 10 000 lignes. Et comme sur une heure entière de trafic ça peut se remplir vite, si je crève ce plafond, la requête sous-compterait sans rien dire. Donc le script lève un flag et le compteur affiche "10 000 personnes ou plus" plutôt qu'un faux nombre. Quand j'y serai aux 10 000 et plus, je pense que je réduirai alors le delta temps en passant de 1h à 30 min...etc.

Côté vie privée, c'est carré également. Cloudflare renvoie à mon serveur une liste JSON des IP passées dans l'heure, mon script en compte le nombre de distinctes, et efface cette liste de sa mémoire dans la milliseconde qui suit. Aucune IP n'est stockée, aucune n'atterrit dans un log, aucun fichier avec les IPs n'est créé sur le disque... Il ne reste qu'un entier. Comme je vous le disais, pas de cookie , pas de traceur, et rien qui touche votre navigateur . Et comme le compteur ne s'affiche jamais en dessous de 10 personnes, impossible d'isoler qui que ce soit.

Maintenant, si vous voulez le même chez vous, sachez que j'ai tout balancé en open source sur GitHub , sous licence MIT, donc servez-vous. Voici les pré-requis :

  1. votre site doit être derrière Cloudflare, le plan gratuit suffit largement.
  2. vous générez un token API Cloudflare avec le droit de lecture sur les analytics.
  3. vous posez le script live_count.py sur votre serveur et vous le lancez une fois par minute (ou toutes les 5 ou 10 min) via un cron.
  4. vous ajoutez le bout de JavaScript et son span dans vos pages, tout se règle par des attributs, aucun script inline, donc ça passe même avec une politique de sécurité stricte.

Le seul truc sur lequel ne pas vous louper, c'est de mettre un temps de cache court à live.json. Si c'est trop long, tous vos visiteurs verraient un chiffre périmé.

Voilà. Un petit compteur maison simili-live sans tracking et qui ne me coûte rien, c'est le bonheur !

Lire la puce de sa carte d'identité en Python sous Linux

Par : Korben ✨

Hubert, fidèle lecteur de Korben.info m'a envoyé un mail pour me dire qu'il avait reçu sa nouvelle carte d'identité. Vous savez celle en petit format avec la puce dedans qu'on peut scanner avec l'app France Identité. Et il en est bien content !

Voilà, l'histoire s'arrête là !

Mais non, je plaisante ! En fait, Hubert s'est posé LA question que personne ne se pose à l'heure de l' identité numérique européenne : Y'a quoi là dedans ?

Et plutôt que d'attendre qu'un employé de mairie expert en technologie ne lui explique (j'rigole, ça n'existe pas), il a passé son week-end à coder cnie-python-tools , un projet codé en python (vous aviez deviné je pense) capable de lire la puce de la CNI et de vous ressortir les infos y compris la photo d'identité.

Le tout sous Linux, évidemment, sans smartphone ni app officielle.

Pour l'utiliser, vous devez brancher un lecteur de carte à contact (un ACR38U , un Omnikey (liens affiliés), ce genre de bestiole compatible PC/SC), vous lancez uv run cnie-dump, et vous tapez le CAN, c'est-à-dire les 6 chiffres imprimés au recto de votre carte.

Photo envoyée par Hubert, je me suis permis d'enlever ses données personnelles #RGPD-way-of-life ^^

Y'a besoin de cette clé car c'est elle qui permet de déverrouiller la puce via un protocole qui s'appelle PACE. C'est ce mécanisme précis qu'utilise la carte France Identité quand elle lit votre carte en NFC sauf que là c'est direct sur votre PC. Son script permet alors de récupérer toutes les data dans des fichiers bruts + un summary.json qui liste tout ce que la carte a bien voulu cracher.

Et c'est qu'elle est bavarde cette coquine, puisqu'avec ce simple script, elle vous sort votre état civil complet (nom, prénoms, date et lieu de naissance, nationalité), votre adresse, votre taille, la MRZ (la fameuse bande de caractères qu'on retrouve aussi sur les passeports), mais aussi la photo qui est dessus au format JPEG 2000, un format parfois un peu pénible à ouvrir.

Bref, de quoi remplir un formulaire administratif sans avoir à tout retaper.

Maintenant rassurez-vous, il y a quand même des données qu'on ne peut pas extraire. Sur la CNIe française, la donnée biométrique sensible, ce sont vos deux empreintes digitales (DG3), et celles-là restent bouclées à double tour derrière l'EAC, une couche de sécurité réservée aux terminaux officiels de l'État. Quand le script tape à cette porte, la carte répond aussi sèchement qu'un agent assermenté sans clim, avec le code 6982, ce qui veut dire "security status not satisfied", cause toujours.

Si ça vous dit d'essayer bien sûr, c'est à utiliser uniquement avec votre propre carte. Et si le lecteur sur la photo ci-dessus vous parle, c'est normal. Plutôt que d'acheter un lecteur de carte tout neuf, Hubert a simplement réalisé ses tests avec le lecteur fourni par les TCL (le réseau de transport Lyonnais) qui visiblement est dans le tur-fu en ce qui concerne la recharge des abonnements de métro ^^.

Merci Hubert pour le partage !!

cnie-python-tools

Le compilateur JIT de Python est menacé, et pas pour une raison technique

Le conseil de pilotage de Python, l'instance qui tranche les grandes décisions du langage, a demandé le 5 juin la suspension de tout nouveau développement sur son compilateur JIT.

Un JIT (just-in-time), c'est un compilateur à la volée : au lieu d'interpréter votre code ligne par ligne, il traduit les portions les plus sollicitées en instructions machine pendant l'exécution, histoire de gagner en vitesse. Python en a un, expérimental, depuis la version 3.13 sortie début 2024.

Le problème n'est pas le code. Il est dans la procédure.

Ce JIT est arrivé dans la branche principale de CPython, l'implémentation de référence du langage, sans passer par le circuit de décision habituel. Chez Python, toute évolution majeure doit faire l'objet d'un PEP, un document formel que la communauté discute puis valide. Celui qui couvre le JIT, le PEP 744 signé Brandt Bucher et Savannah Ostrowski, n'est qu'informatif et laisse plusieurs questions en suspens : la maintenance future, la compatibilité avec l'outillage existant, les critères de réussite mesurables.

Le conseil l'a reconnu noir sur blanc : il n'a pas été "aussi strict sur le respect du processus qu'un changement de cette ampleur le méritait". Responsabilité partagée, donc.

En pratique, plus aucune nouvelle fonctionnalité JIT ne peut atterrir sur la branche principale tant qu'un PEP en bonne et due forme n'est pas accepté. Les corrections de bugs et de sécurité, elles, continuent. Le conseil laisse une fenêtre de six mois pour soumettre et faire valider ce document. Passé ce délai, faute d'accord, le code du JIT sera purement et simplement retiré.

Le timing est mauvais. Le JIT amélioré était l'une des nouveautés mises en avant de Python 3.15, dont les fonctionnalités sont déjà gelées et dont la sortie est attendue en octobre. Sur du x86-64 sous Linux, il promet un gain de 8 à 9% en moyenne, même s'il reste désactivé par défaut et consomme 10 à 20% de mémoire en plus.

Mark Shannon, un des principaux contributeurs, n'a pas caché son agacement. Pour lui, tout arrêter d'un coup fait perdre l'élan et risque de faire fuir les nouveaux venus, alors il réclame une période de grâce pour avancer pendant que le PEP se construit. Barry Warsaw, lui, a demandé pourquoi le travail ne pourrait pas se poursuivre dans un dépôt séparé le temps des discussions.

La réponse du conseil tient en une idée : mettre le développement en pause évite que le JIT devienne une cible mouvante pendant qu'on débat de son sort.

Du coup, on se retrouve avec une techno qui fonctionne, déjà embarquée dans le langage, suspendue à un document qui n'existe pas encore.

Geler une techno qui marche pour une procédure oubliée, c'est agaçant sur le moment. Mais sur un langage utilisé par des millions de gens, c'est probablement plus prudent.

Source : The Register

BadHost - Un caractère et votre agent IA passe à l'ennemi

Par : Korben ✨

Les chercheurs de X41 D-Sec viennent de divulguer une faille critique baptisée BadHost (CVE-2026-48710) dans Starlette, le framework Python qui sert de fondation à FastAPI, vLLM , LiteLLM et une grande partie des serveurs MCP basés sur FastAPI.

325 millions de téléchargements par semaine, et il suffit d'injecter un seul caractère dans le header HTTP "Host" pour contourner les contrôles d'accès path-based qui lisent "request.url.path" dont autant dire que beaucoup de déploiements d'agents IA en production tournent en ce moment avec une porte d'entrée très mal verrouillée.

Le proof of concept publié par OSTIF donne ceci :

curl -i -H 'Host: foo' http://target/admin # 403, bloqué
curl -i -H 'Host: foo?' http://target/admin # 200, ça passe !!

Et c'est tout ! Un simple point d'interrogation collé au Host header, et l'endpoint "/admin" qui jusqu'alors filtrait les non-authentifiés s'ouvre alors aussi facilement que le claque-merde de mes haters ^^.

Donc si votre infra utilise FastAPI, vLLM ou LiteLLM exposés directement en ASGI (uvicorn, hypercorn, granian) sans reverse proxy strict devant, vous pouvez tester votre exposition immédiatement grâce au scanner de BadHost développé par Nemesis et X41 D-Sec.

Niveau mécanique, Starlette reconstruit l'objet "request.url" en concaténant la valeur du header "Host" avec le path de la requête, puis re-parse le tout. Sauf que la valeur de "Host" n'est jamais validée donc si vous y injectez un "/", un "?" ou un "#", vous décalez la frontière entre path, query et fragment au moment du re-parse.

Du coup, le routeur Starlette dispatche sur le vrai path de la requête HTTP (donc votre endpoint sensible s'exécute bien), mais les middlewares qui lisent "request.url.path" voient simplement un path empoisonné qui ne correspond plus à rien d'interdit.

Donc le contrôle d'accès saute et le code derrière tourne quand même. On est sur un score CVSS de 7/10 et la boite de sécu Secwest estime même que cette note est largement sous-estimée... En gros c'est super grave !

Car la portée réelle ce sont surtout les serveurs MCP qui peuvent stocker ou manipuler des tokens et identifiants pour accéder aux ressources externes auxquelles les agents IA se connectent : bases de données, comptes mail, calendriers, S3, webhooks...etc

Bref, le genre de "coffre-fort" que vous ne voulez pas voir ouvert via un header HTTP à la con malformé. Markus Vervier de X41 D-Sec a même publié un petit échantillon de ce que leurs scanners ont déjà trouvé en production : Des bases de données d'essais cliniques chez des biopharmas, des données de vérification d'identité avec PII en temps réel, des accès SSH à des équipements industriels via bastion, des boites mails complètes en lecture/écriture, des listes de souscripteurs CMS, des topologies AWS complètes avec metric queries.

Bref, l'écosystème agents IA vient de passer en mode naturiste !

Pour régler ce problème, vous devez donc mettre à jour vers Starlette 1.0.1 ou supérieur, dans tous vos déploiements LLM qui l'intègrent... Et là c'est le bordel parce qu'il y en a partout : Dans les images Docker, les virtualenvs et les artefacts "vendorisés" un peu partout... Donc faut tout rebuilder.

Et si vous avez du code custom, l'OSTIF recommande aussi de remplacer request.url.path par request.scope["path"] partout où une décision de sécurité est prise.

En gros, lire la valeur non reconstruite est le "fix" qui survivra aux prochaines versions du bug, parce que croyez-moi, ça reviendra à coup sûr !

Maintenant, côté infra, X41 D-Sec et OSTIF indiquent que nginx, Apache httpd et Cloudflare rejettent le PoC par défaut, mais ça ne doit pas vous empêcher de vérifier votre config. Donc ne traitez votre reverse proxy comme une mitigation qu'après l'avoir testé explicitement avec le scanner Nemesis.

Au-delà du correctif technique, BadHost rappelle une mécanique qu'on a déjà vue avec la faille RCE de llama-cpp-python à savoir que la chaîne d'approvisionnement de l'IA ne tient que sur quelques mainteneurs bénévoles qui prennent des risques personnels énormes pour patcher proprement.

Kludex, le mainteneur de Starlette, est actuellement sous une avalanche de reports depuis des mois. L'audit qui a permis de trouver le bug a par ailleurs été financé par OSTIF et AWS et sans ça, BadHost serait encore probablement dans la nature pour un an voire plus avant d'être découvert plus naturellement.

Donc si votre boîte fait tourner du LLM en prod via FastAPI, vLLM ou LiteLLM, vous avez aujourd'hui 2 choses urgentes à faire : 1/ passer votre infra dans le scanner Nemesis, et 2/ envoyer un petit don à Kludex pour le soutenir !

Sources : Ars Technica , OSTIF

Rocky - Le pote alien de Projet Dernière Chance débarque sur Raspberry Pi

Par : Korben ✨

J'sais pas si vous avez vu le film ou lu le livre mais Rocky, c'est l'araignée de roche extraterrestre de Projet Dernière Chance (Project Hail Mary) qui communique en chantant. Et Lahiru Maramba, un dev Firebase en poste chez Google, vient de le recréer en vrai avec un Raspberry Pi Zero 2W et un LLM local. Et voilà comme avoir un vrai pote Eridien posé sur votre bureau, qui vous répond en accords polyphoniques au lieu de parler.

L'architecture c'est ce que son concepteur appelle du "Voice Box & Brain". Le Pi Zero 2W tout seul est bien trop faiblard pour faire tourner un modèle de langage, du coup le Pi gère juste le hardware (micro, écran LCD, LED RGB, synthèse des accords) et balance l'audio brut à un Mac qui fait le gros du calcul. Le Mac transcrit ce que vous racontez avec mlx-whisper (un modèle Whisper-Tiny optimisé Apple Silicon), passe le texte à LM Studio qui fait tourner un Gemma 4 quantifié en local, et renvoie la réponse au Pi qui la joue en musique. Latence totale annoncée sur le repo, environ 2 secondes, soit, selon son propre benchmark, le même temps que via l'API Gemini dans le cloud, sauf que là, tout en local !

Le langage Eridien, lui, est fidèle au bouquin d'Andy Weir puisque chaque réponse est synthétisée en accords. Certains mots sont mappés sur des accords émotionnels précis, par exemple "amaze" sort en Mi majeur bien lumineux. Et pour les mots inconnus, ils sont hashés mathématiquement vers une signature de 3 fréquences, déterministe et permanente. Autrement dit, le même mot bizarre produira toujours exactement le même accord, comme un vrai vocabulaire qui se construit. C'est ce genre de petit détail qui fait la diff...

Côté matériel, il faut un Raspberry Pi Zero 2W et un PiSugar Whisplay HAT, un module tout-en-un qui apporte l'écran LCD, le bouton, la LED RGB et l'audio. De son côté, le repo propose 2 chemins d'install : la méthode "It Just Works" avec les drivers système précompilés (apt-get et c'est parti), ou la méthode isolée avec uv pour ceux qui veulent un environnement propre. Côté Mac, vous lancez LM Studio avec le modèle 4-bit quantifié sur le port 1234 et Y'a même un mode cloud avec une clé API Gemini si vous n'avez pas de Mac sous la main, ainsi qu'une fonctionnalité expérimentale planquée avec un générateur de sons façon R2-D2.

Pour la petite histoire, le film Projet Dernière Chance réalisé par Phil Lord et Christopher Miller est sorti en mars, avec Ryan Gosling en Ryland Grace et pour donner une voix à Rocky, les sound designers d'Hollywood ont tout simplement bossé avec un ocarina pour les aigus, une jarre pour les graves, et des chants de baleine, après avoir consulté Andy Weir sur l'anatomie du bestiau.

Je l'ai vu, et franchement, j'ai bien aimé. Je suis bien rentré dedans, même si j'aurais préféré que ce soit un peu plus "hard science" et un peu plus bidouille DIY comme l'était "Seul Sur Mars"... mais bon, il en faut pour tous les goûts.

Après si l'idée d'un compagnon IA DIY vous branche mais que vous voulez un truc plus généraliste et pas un Eridien qui chante, jetez un œil à Adeus , l'assistant IA personnel open source que j'avais couvert.

Quoiqu'il en soit, voici la vidéo complète où Lahiru montre tout le process, du câblage à Rocky qui prend vie :

Bref, c'est gratuit, c'est sous licence MIT, et le repo est juste ici .

Amusez-vous bien à construire votre petit pote Eridien !

JDownloader a diffusé des versions piégées, votre PC est peut-être compromis

Entre le 6 et le 7 mai 2026, le site officiel jdownloader.org a été compromis et a servi pendant un peu plus d'une journée des installeurs piégés à la place des versions légitimes du célèbre gestionnaire de téléchargements.

Concrètement, les liens alternatifs pour Windows et l'installateur shell pour Linux ont été remplacés par un loader qui déploie un RAT (Remote Access Trojan) écrit en Python sur la machine de la victime. Pour ceux qui ne connaissent pas, un RAT donne à l'attaquant un contrôle total à distance de votre PC : exécution de commandes, vol de données, installation d'autres malwares, et tout ce qui peut se faire avec un compte utilisateur compromis.

Bonne nouvelle dans le malheur. Tous les canaux de distribution n'ont pas été touchés. La version macOS est passée à travers, pareil pour les installations via Flatpak, Winget et Snap, ainsi que pour le package JAR principal de JDownloader. Seuls les liens "alternative download" Windows et le script shell Linux du site officiel sont contaminés. Si vous utilisez ces canaux pour vous mettre à jour, c'est sur eux qu'il faut vérifier.

Le problème a d'abord été relevé par un utilisateur Reddit, "PrinceOfNightSky", qui a constaté que les exécutables téléchargés étaient signalés par Microsoft Defender et signés par des éditeurs douteux (Zipline LLC, The Water Team) au lieu de la signature légitime AppWork GmbH.

Une fois alerté, le développeur de JDownloader a confirmé la fuite, mis le site hors ligne, et publié un rapport d'incident détaillé pour permettre l'analyse externe. La porte d'entrée des attaquants ? Une vulnérabilité du CMS du site qui permettait de modifier les listes de contrôle d'accès et le contenu sans authentification. Pas génial.

Le malware Windows fonctionne en deux étages. Un petit programme téléchargé sert de loader, qui récupère et exécute ensuite le vrai payload en se connectant à deux serveurs de commande nommés parkspringshotel[.]com et auraguest[.]lk. Architecture modulaire, ce qui veut dire que l'attaquant peut envoyer le code Python qu'il veut depuis ses serveurs et adapter sa charge en temps réel. Vol de mots de passe, persistance, mouvement latéral sur le réseau local, tout y est possible.

Si vous avez téléchargé JDownloader depuis le site officiel entre le 6 et le 7 mai, faites donc très attention. Réinstallez complètement l'OS et changez tous vos mots de passe. Un RAT donne suffisamment d'accès pour qu'un nettoyage par antivirus seul ne soit pas une garantie suffisante. Pénible mais c'est le seul moyen propre.

Source : Bleeping Computer

Scrapling - Le scraper Python qui se répare tout seul

Par : Korben ✨

Le scraping web, c'est un combat permanent contre les sites qui changent leur HTML toutes les deux semaines. Vous vous emmerdez à coder vos sélecteurs CSS, ça marche pendant un mois, puis le site refait son design et hop, votre script s'eteint en silence. C'est pourquoi Karim Shoair (alias D4Vinci sur GitHub) a sorti Scrapling, un framework Python qui s'adapte tout seul quand le DOM bouge.

La clé c'est adaptive=True sur n'importe quel sélecteur. Vous lui dites "je cherchais .product", Scrapling sauvegarde alors la signature de l'élément (texte, attributs, position dans l'arbre), et la prochaine fois que le site a renommé sa classe, il retrouve l'élément via similarité.

Concrètement ça donne ça :

from scrapling.fetchers import StealthyFetcher
StealthyFetcher.adaptive = True
page = StealthyFetcher.fetch('https://example.com', headless=True)
product = page.css_first('.product', adaptive=True) # Retrouve l'élément même si la classe a changé

Le truc marche grâce à un algo de similarité maison qui compare la structure DOM autour de l'élément. L'auteur lui-même a écrit un long post Medium intitulé " Creating self-healing spiders with Scrapling in Python without AI ", et ça résume bien la philosophie : pas de modèle IA mais juste des heuristiques solides !

La doc précise que adaptive=True ne sauvegarde que le premier élément de la sélection. Du coup si vous récupérez 50 produits d'un coup avec .css('.product'), seul le premier sera adapté. Faudra donc soit utiliser css_first comme dans l'exemple, soit boucler manuellement et appeler adaptive sur chaque élément. C'est bon à savoir...

Y'a également 3 fetchers selon le besoin. Fetcher pour les requêtes HTTP rapides avec spoofing TLS, StealthyFetcher qui passe Cloudflare Turnstile via un navigateur furtif (Camoufox sous le capot), et DynamicFetcher qui lance un Chromium ou un Chrome via Playwright pour les sites lourds en JS. Du coup vous pouvez démarrer léger en HTTP et basculer vers un navigateur uniquement quand un site bloque, sans réécrire votre code.

Côté perfs, le README annonce du lourd : 2 ms pour extraire 5000 éléments contre 1584 ms pour BeautifulSoup avec lxml. Sauf que Parsel et Scrapy font aussi 2 ms. Donc le gain vient du moteur lxml utilisé en direct, ce qui veut dire que si vous étiez déjà sur Scrapy, vous ne gagnerez pas en vitesse brute. Mais si vous traînez encore du BS4 partout, le saut sera énorme !

Sur le terrain anti-bot, ça se compare bien à Botasaurus dont je vous avais parlé. La différence c'est que Scrapling embarque un ProxyRotator natif et propose un blocage d'ads/trackers (~3500 domaines) activable via block_ads=True ou automatique en mode MCP, ce qui simplifie la vie quand vous tournez sur un serveur (où les IPs des datacenter se font régulièrement filtrer). Botasaurus, lui, vous laisse gérer la rotation à la main.

Détail sympa pour les bidouilleurs : y'a également un serveur MCP est intégré (pip install "scrapling[ai]"). Du coup Claude ou Cursor peuvent piloter Scrapling directement pour extraire des données, en réduisant la consommation de tokens car l'IA ne voit pas tout le HTML brut, juste ce qui est extrait. Pour les agents qui scrappent en boucle, c'est cool.

Notez que les sponsors Platinum du projet sont tous des fournisseurs de proxies (DataImpulse, BirdProxies, Evomi, etc.). C'est logique vu l'usage du framework, mais gardez en tête que pour bypasser un Cloudflare sérieux à grande échelle, vous aurez besoin de proxies résidentiels payants, donc d'eux. L'outil est gratuit, mais le contournement industriel ne l'est pas.

Pour installer, c'est pip install "scrapling[fetchers]" puis scrapling install pour récupérer les binaires navigateur. Une image Docker existe aussi (pyd4vinci/scrapling) et y'a même un shell interactif (scrapling shell) pour debugger vos sélecteurs en live.

Bref, c'est carrément pas mal pour ceux qui scrapent régulièrement. Alors si BS4 vous fait pleurer, allez voir par ici .

Et merci à Letsar pour le lien !

parallel-rsync - Empiler les rsync en parallèle sans galère

Par : Korben ✨

Vous synchronisez 4 ou 5 dossiers vers plusieurs serveurs avec rsync ? Alors vous connaissez ce sketch quand un job mouline pendant que les autres font la queue, parce que rsync de base c'est mono-thread et ça avance en file indienne.

Hé bien y'a un petit utilitaire Python qui dégoupille tout ça, pondu par overflowy. Ça s'appelle parallel-rsync et le nom annonce la couleur !

L'idée c'est de pouvoir empiler plusieurs jobs rsync en parallèle, avec une config YAML pour piloter le tout. Vous décrivez vos sources et destinations dans sync.yml, vous lancez parallel-rsync -c sync.yml --workers 4 --max-per-host 2, et hop, ça parallélise.

Le bougre tourne sur un ThreadPoolExecutor Python 3 qui spawn N processus rsync système avec un cap global et un cap par hôte. Et pendant ce temps, des barres de progression vous affichent l'avancement de chaque transfert sans que la console parte en sucette.

La dernière fois, je vous parlais de rsyncy qui collait juste une barre de progression à un rsync solo mais là, on monte clairement d'un cran avec une orchestration multi-cibles.

--workers cap c'est donc le nombre total de processus rsync simultanés (4 par défaut). --max-per-host limite la concurrence par destination (2 par défaut, histoire de ne pas saturer un seul serveur, parce que oui, balancer 8 rsync sur la même machine c'est juste se tirer une balle dans le pied côté I/O).

--timeout met une laisse à chaque rsync, --dry-run ajoute le flag à toutes les commandes pour tester avant de tirer, et --no-progress débraye les barres si vous voulez juste les logs. Côté logging, --log-file et --log-level font également le job.

Par contre y'a pas de retry automatique donc si une session SSH coupe en plein transfert, faudra relancer à la main. C'est logique mais un peu dommage.

Sur un homelab, ce genre de config YAML permet de résoudre le problème des synchros récurrentes avec un seul fichier centralisé au lieu de 8 scripts shell.

Notez aussi que le repo build un binaire universel via cosmofy , qui empaquette le tout en un exécutable cross-platform Windows, macOS et Linux d'un coup. Du coup, pas besoin d'installer Python sur la machine cible. Carrément pratique pour distribuer sur des serveurs où vous n'avez pas envie de gérer un environnement Python complet avec pip et un venv.

Petit point d'attention quand même : rsync lui-même doit être installé sur la machine qui lance le binaire, ce qui est natif sous macOS et Linux mais nécessite WSL ou Cygwin sous Windows.

Y'avait déjà msrsync qui découpe les transferts en buckets, parsyncfp qui s'appuie sur fpart pour grouper par taille, et la classique combine find . -type f | parallel -j10 rsync que tout sysadmin a bricolée un jour pour gratter de la bande passante. De son côté, overflowy se place plutôt sur le créneau "config déclarative" pour orchestrer plusieurs rsync entre sources et cibles.

Le code est sous licence MIT et tout se passe sur le repo GitHub . À tester si vous orchestrez régulièrement plusieurs rsync à la main.

CANviz - Analyser le bus CAN de sa voiture dans le navigateur

Par : Korben ✨

Vous voulez comprendre ce qui se passe dans le cerveau de votre bagnole ? Hé bien pour cela avant, il fallait du matos pro et des suites logicielles à licence annuelle. Mais maintenant, y'a CANviz .

Un pip install canviz, un module USB à quelques balles branché sur le bus CAN de la voiture, et hop, vous accédez à tous les secrets de votre voiture simplement en ouvrant votre navigateur sur localhost:8080. Toutes les trames qui circulent sur le réseau interne du véhicule s'affichent en direct dans un tableau qui défile sans ramer à 2000 fps si j'en crois le README, donc ça envoie !

Ce projet signé Chanchal Dhiman tourne sur n'importe quelle config équipée de Python 3.10 ou supérieur, et côté matériel, CANviz se branche sur plein de bazars tels que les modules à firmware Candlelight (genre FYSETC UCAN autour de 8 balles ou CANable 1.0 autour de 15), les périphériques slcan via port COM, et du matériel sérieux type PEAK PCAN-USB, Kvaser, Vector ou même socketcan sur Raspberry Pi. En gros, si votre clé USB CAN est compatible avec python-can, CANviz la gère !

L'interface décode alors les fichiers DBC (le format de base de données du CAN), donc au lieu de lire des paquets hexadécimaux chelous, vous voyez directement "vitesse moteur = 1450 rpm" ou "position accélérateur = 34%". Vous pouvez aussi filtrer par ID ou par nom de signal, et le filtre se garde dans l'URL. Comme ça, vous pouvez partager une vue à un pote en copiant simplement le lien.

Le truc vraiment pratique, c'est surtout la partie enregistrement. Vous capturez une session en .asc ou .csv, et vous la rejouez plus tard à vitesse variable (de 0.5x pour décortiquer lentement, jusqu'à 10x pour survoler), ou vous forgez vos propres trames depuis l'interface pour tester la réaction d'un module donné. Une API REST et du WebSocket ouvrent aussi la porte aux bricolages en Python, avec une doc interactive accessible sur /docs.

Autre truc malin, vu que c'est un serveur web derrière : vous pouvez déployer CANviz sur un Raspberry Pi planqué dans la bagnole et le consulter à distance en SSH. Par contre, pas de WebUSB ici. L'auteur a explicitement fait le choix de passer par python-can côté serveur pour des raisons de sécurité. L'accès USB reste donc dans le sandbox Python, et le browser ne touche rien. J'avoue, je préfère.

Le projet est sous licence MIT, et est encore jeune, mais l'approche est éprouvée. Pour ceux qui cherchent des alternatives desktop, y'a bien sûr CANgaroo côté Qt, ou SavvyCAN qui tourne aussi en natif. Et si vous voulez bidouiller votre voiture comme Charlie Miller l'a fait avec la Jeep , y'a toujours le Panda de Comma sorti en 2017 avec son soft Cabana.

Bref, pour quelques euros de module USB et un pip install des familles, vous pouvez transformer votre laptop en analyseur CAN niveau pro et ça c'est plutôt classe !

Source

OpenAI is acquiring open source Python tool-maker Astral

OpenAI announced Thursday that it has entered into an agreement to acquire Astral, the company behind popular open source Python development tools such as uv, Ruff, and ty, and integrate the company into its Codex team.

The deal, whose financial terms were not publicly disclosed, will help OpenAI "accelerate our work on Codex and expand what AI can do across the software development lifecycle," the company said in an announcement post. Integrating Astral's tools more closely with Codex after the acquisition will "enable AI agents to work more directly with the tools developers already rely on every day," it continued.

Astral's most popular open source projects include:

Read full article

Comments

Levelling up with Python: Create with data

Learning Python often starts with the same building blocks: variables, functions, and loops. However, once young people have learnt these essential foundations, they may be eager to grow their skills and start using Python to explore data and create something meaningful to them. 

A young learner showing a Python project in the Code Editor.

Our free ‘More Python’ project path helps learners move beyond the basics and use data to create impactful projects of their own.

Python as a tool for exploring the world

Python is the most widely used programming language in the world, not just because it’s accessible, but because it’s powerful. It is used to analyse data, build models, create data visualisations, and explore important questions.

A young learners is excited about his Python project.

For young learners, this means learning Python can become more than a coding exercise. It can be a way to investigate topics they care about, analyse and understand information, and tell powerful stories about real-world issues.

A illustration featuring examples of different types of graphs: a line graph, a bar chart, and a venn diagram.

Working with data helps learners see how coding connects to the world around them — and builds confidence along the way.

Why learning with data matters

In our day-to-day lives, data is everywhere: in sports results, maps, and scientific research, to name only a few examples. Learning how to work with data helps young people develop skills that go far beyond programming, including:

  • Thinking logically and solving problems
  • Interpreting and questioning information
  • Making decisions based on evidence

Data also underpins many of the AI systems people use today. For example, large language models, used to build tools such as ChatGPT, are trained on vast amounts of data. Therefore, understanding how data is collected, organised, and used is an important part of AI literacy.

In Python, structures like lists and dictionaries make it possible to organise, analyse, and explore data in creative ways. Using these tools to build projects can help abstract computing concepts start to feel more concrete and meaningful.

What learners create in the ‘More Python’ project path

The ‘More Python’ project path supports learners through three stages: Explore, Design, and Invent. Each stage builds skills while giving learners more ownership over what they create.

In the Explore stage, young people learn new concepts and build confidence in using data and core Python structures, such as lists and dictionaries. Projects include:

  • Making an interactive chart of Olympic medals
  • Building a model of the solar system
  • Creating a frequency graph that learners can analyse to crack a code

These projects help learners develop new skills, while exploring how Python can be used to analyse and explain real-world information.

A young learner uses the Code Club Projects site on computer to do Python coding.

As learners progress to the Design stage, they start making creative choices about how their projects look and behave. In this stage, they:

  • Create a project that produces encoded art based on a user’s name
  • Build an interactive world map that helps users learn interesting facts

Here, Python becomes a creative medium. As well as putting their new skills into practice, learners think about audience, interaction, and presentation to make their projects their own.

In the Invent stage, learners bring everything together. Using the skills they have built, they design and create a data visualisation on a topic they are passionate about. This final project gives learners the freedom to choose their data, shape their idea, and tell a story that matters to them.

An illustration of a robot on wheels.

By this point, learners are planning and creating their own projects, growing in confidence and independence.

Take the next step with Python

If the young people you support have already learned the basics of Python, ‘More Python’ offers a clear and creative next step. The projects are designed to be accessible, and young people can work through them at their own pace, whether they are learning independently, at a Code Club, or in the classroom.

By working with data, getting creative, and making their own original projects, learners can build confidence and start to see what they can achieve with Python.

Alongside the ‘More Python’ project path, you can access hundreds of free coding projects on our Code Club Projects site. Find more projects to suit your learners’ interests, and support them to build their digital skills through creativity and making.

The post Levelling up with Python: Create with data appeared first on Raspberry Pi Foundation.

Introducing picamzero: Simplifying Raspberry Pi Camera projects for beginners

Par : Laura Sach

Thousands of learners worldwide take their first steps into text-based programming using the Python programming language. Python is not only beginner-friendly, but is also used extensively in industry.

An educator helps two young learners with a coding project in a classroom.

In 2015, Python developer Daniel Pope, who has a keen interest in education, noticed that beginners often have great ideas for creating projects but struggle because the software libraries they need to use are aimed at more confident programmers. To address this, he created Pygame Zero — a simplified version of the popular PyGame software. Since then, various developers have expanded the range of ‘zero’ libraries for Python.

How Python zero libraries help beginner programmers

The Raspberry Pi Foundation has a long history of supporting Python zero libraries. GPIO Zero was launched back in 2015, followed by guizero and then picozero. The goal of all ‘zero’ libraries is the same: to help beginner programmers create amazing projects using simple, understandable code, supported by useful documentation. 

The Picamera2 library is a powerful tool for advanced users, but beginners — such as Astro Pi: Mission Space Lab programme participants — would benefit from a zero library to allow them to use the Raspberry Pi Camera module. 

The Astro Pi Mark II units.
The Astro Pi Mark II units
Image taken by Astro Pi: Mission Space Lab programme participants

Picamzero: how to get started

The Code Club Projects and Youth Programmes teams at the Raspberry Pi Foundation have joined forces to create picamzero: a new library that makes it simple for beginners to use the Raspberry Pi Camera board.

As with the other ‘zero’ libraries, it’s straightforward to get started. You can install picamzero by typing two commands in your Raspberry Pi’s terminal:

sudo apt update

sudo apt install python3-picamzero

Once it’s installed, setting up your program to communicate with your camera is easy:

from picamzero import Camera

cam = Camera()

You can ask picamzero to take a time-lapse sequence and make a video of your images using a single line of code.

cam.capture_sequence("mysequence.jpg", make_video=True)

Picamzero also makes it easy to add text and image overlays to your images.

A Lego scene captured using picamzero.
A Lego scene captured using picamzero

We’ve written beginner-friendly documentation for the new library so that you can explore what you can create using just a few lines of code. We’ve also updated our resources so that you can start making exciting projects using picamzero straight away:

We hope you enjoy using picamzero. Please get in touch if you have any feedback or suggestions. Happy coding!

The post Introducing picamzero: Simplifying Raspberry Pi Camera projects for beginners appeared first on Raspberry Pi Foundation.

Bridging the gap from Scratch to Python: Introducing ‘Paint with Python’

Par : Marc Scott

We have developed an innovative activity to support young people as they transition from visual programming languages like Scratch to text-based programming languages like Python.

An illustration of a web browser window with colourful tags and labels around it.

This activity introduces a unique interface that empowers learners to easily interact with Python while they create a customised painting app.

“The kids liked the self-paced learning, it allowed them to work at their own rate. They liked using RGB tables to find their specific colours.” – Code Club mentor

Why learn to code Python?

We’ve long been championing Python as an ideal tool for young people who want to start text-based programming. Python has simple syntax and needs very few lines of code to get started, and there is a vibrant community of supportive programmers surrounding it.

However, we know that starting with Python can be challenging for young people who have never done any text-based coding. They can face obstacles such as software installation issues, getting used to a new syntax, and the need for appropriate typing skills.

How ‘Paint with Python’ helps learners get started

‘Paint with Python’ is an online educational activity that addresses many of these challenges and helps young people learn to code Python for the first time. It’s entirely web-based, requiring no software installation beyond a web browser. Instructions are displayed in a side panel, allowing learners to read and code without needing to switch tabs.

To help young people with creating their painting app, much of the initial code is pre-written behind the scenes, which enables learners to focus on experimenting with Python and observing the outcomes. They engage with the code by clicking on suggested options or, in some cases, by typing small snippets of Python. For example, they can select colours from a range of options or, as they grow more confident, type RGB values to create custom colours.

The activity is fully responsive for mobile and tablet devices and provides a final view of the full program on the last page, together with suggested routes to continue learning text-based programming.

An accessible introduction to text-based programming

We believe this activity offers an accessible way for young learners to begin their journey with text-based programming and learning to code Python. The code they write is straightforward and the activity is designed to minimise errors. When mistakes do occur, the interface provides clear, constructive feedback, guiding learners to make corrections.

Try out ‘Paint with Python’ at rpf.io/paint-with-python. We’d love to hear your feedback! Please send any thoughts you have to uxresearch@raspberrypi.org. 

This activity was developed with support from the Cisco Foundation. Through our funding partnership with them, we’ve been able to provide thousands of young people with the inspiration and opportunity to progress their coding skills anywhere, and on any device.

The post Bridging the gap from Scratch to Python: Introducing ‘Paint with Python’ appeared first on Raspberry Pi Foundation.

Setting up VSCode for Ansible Lightspeed AI in Ubuntu 22.04 desktop

Par : Vivek Gite

Red Hat launched the Ansible Lightspeed Code Assistant Generative AI with IBM Watson Code Assistant in May 2023. This preview is now available to all Ansible users, allowing them to explore the technology, provide feedback to Red Hat, and further train the AI model. In this brief blog post, I will share my personal experience with installing and utilizing Ansible Lightspeed AI to create playbooks in VSCode using Ubuntu Linux 20.04 LTS desktop.

Love this? sudo share_on: Twitter - Facebook - LinkedIn - Whatsapp - Reddit

The post Setting up VSCode for Ansible Lightspeed AI in Ubuntu 22.04 desktop appeared first on nixCraft.

Kids’ coding languages

Par : Marc Scott

Programming is becoming an increasingly useful skill in today’s society. As we continue to rely more and more on software and digital technology, knowing how to code is also more and more valuable. That’s why many parents are looking for ways to introduce their children to programming. You might find it difficult to know where to begin, with so many different kids’ coding languages and platforms available. In this blog post, we explore how children can progress through different programming languages to realise their potential as proficient coders and creators of digital technology.

Two kids share their Scratch coding project on a laptop.

ScratchJr

Everyone needs to start somewhere, and one great option for children aged 5–7 is ScratchJr (Scratch Junior), a visual programming language with drag-and-drop blocks for creating simple programs. ScratchJr is available for free on Android and iOS mobile devices. It’s great for introducing young children to the basics of programming, and they can use it to create interactive stories and games.

Scratch

Moving on from ScratchJr, there’s its web-based sibling Scratch. Scratch offers drag-and-drop blocks for creating programs and comes with an assortment of graphics, sounds, and music for your child to bring their programs to life. This visual programming language is designed specifically for children to learn programming fundamentals. Scratch is available in multiple spoken languages and is perfect for beginners. It allows kids to create interactive stories, animations, and games with ease.

The Raspberry Pi Foundation has a wealth of free Scratch resources we have created specifically for young people who are beginners, such as the ‘Introduction to Scratch’ project path. And if your child is interested in physical computing to interact with the real world using code, they can also learn how to use electronic components, such as buzzers and LEDs, with Scratch and a Raspberry Pi computer.  

Young person using a laptop to code in Scratch, our favourite of all kids' coding languages.

MakeCode

Another fun option for children who want to explore coding and physical computing is the micro:bit. This is a small programmable device with an LED display, buttons, and sensors, and it can be used to create games, animations, interactive projects, and lots more. To control a micro:bit, a visual programming language called MakeCode can be used. The micro:bit can also be programmed using Scratch or text-based languages such as Python, offering an easy transition for children as their coding skills progress. Have a look at our free collection of micro:bit resources to learn more.

HTML

Everyone is familiar with websites, but fewer people know how they are coded. HTML is a markup language that is used to create the webpages we use every day. It’s a great language for children to learn because they can see the results of their code in real time, in their web browser. They can use HTML and CSS to create simple webpages that include links, videos, pictures, and interactive elements, all the while learning how websites are structured and designed. We have many free web design resources for your child, including a basic ‘Introduction to web development’ project path.

Three kids coding at laptops.

Python 

If your child is becoming confident with Scratch and HTML, then using Python is the recommended next stage in their learning. Python is a high-level text-based programming language that is easy to read and learn. It is a popular choice for beginners as it has a simple syntax that often reads like plain English. Many free Python projects for young people are available on our website, including the ‘Introduction to Python’ path.

A kid coding in Python on a laptop.

The Python community is also really welcoming and has produced a myriad of online tutorials and videos to help learners explore this language. Python can be used to do some very powerful things with ease, which is why it is so popular. For example, it is relatively simple to create Python programs to engage in machine learning and data analysis. If you wanted to explore large language models such as GPT, on which the ChatGPT chatbot is based, then Python would be the language of choice.

JavaScript 

JavaScript is the language of the web, and if your child has become proficient in HTML, then this is the next language for them. JavaScript is used to create interactive websites and web applications. As young people become more comfortable with programming, JavaScript is a useful language to progress to, given how ubiquitous the web is today. It can be tricky to learn, but like Python, it has a vast number of libraries of functions that people have already created for it to achieve things more quickly. These libraries make JavaScript a very powerful language to use.

Try out kids’ coding languages

There are many different programming languages, and each one has its own strengths and weaknesses. Some are easy to learn and use, some are really fast, and some are very secure.

Two kids coding together on Code Club World.

Starting with visual languages such as Scratch or MakeCode allows your child to begin to understand the basic concepts of programming without needing any developed reading and keyboard skills. Once their understanding and skills have improved, they can try out text-based languages, find the one that they are comfortable with, and then continue to learn. It’s fairly common for people who are proficient in one programming language to learn other languages quite quickly, so don’t worry about which programming language your child starts with.

Whether your child is interested in working in software development or just wants to learn a valuable — and creative — skill, helping them learn to code and try out different kids’ coding languages is a great way for you to open up new opportunities for them.

The post Kids’ coding languages appeared first on Raspberry Pi Foundation.

Test our new Code Editor for young people

We are building a new online text-based Code Editor to help young people aged 7 and older learn to write code. It’s free and designed for young people who attend Code Clubs and CoderDojos, students in schools, and learners at home.

The interface of the beta version of the Raspberry Pi Foundation's Code Editor.
The Code Editor interface

At this stage of development, the Code Editor enables learners to:

  • Write and run Python code right in their browser, with no setup required. The interface is simple and intuitive, which makes getting started with text-based coding easier.
  • Save their code using their Raspberry Pi Foundation account. We want learners to easily build on projects they start in the classroom at home, or bring a project they’ve started at home to their coding club.
A young person at a CoderDojo uses the Raspberry Pi Foundation's Code Editor.

We’ve chosen Python as the first programming language our Code Editor supports because it is popular in schools, CoderDojos, and Code Clubs. Many educators and young people like Python because they see it as similar to the English language. It is often the text-based language young people learn when they take their first steps away from a block-based programming environment, such as Scratch. 

Python is also widely used by professional programmers and usually tops at least one of the industry-standard indexes that ranks programming languages.

We will be adding support for web development languages (HTML/CSS/JavaScript) to the Editor in the near future.

We’re also planning to add features such as project sharing and collaboration, which we know young people will love. We want the Editor to be safe, accessible, and age-appropriate. As safeguarding is always at the core of what we do, we’ll only make new features available once we’ve ensured they comply with the ICO’s age-appropriate design code and our safeguarding policies.

Test the Code Editor and tell us what you think

We are inviting you to test the Code Editor as part of what we call the beta phase of development. As the Editor is still in development, some things might not look or work as well as we’d like — and this is why we need your help. 

A text output in the beta version of the Raspberry Pi Foundation's Code Editor.
Text output in the Code Editor

We’d love you to try the Editor out and let us know what worked well for you, what didn’t work well, and what you’d like to see next.

You can now try out the Code Editor in the first two projects of our ‘Intro to Python’ path. We’ve included a feedback form for you to let us know which project you tried, and what you think of the Editor. We’d love to hear from you.

Your feedback helps us decide what to do next. Based on what learners, educators, volunteers, teachers, and parents tell us, we will make the improvements to the Editor that matter most to the young people we aim to support.

Where next for the Code Editor?

One of our long-term goals is to engage millions of young people in learning about computing and how to create with digital technologies. We’re developing the Code Editor with three main aims in mind.

1. Supporting young people’s learning journeys

We aim to build the Code Editor so it:

  • Suits beginners and also supports them as their confidence and independence grows, so they can take on their own coding projects in a familiar environment
  • Helps learners to transition from block-based to text-based, informed by our deep understanding of pedagogy and computing education
  • Brings together projects instructions and code editing into a single interface so that young people do not have to switch screens, which makes coding easier

2. Removing barriers to accessing computing education

Our work on the Code Editor will:

  • Ensure it works well on mobile and tablet devices, and low-cost computers including the Raspberry Pi 4 2GB
  • Support localisation and translation, so we can tailor the Editor for the needs of young people all over the world

3. Making learning to program engaging for more young people

We want to offer a Code Editor that:

  • Enables young people to build a vast variety of projects because it supports graphic user interface output and supplies images and sprites for use in multimedia projects

We’re also planning on making the Editor available as an open source project so that other projects and organisations focussed on helping people learn to code can benefit. More on this soon.

Our work on the Code Editor has been generously funded by the Algorand Foundation and Endless, and we thank them for their generous support. If you are interested in partnering with us to fund this key work, please reach out to us via email.

The post Test our new Code Editor for young people appeared first on Raspberry Pi Foundation.

Take part in the Hour of Code

Par : Liz Smart

Launched in 2013, Hour of Code is an initiative to introduce young people to computer science using fun one-hour tutorials. To date, over 100 million young people have completed an hour of code with it. 

A girl doing a physical computing project.

Although the Hour of Code website is accessible all year round, every December for Computer Science Education Week people worldwide run their own Hour of Code events. Each year we love seeing many Code Clubs, CoderDojos, and young people at home across the community complete their Hour of Code. You can register your 2022 Hour of Code event now to run between 5 and 11 December. 

To support your event, we have pulled together a bumper set of our free coding projects, which can each be completed in just one hour. You will find these activities on the Hour of Code website.

Two young digital makers using Raspberry Pi

There’s something for all ages and levels of experience, so put an hour aside and help young people make something fabulous with code:

Ages 7–11

Beginner

For younger creators new to coding, a Scratch project is a great place to start. 

alt=""


With our Space talk project, they can create a space scene with characters that ‘emote’ to share their thoughts or feelings using sounds, colours, and actions. Creators program the character emotes using Scratch blocks to control graphic effects, costume animation, and sound effects. 

Alternatively, our Stress ball project lets them code an onscreen stress ball that reacts to user clicks. Creators use the Paint and Sound editors in Scratch to personalise a clickable stress ball, and they add Scratch blocks to control graphic effects, costume animation, and sound effects. 

We love this fun stress ball example sent to us recently by young creator April from the United States:

Another great option is to use Code Club World, which is a free tool to help children who are new to coding.  

Creators can develop a character avatar, design a T-shirt, make some music, and more.

Comfortable

For 7- to 11-year-olds who are more comfortable with block-based coding, our project Broadcasting spells is ideal to choose. With the project, they connect Scratch blocks to code a wand that casts spells turning sprites into toads, and growing and shrinking them. Creators use broadcast blocks to transform multiple sprites at once, and they create sound effects with the Sound editor in Scratch. 

alt=""

Ages 11–14

Beginner

We have three exciting projects for trying text-based coding during Hour of Code in this category. The first, Anime expressions, is one of our brand-new ‘Introduction to web development’ projects. With this project, young people create a responsive webpage with text and images for an anime drawing tutorial. They write HTML to structure the webpage and CSS styles to apply layout, colour palettes, and fonts. 

For a great introduction to coding with Python, we have the project Hello world from our ‘Introduction to Python’ path. With this project, creators write Python text-based code to create an interactive program that shows text and emojis based on user input. They learn about variables as they use them to store text and numbers, and they learn about writing functions to organise code and do calculations, retrieve the current date and time, and make a customisable dice. 

alt=""

LED firefly is a fantastic physical making project in which young people use a Raspberry Pi Pico microcontroller and basic electronic components to create a blinking LED firefly. They program the LED’s light patterns with MicroPython code and activate it via a switch they make themselves using jumper wires.

A blinking LED with paper wings.

Comfortable

For 11- to 14-year-olds who are already comfortable with HTML, the Flip treat webcards project is a fun option. With this, they create a webpage showing a set of cards that flip when a visitor’s mouse pointer hovers over them. Creators use CSS styling and animations to add interactivity, then they customise the cards with fancy fonts and colour gradients.

Young people who have already done some Python coding can try out our project Target practice. With this project they create a game, using the p5 graphics library to draw a colourful target, and writing code so that the player scores points by hitting the target’s rings with arrows. While they create the project, they learn about RGB colours, shape positioning with x and y coordinates, and decisions using if, else-if, and else code statements. 

Ages 14+

Beginner

Our project Charting champions is a great introduction to data visualisation and analysis for coders aged 15 and older. With the project, they will discover the power of the Python programming language as they store Olympic medal data in lists and use the pygal library to create an interactive chart.

alt=""

Comfortable

Teenage coders who feel comfortable with Python programming can use our project Solar system simulator to code an animated, interactive solar system model using the Python p5 graphics library. Their model will be interactive, as they’ll use dictionaries to store planet facts that display when a user clicks on an orbiting planet.

Coding for Hour of Code and beyond

Now is the time to register your Hour of Code event, then decide which project you’d like to support young people to create. You can download certificates for each of the creators from the Hour of Code certificates page.

And make sure to check out our project paths so you know what projects you can help the young people you support to code beyond this one hour of code. 

We don’t just create activities so that other people can experience coding and digital making — we also get involved ourselves!

Two members of the Code Club working at computers.

Recently, our teams who support the Code Club and CoderDojo networks got together to make LED fireflies. We are excited to get coding again as part of Hour of Code and Computer Science Education Week.

The post Take part in the Hour of Code appeared first on Raspberry Pi.

Learn to program in Python with our online courses

Par : Rosa Brown

If you’re new to teaching programming or looking to build or refresh your programming knowledge, we have a free resource that is perfect for you. Our ‘Learn to program in Python’ online course pathway is for educators who want to develop their understanding of the text-based language Python. Each course is packed with information and activities to help you apply what you learn in your classroom teaching.

A computing teacher and a learner do physical computing in the primary school classroom.

Why learn to program in Python?

Compared to many other programming languages, writing a program in Python is closer to writing in English, which makes starting to program much easier (if you have some proficieny in English). Python is also a general-purpose programming language, so once you’ve learned the basics, you can use Python for lots of different programming activities.

That’s why Python is a perfect choice for learning to program, and why many of our educational resources involve Python. Our seven online Python courses cover aspects from taking your first steps into programming, to writing a program to control an electronic circuit, to learning about object-oriented programming.

With time and practice, you will be able to use Python programming to create unique solutions to problems, build helpful tools, and make things that are important to you.

How does the Python course pathway work? 

The courses in the pathway have been written by our educators and include advice and activities to help you teach programming in your classroom. You can reuse the course activities to explain programming concepts to your learners and get them to write programs themselves. Because you will have first-hand experience of the activities, you’ll be able to anticipate your learners’ difficulties and adapt your lessons to suit them.

In a computing classroom, a smiling girl raises her hand.

All the courses are designed to take three or four weeks to complete, based on you spending two hours a week on participating. You can have free time-limited access to each course for the length of time it’s designed to take to complete. For example, if it’s a four-week course, like ‘Programming 101’, you can sign up for free to get four weeks of access.

The seven courses in the Python path can be completed in any order you like, and you can choose the courses that match your interests and needs.

A room of educators at desktop computers.

Each course involves activities that help you create a programming project using the concepts that you’re learning about. These activities are designed to be a fun and interactive way to reinforce what you’ve learned and can also be used with your learners in the classroom.

Course spotlight: Programming 101

If programming is completely new to you, our ‘Programming 101’ course is the best place to start. In ‘Programming 101’, we use this definition of programming to start with the idea that programming is about you telling a computer what to do: 

“Programming is how you get computers to solve problems.” 

We see programming as a chance to think creatively about a problem and about all the different ways it could be solved. While you might be unfamiliar with terms like programming, algorithms, or selection, the ‘Programming 101’ course demonstrates how they touch on things that many of us know from other areas of our lives.

On the course, you will:

  • Learn about basic programming concepts such as sequencing and repetition
  • Start to write your own programs
  • Discover how to interpret error messages to find and fix mistakes in your programs

What will you make in the courses?

Through building an understanding of programming, you will see how you can write your own programs to make games, quizzes, physical computing projects, and more. Here’s look at some of the things you could make in three of the seven courses: 

  • Programming 101: Write your first program in Python to make a personal assistant bot. You’ll discover how to make the output of your program respond to the user’s input.  
alt=""
You’ll write a program to create personal assistant bot in the ‘Programming 101’ course for beginners.
  • Programming with GUIs: Build a game where players compare two sets of emoji to find the emoji that matches. To make this game, you’ll use what you learn in the course to design the layout of a graphic user interface (GUI) and make sure only one emoji appears twice. 
alt=""
You’ll make an interactive graphic game in the ‘Programming with GUIs’ course.
  • Object-oriented Programming: Create a text-based adventure game with a character on a quest through different rooms! You’ll discover how to write a program that reacts to user input, and how to write your own code to create more challenges within the game based on your ideas.    

So check out our courses and start gaining Python programming skills today!

Python programming resources for young people

If you want to help your learners develop their understanding of programming in Python, you’ll be interested in these free resources we’ve created for young people: 

Introduction to Python: Our guided project path for learners who are new to text-based programming. We have created these projects with young people around the age of 9 to 13 in mind. Each project takes one hour to complete, and learners can make their own fun programs while learning about Python.

More Python: Our guided project path for learners who want to move beyond the ‘Intro to Python’ path to write programs that contain charts, artwork, and more. We’ve written these projects for young people around the age of 10 to 13.

Isaac Computer Science: This learning platform we’ve created for GCSE and A level students (age 14 to 18) uses Python and other text-based languages to teach the programming concepts within England’s computer science curriculum.   

The post Learn to program in Python with our online courses appeared first on Raspberry Pi.

How do I start my child coding?

Par : Marc Scott

You may have heard a lot about coding and how important it is for children to start learning about coding as early as possible. Computers have become part of our lives, and we’re not just talking about the laptop or desktop computer you might have in your home or on your desk at work. Your phone, your microwave, and your car are all controlled by computers, and those computers need instructions to tell them what to do. Coding, or computer programming, involves writing those instructions.

A boy types code at a CoderDojo coding club.

If children discover a love for coding, they will have an avenue to make the things they want to make; to write programs and build projects that they find useful, fun, or interesting. So how do you give your child the opportunity to learn about coding? We’ve listed some free resources and suggested activities below.

Scratch Junior 

If you have a young child under about 7 years of age, then a great place to begin is with ScratchJr. This is an app available on Android and iOS phones and tablets, that lets children learn the basics of programming, without having to worry about making mistakes.

ScratchJr programming interface.

Code Club World

The Raspberry Pi Foundation has developed a series of activities for young learners, on their journey to developing their computing skills. Code Club World provides a platform for children to play with code to design their own avatar, make it dance, and play music. Plus they can share their creations with other learners. 

“You could have a go too and discover Scratch together. The platform is designed for complete beginners and it is great fun to play with.”

Carol Thornhill, Engineering Science MA, Mathematics teacher

Scratch

For 7- to 11-year-old children, Scratch is a good way to begin their journey in coding, or to progress from ScratchJr. Like ScratchJr, Scratch is a block-based language, allowing children to assemble code to produce games, animations, stories, or even use some of the add-ons to interact with electronic devices and explore physical computing.

A girl with her Scratch project
A girl with a Scratch project she has coded.

The Raspberry Pi Foundation has hundreds of Scratch projects that your child can try out, but the best place to begin is with our Introduction to Scratch path, which will provide your child with the basic skills they need, and then encourage them to build projects that are relevant to them, culminating in their creation of their own interactive ebook.

Your child may never tire of Scratch, and that is absolutely fine — it is a fully functioning programming language that is surprisingly powerful, when you learn to understand everything it can do. Another advantage of Scratch is that it provides easy access to graphics, sounds, and interactivity that can be trickier to achieve in other programming languages.

Python 

If you’re looking for more traditional programming languages for your child to progress on to, especially when they reach 12 years of age or beyond, then we like to direct our young learners to the Python programming language and to the languages that the World Wide Web is built on, particularly HTML, CSS, and JavaScript.

Animation coded in Python of an archery target disk.
An animation coded using Python.

Our Python resources cover the basics of using the language, and then progress from there. Python is one of the most widely used languages when it comes to the fields of artificial intelligence and data science, and we have resources to support your child in learning about these fascinating aspects of technology. Our projects can even introduce your child to the world of electronics and physical computing with activities that use the inexpensive Raspberry Pi Pico, and a handful of electronic components, enabling your kids to create a wide variety of art installations and useful gadgets.

“Trying Python doesn’t mean you can’t go back to Scratch or switch between Scratch and Python for different purposes. I still use Scratch for some projects myself!”

Tracy Gardner, Computer Science PhD, former IBM Software Architect and currently a project writer at the Raspberry Pi Foundation
A young person codes at a Raspberry Pi computer.
Python is a great text-based programming language for young people to learn.

Coding projects

On our coding tutorials website we have many different projects to help your child learn coding and digital making. These range from beginner resources like the Introduction to Scratch path to more advanced activities such as the Introduction to Unity path, where children can learn how to make 3D worlds and games. 

“Our new project paths can be tackled by young creators on their own, without adult intervention. Paths are structured so that they build skills and confidence in the early stages, and then provide more open-ended tasks and inspirational ideas that creators can adapt or work from.”

Rik Cross, BSc (Hons), PGCE, former teacher and Director of Informal Learning at the Raspberry Pi Foundation

Web development 

The Web is integral to many of our lives, and we believe that it is important for children to have an understanding of the technology that drives it. That is why we have an Introduction to the Web path that allows children to develop their own web pages, focusing on the kinds of webpages that they want to build, be that sending a greeting card, telling a story, or creating a showcase of their projects.

A girl has fun learning to code at home on a tablet sitting on a sofa.
It’s empowering for children to learn to how the websites they visit are created with code.

Coding clubs 

Coding clubs are a great place for children to have fun and become more confident with coding, where they can learn through making and share their creations with each other. The Raspberry Pi Foundation operates the world’s largest network of coding clubs — CoderDojo and Code Club. 

“I have a new group of creators at my Code Club every year and my favourite part is when they realise they really can let their imagination run wild. You want to make an animation where a talking pineapple chases a snowman — absolutely. You want to make a piece of scalable art out of 1000 pixelated cartoon musical instruments — go right ahead. If you can code it, you can make it ”

Liz Smart, Code Club and CoderDojo mentor, former Solutions Architect and project writer for the Raspberry Pi Foundation
Three teenage girls at a laptop.
At Code Club and CoderDojo, many young people enjoy teaming up to code projects together.

Coding challenges 

Once your child has learnt some of the basics, they may enjoy entering a coding challenge! The European Astro Pi Challenge programme allows young people to write code and actually have it run on the International Space Station, and Coolest Projects gives children a chance to showcase their projects from across the globe.

A Coolest Projects participant
A girl with her coded creation at an in-person Coolest Projects showcase.

Free resources 

No matter what technology your child wants to engage with, there is a wealth of free resources and materials available from organisations such as the Raspberry Pi Foundation and Scratch Foundation, that prepare young people for 21st century life. Whether they want to become professional software engineers, tinker with some electronics, or just have a play around … encourage them to explore some coding projects, and see what they can learn, make, and do!


Author: Marc Scott, BSc (Hons) is a former Science, Computer Science, and Engineering teacher and the Content Lead for Projects at the Raspberry Pi Foundation.

The post How do I start my child coding? appeared first on Raspberry Pi.

Python coding for kids: Moving beyond the basics

We are excited to announce our second new Python learning path, ‘More Python’, which shows young coders how to add real data to their programs while creating projects from a chart of Olympic medals to an interactive world map. The six guided Python projects in this free learning path are designed to enable young people to independently create their own Python projects about the topics that matter to them.

A girl points excitedly at a project on the Raspberry Pi Foundation's projects site.
Two kids are at a laptop with one of our coding projects.

In this post, we’ll show you how kids use the projects in the ‘More Python’ path, what they can make by following the path, and how the path structure helps them become confident and independent digital makers.

Python coding for kids: Our learning paths

Our ‘Introduction to Python’ learning path is the perfect place to start learning how to use Python, a text-based programming language. When we launched the Intro path in February, we explained why Python is such a popular, useful, and accessible programming language for young people.

Because Python has so much to offer, we have created a second Python path for young people who have learned the basics in the first path. In this new set of six projects, learners will discover new concepts and see how to add different types of real data to their programs.

Illustration of different graph types
By following the ‘More Python’ path, young people learn the skills to independently create a data visualisation for a topic they are passionate about in the final project.

Key questions answered

Who is this path for?

We have written the projects in this path with young people around the age of 10 to 13 in mind. To code in a text-based language, a young person needs to be familiar with using a keyboard, due to the typing involved. Learners should have already completed the ‘Introduction to Python’ project path, as they will build on the learning from that path.

Three young tech creators show off their tech project at Coolest Projects.

How do young people learn with the projects? 

Young people need access to a web browser to complete our project paths. Each project contains step-by-step instructions for learners to follow, and tick boxes to mark when they complete each step. On top of that, the projects have steps for learners to:

  • Reflect on what they have covered in the project
  • Share their projects with others
  • See suggestions to upgrade their projects

Young people also have the option to sign up for an account with us so they can save their progress at any time and collect badges.

A young person codes at a Raspberry Pi computer.

While learners follow the project instructions in this project path, they write their code into Trinket, a free web-based coding platform accessible in a browser. Each project contains a link to a starter Trinket, which includes everything to get started writing Python code — no need to install any additional software.

Screenshot of Python code in the online IDE Trinket.
This is what Python code on Trinket looks like.

If they prefer, however, young people also have the option of instead writing their code in a desktop-based programming environment, such as Thonny, as they work through the projects.

What will young people learn?  

To use data in their Python programs, the project instructions show learners how to:

  • Create and use lists
  • Create and use dictionaries
  • Read data from a data file

The projects support learners as they explore new concepts of digital visual media and: 

  • Create charts using the Python library Pygal
  • Plot pins on a map
  • Create randomised artwork

In each project, learners reflect and answer questions about their work, which is important for connecting the project’s content to their pre-existing knowledge.

In a computing classroom, a girl laughs at what she sees on the screen.

As they work through the projects, learners see different ways to present data and then decide how they want to present their data in the final project in the path. You’ll find out what the projects are on the path page, or at the bottom of this blog post.

The project path helps learners become independent coders and digital makers, as each project contains slightly less support than the one before. You can read about how our project paths are designed to increase young people’s independence, and explore our other free learning paths for young coders

How long will the path take to complete?

We’ve designed the path to be completed in around six one-hour sessions, with one hour per project, at home, in school, or at a coding club. The project instructions encourage learners to add code to upgrade their projects and go further if they wish. This means that young people might want to spend a little more time getting their projects exactly as they imagine them.

In a classroom, a teacher and a student look at a computer screen while the student types on the keyboard.

What can young people do next?

Use Unity to create a 3D world

Unity is a free development environment for creating 3D virtual environments, including games, visual novels, and animations, all with the text-based programming language C#. Our ‘Introduction to Unity’ project path for keen coders shows how to make 3D worlds and games with collectibles, timers, and non-player characters.

Take part in Coolest Projects Global

At the end of the ‘More Python’ path, learners are encouraged to register a project they’ve made using their new coding skills for Coolest Projects Global, our free and world-leading online technology showcase for young tech creators. The project they register will become part of the online gallery, where members of the Coolest Projects community can celebrate each other’s creations.

A young coder shows off her tech project for Coolest Projects to two other young tech creators.

We welcome projects from all young people, whether they are beginners or experienced coders and digital makers. Coolest Projects Global is a unique opportunity for young people to share their ingenuity with the world and with other young people who love coding and creating with digital technology.

Details about the projects in ‘More Python’
The ‘More Python’ path is structured according to our Digital Making Framework, with three Explore project, two Design projects, and a final Invent project.

Explore project 1: Charting champions

Illustration of a fast-moving, smiling robot wearing a champion's rosette.
In this Explore project, learners discover the power of lists in Python by creating an interactive chart of Olympic medals. They learn how to read data from a text file and then present that data as a bar chart.

Explore project 2: Solar system

Illustration of our solar system.
In this Explore project, learners create a simulation of the solar system. They revisit the drawing and animation skills that they learned in the ‘Introduction to Python’ project path to produce animated planets orbiting the sun. The animation is based on real data taken from a data file to simulate the speed that the planets move at as they orbit. The simulation is also interactive, using dictionaries to display data about the planets that have been selected.

Explore project 3: Codebreaker

Illustration of a person thinking about codebreaking.
The final Explore project gets learners to build on their knowledge of lists and dictionaries by creating a program that encodes and decodes a message using an Atbash cipher. The Atbash cipher was originally developed in the Hebrew language. It takes the alphabet and matches it to its reverse order to create a secret message. They also create a script that checks how many times certain letters have been used in an encoded message, so that they can discover patterns.

Design project 1: Encoded art

Illustration of a robot painting a portrait of another robot.
The first Design project allows learners to create fun pieces of artwork by encoding the letters of their name into images, patterns, or drawings. Learners can choose the images that will be produced for each letter, and whether these appear at random or in a geometric pattern.
Learners are encouraged to share their encoded artwork in the community library, where there are lots of fun projects to discover already. In this project, learners apply all of the coding skills and knowledge covered in the Explore projects, including working with dictionaries and lists.

Design project 2: Mapping data

Illustration of a map and a hand of someone marking it with a large pin.
In the next Design project, learners access data from a data file and use it to create location pins on a world map. They have six datasets to choose from, so they can use one that interests them. They can also choose from a variety of maps and design their own pin to truly personalise their projects.

Invent project: Persuasive data presentation

Illustration of different graph types
This project is designed to use all of the skills and knowledge covered in this path, and most of the skills from the ‘Introduction to Python’ path. Learners can choose from eight datasets to create data visualisations. They are also given instructions on how to access and prepare other datasets if they want to visualise data about a different topic.
Once learners have chosen their dataset, they can decide how they want it to be displayed. This could be a chart, a map with pins, or a unique data visualisation. There are lots of example projects to provide inspiration for learners. One of our favourites is the ISS Expedition project, which places flags on the ISS depending on the expedition number you enter.

The post Python coding for kids: Moving beyond the basics appeared first on Raspberry Pi.

Coding for kids: Art, games, and animations with our new beginners’ Python path

Python is a programming language that’s popular with learners and educators in clubs and schools. It also is widely used by professional programmers, particularly in the data science field. Many educators and young people like how similar the Python syntax is to the English language.

Two girls code together at a computer.

That’s why Python is often the first text-based language that young people learn to program in. The familiar syntax can lower the barrier to taking the first steps away from a block-based programming environment, such as Scratch.

In 2021, Python ranked in first place in an industry-standard popularity index of a major software quality assessment company, confirming its favoured position in software engineering. Python is, for example, championed by Google and used in many of its applications.

Coding for kids in Python

Python’s popularity means there are many excellent resources for learning this language. These resources often focus on creating programs that produce text outputs. We wanted to do something different.

Two young people code at laptops.

Our new ‘Introduction to Python’ project path focuses on creating digital visuals using the Python p5 library. This library is like a set of tools that allows you to get creative by using Python code to draw shapes, edit images, and create frame-by-frame animations. That makes it the perfect choice for young learners: they can develop their knowledge and skills in Python programming while creating cool visuals that they’ll be proud of. 

What is in the ‘Introduction to Python’ path?

The ‘Introduction to Python’ project path is a set of written coding instructions, designed according to our Digital Making Framework.

How the 'Intro to Python' path is shown on our website.
How the ‘Intro to Python’ path is shown on our website.

Through the Framework, we encourage learners to become independent coders and digital makers by gently removing scaffolding as they progress along the projects in a path. Paths begin with three Explore projects, in which learners are guided through tasks that introduce them to new coding skills. Next, learners complete two Design projects. Here, they are encouraged to practise their skills and bring in their own interests to personalise their coding creations. Finally, learners complete one Invent project. This is where they put everything that they have learned together and create something unique that matters to them.

""
Emoji, archery, rockets, art, and movement are all part of this Python path.

The structure of our Digital Making Framework means that learners experience the structured development process of a coding project and learn how to turn their ideas into reality. The Framework also supports with finding errors in their code (debugging), showing them that errors are a part of computer programming and just temporary setbacks that you can overcome.

What coding skills and knowledge will young people learn?

The Explore projects are where the initial learning takes place. The key programming concepts covered in this path are:

  • Variables
  • Performing calculations with variables
  • Using functions
  • Using selection (if, elif and else)
  • Using repetition (for loops)
  • Using randomisation
  • Importing from libraries

Learners also explore aspects of digital visual media concepts:

  • Coordinates
  • RGB colours
  • Screen size
  • Layers
  • Frames and animation

Learners then develop these skills and knowledge by putting them into practice in the Design and Invent projects, where they add in their own ideas and creativity. 

Explore project 1: Hello world emoji

In the first Explore project of this path, learners create an interactive program that uses emoji characters as the visual element.

""

This is the first step into Python and gets learners used to the syntax for printing text, using variables, and defining functions.

Explore project 2: Target practice

In this Explore project, learners create an archery game. They are introduced to the p5 library, which they use to draw an archery board and create the arrows.

""

The new programming concept covered in this project is selection, where learners use if, elif and else to allocate points for the game.

Explore project 3: Rocket launch

The final Explore project gets learners to animate a rocket launching into space. They create an interactive animation where the user is asked to enter an amount of fuel for the rocket launch. The animation then shows if the fuel is enough to get the rocket into orbit.

""

The new programming concept covered here is repetition. Learners use for loops to animate smoke coming from the exhaust of the rocket.

Design project 1: Make a face

The first Design project allows learners to unleash their creativity by drawing a face using the Python coding skills that they have built in the Explore projects. They have full control of the design for their face and can explore three examples for inspiration.

""

Learners are also encouraged to share their drawings in the community library, where there are lots of fun projects to discover already. In this project, learners apply all of the coding skills and knowledge covered in the Explore projects, including selection, repetition, and variables.

Design project 2: Don’t collide!

In the second Design project, learners code a scrolling game called ‘Don’t collide’, where a character or vehicle moves down the screen while having to avoid obstacles.

""

Learners can choose their own theme for the game, and decide what will move down the screen and what the obstacles will look like. In this project, they also get to practice everything they learned in the Explore projects. 

Invent project: Powerful patterns

This project is the ultimate chance for learners to put all of their skills and knowledge into practice and get creative. They design their own unique patterns and create frame-by-frame animations.

""

The Invent project offers ingredients, which are short reminders of all the key skills that learners have gained while completing the previous projects in the path. The ingredients encourage them to be independent whilst also supporting them with code snippets to help them along.

Key questions answered

Who is the ‘Introduction to Python’ path for?

We have written the projects in the path with young people around the age of 9 to 13 in mind. To code in a text-based language, a young person needs to be familiar with using a keyboard, due to the typing involved. A learner may have completed one of our Scratch paths prior to this one, but this isn’t essential. and we encourage beginner coders to take this path first if that is their choice.

A young person codes at a Raspberry Pi computer.

What software do learners need to code these projects?

A web browser. In every project, starter code is provided in a free web-based development environment called Trinket, where learners add their own code. The starter Trinkets include everything that learners need to use Python and access the p5 library.

If preferred, the projects also include instructions for using a desktop-based programming environment, such as Thonny.

How long will the path take to complete?

We’ve designed the path to be completed in around six one-hour sessions, with one hour per project. However, the project instructions encourage learners to upgrade their projects and go further if they wish. This means that young people might want to spend a little more time getting their projects exactly as they imagine them.

Can a young person save their progress through the path?

Yes, if you or your young person sign up for an account, progress will be saved. The account will also show what other projects on our website the young person has completed.

What can young people do next after completing this path?

Taking part in Coolest Projects Global

At the end of the path, learners are encouraged to register a project they’re making with their new coding skills for Coolest Projects Global, our world-leading online technology showcase for young people.

Three young tech creators show off their tech project at Coolest Projects.

Taking part is free, all online, and beginners as well as more experienced young tech creators are welcome and invited. This is their unique opportunity to share their ingenuity in an online gallery for the world and the Coolest Projects community to celebrate.

Coding more Python projects with us

Coming very soon is our ‘More Python’ path. In this path, learners will move beyond the basics they learned in Introduction to Python. They will learn how to use lists, dictionaries, and files to create charts, models, and artwork. Keep your eye on our blog and social media for the release of ‘More Python’.

The post Coding for kids: Art, games, and animations with our new beginners’ Python path appeared first on Raspberry Pi.

Introducing Code Club World: a new way for young people to learn to code at home

Today we are introducing you to Code Club World — a free online platform where young people aged 9 to 13 can learn to make stuff with code.

Images from Code Club World, a free online platform for children who want to learn to code

In Code Club World, young people can:

  • Start out by creating their personal robot avatar
  • Make music, design a t-shirt, and teach their robot avatar to dance!
  • Learn to code on islands with structured activities
  • Discover block-based and text-based coding in Scratch and Python
  • Earn badges for their progress 
  • Share their coding creations with family, friends, and the Code Club World community

Learning to code at home with Code Club World: meaningful, fun, flexible

When we spoke to parents and children about learning at home during the pandemic, it became clear to us that they were looking for educational tools that the children can enjoy and master independently, and that are as fun and social as the computer games and other apps the children love.

A girl has fun learning to code at home, sitting with a laptop on a sofa, with a dog sleeping next to her and her father writing code too.
Code Club World is educational, and as fun as the games and apps young people love.

What’s more, a free tool for learning to code at home is particularly important for young people who are unable to attend coding clubs in person. We believe every child should have access to a high-quality coding and digital making education. And with this in mind, we set out to create Code Club World, an online environment as rich and engaging as a face-to-face extracurricular learning experience, where all young people can learn to code.

The Code Club World activities are mapped to our research-informed Digital Making Framework — a coding and digital making curriculum for non-formal settings. That means when children are in the Code Club World environment, they are learning to code and use digital making to independently create their ideas and address challenges that matter to them.

Islands in the Code Club World online platform for children who want to learn to code for free.
Welcome to Code Club World — so many islands to explore!

By providing a structured pathway through the coding activities, a reward system of badges to engage and motivate learners, and a broad range of projects covering different topics, Code Club World supports learners at every stage, while making the activities meaningful, fun, and flexible.

A girl has fun learning to code at home on a tablet sitting on a sofa.
Code Club World’s home island works as well on mobile phones and tablets as on computers.

We’ve also designed Code Club World to be mobile-friendly, so if a young person uses a phone or tablet to visit the platform, they can still code cool things they will be proud of.

Created with the community

Since we started developing Code Club World, we have been working with a community of more than 1000 parents, educators, and children who are giving us valuable input to shape the direction of the platform. We’ve had some fantastic feedback from them:

“I’ve not coded before, but found this really fun! … I LOVED making the dance. It was so much fun and made me laugh!”

Learner, aged 11

“I love the concept of having islands to explore in making the journey through learning coding, it is fabulous and eye-catching.”

Parent

The platform is still in beta status — this means we’d love you to share it with young people in your family, school, or community so they can give their feedback and help make Code Club World even better.

Together, we will ensure every child has an equal opportunity to learn to code and make things that change their world.

The post Introducing Code Club World: a new way for young people to learn to code at home appeared first on Raspberry Pi.

Code a Spectrum-style Crazy Golf game | Wireframe #54

Putt the ball around irrational obstacles in our retro take on golf. Mark Vanstone has the code

First released by Mr. Micro in 1983 – then under the banner of Sinclair Research – Krazy Golf was, confusingly, also called Crazy Golf. The loading screen featured the Krazy spelling, but on the cover, it was plain old Crazy Golf.

Designed for the ZX Spectrum, the game provided nine holes and a variety of obstacles to putt the ball around. Crazy Golf was released at a time when dozens of other games were hitting the Spectrum market, and although it was released under the Sinclair name and reviewed in magazines such as Crash, it didn’t make much impact. The game itself employed a fairly rudimentary control system, whereby the player selects the angle of the shot at the top left of the screen, sets the range via a bar along the top, and then presses the RETURN key to take the shot.

The game was called Crazy Golf on the cover, but weirdly, the loading screen spelled the name as Krazy Golf. The early games industry was strange.


If you’ve been following our Source Code articles each month, you will have seen the pinball game where a ball bounces off various surfaces. In that example, we used a few shortcuts to approximate the bounce angles. Here, we’re only going to have horizontal and vertical walls, so we can use some fairly straightforward maths to calculate more precisely the new angle as the ball bounces off a surface. In the original game, the ball was limited to only 16 angles, and the ball moved at the same speed regardless of the strength of the shot. We’re going to improve on this a bit so that there’s more flexibility around the shot angle; we’ll also get the ball to start moving fast and then reduce its speed until it stops.

Horizontal or vertical obstruction?

To make this work, we need to have a way of defining whether an obstruction is horizontal or vertical, as the calculation is different for each. We’ll have a background graphic showing the course and obstacles, but we’ll also need another map to check our collisions. We need to make a collision map that just has the obstacles on it, so we need a white background; mark all the horizontal surfaces red and all the vertical surfaces blue.

As we move the ball around the screen (in much the same way as our pinball game) we check to see if it has collided with a surface by sampling the colours of the pixels from the collision map. If the pixel’s blue, we know that the ball has hit a vertical wall; if it’s red, the wall’s horizontal. We then calculate the new angle for the ball. If we mark the hole as black, then we can also test for collision with that – if the ball’s in the hole, the game ends.

The pointer’s angle is rotated using degrees, but we’ll use radians for our ball direction as it will simplify our movement and bounce calculations.

Get the code

We have our ball bouncing mechanism, so now we need our user interaction system. We’ll use the left and right arrow keys to rotate our pointer, which designates the direction of the next shot. We also need a range-setting gizmo, which will be shown as a bar at the top of the screen. We can make that grow and shrink with the up and down arrows.

Then when we press the RETURN key, we transfer the pointer angle and the range to the ball and watch it go. We ought to count each shot so that we can display a tally to the player once they’ve putted the ball into the hole. From this point, it’s a simple task to create another eight holes – and then you’ll have a full crazy golf game!

Here’s Mark’s code for a simple golf game. To get it running on your system, you’ll need to install Pygame Zero. And for the full code, head to our Github.

Get your copy of Wireframe issue 55

You can read more features like this one in Wireframe issue 54, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 54 for free in PDF format.

The post Code a Spectrum-style Crazy Golf game | Wireframe #54 appeared first on Raspberry Pi.

Code your own pinball game | Wireframe #53

Get flappers flapping and balls bouncing off bumpers. Mark Vanstone has the code in the new issue of Wireframe magazine, available now.

There are so many pinball video games that it’s become a genre in its own right. For the few of you who haven’t encountered pinball for some reason, it originated as an analogue arcade machine where a metal ball would be fired onto a sloping play area and bounce between obstacles. The player operates a pair of flippers by pressing buttons on each side of the machine, which will in turn ping the ball back up the play area to hit obstacles and earn points. The game ends when the ball falls through the exit at the bottom of the play area.

NES Pinball
One of the earliest pinball video games – it’s the imaginatively-named Pinball on the NES.


Recreating pinball machines for video games

Video game developers soon started trying to recreate pinball, first with fairly rudimentary graphics and physics, but with increasingly greater realism over time – if you look at Nintendo’s Pinball from 1984, then, say, Devil’s Crush on the Sega Mega Drive in 1990, and then 1992’s Pinball Dreams on PC, you can see how radically the genre evolved in just a few years. In this month’s Source Code, we’re going to put together a very simple rendition of pinball in Pygame Zero. We’re not going to use any complicated maths or physics systems, just a little algebra and trigonometry.


Let’s start with our background. We need an image which has barriers around the outside for the ball to bounce off, and a gap at the bottom for the ball to fall through. We also want some obstacles in the play area and an entrance at the side for the ball to enter when it’s first fired. In this case, we’re going to use our background as a collision map, too, so we need to design it so that all the areas that the ball can move in are black.

Pinball in Python
Here it is: your own pinball game in less than 100 lines of code.


Next, we need some flippers. These are defined as Actors with a pivot anchor position set near the larger end, and are positioned near the bottom of the play area. We detect left and right key presses and rotate the angle of the flippers by 20 degrees within a range of -30 to +30 degrees. If no key is pressed, then the flipper drops back down. With these elements in place, we have our play area and an ability for the player to defend the exit.


All we need now is a ball to go bouncing around the obstacles we’ve made. Defining the ball as an Actor, we can add a direction and a speed parameter to it. With these values set, the ball can be moved using a bit of trigonometry. Our new x-coordinate will move by the sin of the ball direction multiplied by the speed, and the new y-coordinate will move by the cos of the ball direction multiplied by speed. We need to detect collisions with objects and obstacles, so we sample four pixels around the ball to see if it’s hit anything solid. If it has, we need to make the ball bounce.

Get the code

Here’s Mark’s pinball code. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

If you wanted more realistic physics, you’d calculate the reflection angle from the surface which has been hit, but in this case, we’re going to use a shortcut which will produce a rough approximation. We work out what direction the ball is travelling in and then rotate either left or right by a quarter of a turn until the ball no longer collides with a wall. We could finesse this calculation further to create a more accurate effect, but we’ll keep it simple for this sample. Finally, we need to add some gravity. As the play area is tilted downwards, we need to increase the ball speed as it travels down and decrease it as it travels up.

All of this should give you the bare bones of a pinball game. There’s lots more you could add to increase the realism, but we’ll leave you to discover the joys of normal vectors and dot products…

Get your copy of Wireframe issue 53

You can read more features like this one in Wireframe issue 53, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 53 for free in PDF format.

The post Code your own pinball game | Wireframe #53 appeared first on Raspberry Pi.

Recreate Gradius’ rock-spewing volcanoes | Wireframe #52

Code an homage to Konami’s classic shoot-’em-up, Gradius. Mark Vanstone has the code in the new edition of Wireframe magazine, available now.

Released by Konami in 1985, Gradius – also known as Nemesis outside Japan – brought a new breed of power-up system to arcades. One of the keys to its success was the way the player could customise their Vic Viper fighter craft by gathering capsules, which could then be ‘spent’ on weapons, speed-ups, and shields from a bar at the bottom of the screen.

Gradius screenshot
The Gradius volcanoes spew rocks at the player just before the end-of-level boss ship arrives.

Flying rocks

A seminal side-scrolling shooter, Gradius was particularly striking thanks to the variety of its levels: a wide range of hazards were thrown at the player, including waves of aliens, natural phenomena, and boss ships with engine cores that had to be destroyed in order to progress. One of the first stage’s biggest obstacles was a pair of volcanoes that spewed deadly rocks into the air: the rocks could be shot for extra points or just avoided to get through to the next section. In this month’s Source Code, we’re going to have a look at how to recreate the volcano-style flying rock obstacle from the game.

Our sample uses Pygame Zero and the randint function from the random module to provide the variations of trajectory that we need our rocks to have. We’ll need an actor created for our spaceship and a list to hold our rock Actors. We can also make a bullet Actor so we can make the ship fire lasers and shoot the rocks. We build up the scene in layers in our draw() function with a star-speckled background, then our rocks, followed by the foreground of volcanoes, and finally the spaceship and bullets.

Dodge and shoot the rocks in our homage to the classic Gradius.

Get the ship moving

In the update() function, we need to handle moving the ship around with the cursor keys. We can use a limit() function to make sure it doesn’t go off the screen, and the SPACE bar to trigger the bullet to be fired. After that, we need to update our rocks. At the start of the game our list of rocks will be empty, so we’ll get a random number generated, and if the number is 1, we make a new rock and add it to the list. If we have more than 100 rocks in our list, some of them will have moved off the screen, so we may as well reuse them instead of making more new rocks. During each update cycle, we’ll need to run through our list of rocks and update their position. When we make a rock, we give it a speed and direction, then when it’s updated, we move the rock upwards by its speed and then reduce the speed by 0.2. This will make it fly into the air, slow down, and then fall to the ground. 

Collision detection

From this code, we can make rocks appear just behind both of the volcanoes, and they’ll fly in a random direction upwards at a random speed. We can increase or decrease the number of rocks flying about by changing the random numbers that spawn them. We should be able to fly in and out of the rocks, but we could add some collision detection to check whether the rocks hit the ship – we may also want to destroy the ship if it’s hit by a rock. In our sample, we have an alternative, ‘shielded’ state to indicate that a collision has occurred. We can also check for collisions with the bullets: if a collision’s detected, we can make the rock and the bullet disappear by moving them off-screen, at which point they’re ready to be reused.

That’s about it for this month’s sample, but there are many more elements from the original game that you could add yourself: extra weapons, more enemies, or even an area boss.

Here’s Mark’s volcanic code. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 52

You can read more features like this one in Wireframe issue 52, available directly from Raspberry Pi Press — we deliver worldwide.

Wireframe issue 52's cover

And if you’d like a handy digital version of the magazine, you can also download issue 52 for free in PDF format.

The post Recreate Gradius’ rock-spewing volcanoes | Wireframe #52 appeared first on Raspberry Pi.

Recreate Exerion’s pseudo-3D landscape | Wireframe #51

Swoop over mountains in our homage to Jaleco’s shooter. Mark Vanstone has the code in the latest issue of Wireframe magazine, out now.

Taking the shooting action of Galaxian from a few years earlier, Japanese developer Jaleco released Exerion in 1983. What helped Exerion stand out from other shoot-’em-ups of the period, though, was its pseudo-3D background, which used both a scrolling landscape and moving background elements to create the illusion of depth. This was quite an achievement considering the hardware of the day, and it’s still an eye-catching effect even now.


Exerion’s pseudo-3D effect helped the game stand out from the crowd of other shooters packed into arcades at the time.

Three main elements

To recreate Exerion’s scrolling in Pygame Zero, we need to break the effect down into three main elements. The first is the scrolling stripes that form the landscape’s base layer. These are followed by the elements that roll over the landscape as it scrolls down the screen. Then thirdly, there’s the player’s movement, which affects both the other two elements. Let’s start with the scrolling landscape, which is made of alternating coloured stripes. To give the sense of perspective, they start very thin on the horizon and, as they move down the screen, they grow in thickness. We can create this with a list that contains the heights of each stripe, increasing as we go through the list. Then in our draw() function, we run through the list, drawing the stripes downwards from the horizon using the heights in our list. Then we increase the height of each stripe. When the first stripe reaches a certain height, we take the last one off the end of the list and add it to the beginning, resetting its height to the smallest. 

Our homage to Exerion. You can’t tell from a static image, but the illusion of depth is amazing. Honest. 

Landscape details

The next items to code are the landscape details. These are buildings and hills that we want to move with the stripes so that it looks as though the player’s flying over them as they scroll by. We need to do this in two sections as some will be drawn behind the stripes as they’re over the horizon, while others will be in front of the stripes. We’ll give each landscape item an index which ties it to a stripe, but we’ll give items that are beyond the horizon negative indexes, and those in front, positive.

All the landscape items will start with a negative index to indicate that they all start beyond the horizon. So in the draw() function, we have an initial loop to draw all the items behind the horizon, and then while we’re drawing the stripes, we also draw the items which have the same index as the stripes, so they appear in front. Once we have these two parts, we’ll have a continuous carousel of stripes and landscape items.

Player aircraft

Now we need the player aircraft. We can move it around using the arrow keys, but we want to have the background graphics moving to give the impression of a 3D landscape: if the player moves upwards, we move the horizon down, and do the opposite if the player moves downwards. We then apply a parallax effect to the landscape items. The way we do this is by moving the items at the back a small amount in the opposite direction from the player’s movement, and as we work down through the items, they move more and more. This enhances the impression of depth. 

Once we’ve added a tilt to the aircraft as it turns, we have the makings of an Exerion clone. All that needs to be added are the aliens to shoot at – if you want to add these, then you could take the Galaxian routine from last month’s Source Code. 

Here’s Mark’s code for an Exerion-style, pseudo-3D background. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 51

You can read more features like this one in Wireframe issue 51, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 51 for free in PDF format.

The post Recreate Exerion’s pseudo-3D landscape | Wireframe #51 appeared first on Raspberry Pi.

Recreate Galaxian’s iconic attack patterns | Wireframe #50

Blast dive-bombing aliens in our salute to Namco’s classic. Mark Vanstone has the code

Aliens swoop down towards the player, bombing as they go. Back in 1979, this was a big step forward from Taito’s Space Invaders.

Hot on the heels of the original Space Invaders, Galaxian emerged as a rival space shooter in 1979. Released by Namco, Galaxian brought new colour and unpredictable motion to the alien enemy, who would swoop down on the defending player. Galaxian was so popular in arcades that Namco released a sequel, Galaga, two years later – that game complicated the attack patterns even more. It’s difficult to say how many ports and clones have been made of Galaxian, as there are several versions of similar games for almost every home platform.

The player’s role in Galaxian is similar to Space Invaders, in that they pilot a ship and need to destroy a fleet of aliens. With Galaxian, however, the aliens have a habit of breaking formation and swooping down towards the player’s ship, and dive-bombing it. The aim is to destroy all the enemy ships and move on to the next wave. The subsequent waves of enemies get more difficult as the player progresses. For this sample, we’re going to look at that swooping mechanic, and make the bare nuts and bolts of a Galaxian game with Pygame Zero.

Our Galaxian homage up and running in Pygame Zero.
Our homage to the classic Galaxian, with angry aliens that love to break formation.

First, Galaxian has a portrait display, so we can set the play area’s width and height to be 600 and 800 respectively. Next, we can create a scrolling backdrop of stars using a bitmap that we blit to the screen and move downwards every update. We need a second blit of the stars to fill in the space that the first one leaves as it scrolls down, and we could also have another static background image behind them, which will provide a sense of depth.

Next, we set up the player ship as an Actor, and we’ll capture the left and right arrow keys in the update() function to move the ship left and right on the screen. We can also fire off a bullet with the SPACE bar, which will travel up the screen until it hits an alien or goes off the top of the screen. As in the original Galaxian, you can only shoot one bullet at a time, so we only need one Actor for this.

The aliens are arranged in rows and move left and right across the screen together. We’ll stick to just one type of alien for this sample, but draw two rows of them. You could add extra types and any number of rows. When we create the alien Actors, we can also add a status flag, and we need to determine which side of the row they’re on as when they break formation, the two sides fly in opposite directions. In this case, there’ll be four aliens on the left of each row and four on the right. Once they’re set up in a list, we can iterate through the list on each update and move them backwards and forwards. While we’re moving our aliens, we can also check to see if they’ve collided with a bullet or the player ship. If the collision is with a bullet, the alien cycles through a few frames of an explosion using the status flag, and then, when their status reaches five, they’re no longer drawn. If the collision is with the player, then the player dies and the game’s over. We can also check a random number to see if the alien will start a bombing run; if so, we set the status to one, which will start calls to the flyAlien() function. This function checks which side the alien’s on and starts changing the alien’s angle, depending on the side. It also alters the x and y coordinates, depending on the angle. We’ve written this section in longhand for clarity, but this could be collapsed down a bit with the use of some multiplier variables for the x coordinates and the angles.

There we have it: the basics of Galaxian. Can you flesh it out into a full game?

Here’s Mark’s code for a Galaxian-style shooter with attacking groups of aliens. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 50

You can read more features like this one in Wireframe issue 50, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 50 for free in PDF format.

The post Recreate Galaxian’s iconic attack patterns | Wireframe #50 appeared first on Raspberry Pi.

Remake Manic Miner’s collapsing platforms | Wireframe #49

Traverse a crumbly cavern in our homage to a Spectrum classic. Mark Vanstone has the code

One of the most iconic games on the Sinclair ZX Spectrum featured a little man called Miner Willy, who spent his days walking and jumping from platform to platform collecting the items needed to unlock the door on each screen. Manic Miner’s underground world featured caverns, processing plants, killer telephones, and even a forest featuring little critters that looked suspiciously like Ewoks.

Written by programmer Matthew Smith and released by Bug-Byte in 1983, the game became one of the most successful titles on the Spectrum. Smith was only 16 when he wrote Manic Miner and even constructed his own hardware to speed up the development process, assembling the code on a TRS-80 and then downloading it to the Spectrum with his own hand-built interface. The success of Manic Miner was then closely followed by Jet Set Willy, featuring the same character, and although they were originally written for the Spectrum, the games very soon made it onto just about every home computer of the time.

Miner Willy makes his way to the exit, avoiding those vicious eighties telephones.

Both Manic Miner and Jet Set Willy featured unstable platforms which crumbled in Willy’s wake, and it’s these we’re going to try to recreate this month. In this Pygame Zero example, we need three frames of animation for each of the two directions of movement. As we press the arrow keys we can move the Actor left and right, and in this case, we’ll decide which frame to display based on a count variable, which is incremented each time our update() function runs. We can create platforms from a two-dimensional data list representing positions on the screen with 0 meaning a blank space, 1 being a solid platform, and 2 a collapsible platform. To set these up, we run through the list and make Actor objects for each platform segment.

For our draw() function, we can blit a background graphic, then Miner Willy, and then our platform blocks. During our update() function, apart from checking key presses, we also need to do some gravity calculations. This will mean that if Willy isn’t standing on a platform or jumping, he’ll start to fall towards the bottom of the screen. Instead of checking to see if Willy has collided with the whole platform, we only check to see if his feet are in contact with the top. This means he can jump up through the platforms but will then land on the top and stop. We set a variable to indicate that Willy’s standing on the ground so that when the SPACE bar is pressed, we know if he can jump or not. While we’re checking if Willy’s on a platform, we also check to see if it’s a collapsible one, and if so, we start a timer so that the platform moves downwards and eventually disappears. Once it’s gone, Willy will fall through. The reason we have a delayed timer rather than just starting the platform heading straight down is so that Willy can run across many tiles before they collapse, but his way back will quickly disappear. The disappearing platforms are achieved by changing the image of the platform block as it moves downward.

As we’ve seen, there were several other elements to each Manic Miner screen, such as roaming bears that definitely weren’t from Star Wars, and those dastardly killer telephones. We’ll leave you to add those.

Here’s Mark’s code for a Manic Miner-style platformer. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 49

You can read more features like this one in Wireframe issue 49, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 49 for free in PDF format.

The post Remake Manic Miner’s collapsing platforms | Wireframe #49 appeared first on Raspberry Pi.

Swing into action with an homage to Pitfall! | Wireframe #48

Grab onto ropes and swing across chasms in our Python rendition of an Atari 2600 classic. Mark Vanstone has the code

Whether it was because of the design brilliance of the game itself or because Raiders of the Lost Ark had just hit the box office, Pitfall Harry became a popular character on the Atari 2600 in 1982.

His hazardous attempts to collect treasure struck a chord with eighties gamers, and saw Pitfall!, released by Activision, sell over four million copies. A sequel, Pitfall II: The Lost Caverns quickly followed the next year, and the game was ported to several other systems, even making its way to smartphones and tablets in the 21st century.

Pitfall

Designed by David Crane, Pitfall! was released for the Atari 2600 and published by Activision in 1982

The game itself is a quest to find 32 items of treasure within a 20-minute time limit. There are a variety of hazards for Pitfall Harry to navigate around and over, including rolling logs, animals, and holes in the ground. Some of these holes can be jumped over, but some are too wide and have a convenient rope swinging from a tree to aid our explorer in getting to the other side of the screen. Harry must jump towards the rope as it moves towards him and then hang on as it swings him over the pit, releasing his grip at the other end to land safely back on firm ground.

For this code sample, we’ll concentrate on the rope swinging (and catching) mechanic. Using Pygame Zero, we can get our basic display set up quickly. In this case, we can split the background into three layers: the background, including the back of the pathway and the tree trunks, the treetops, and the front of the pathway. With these layers we can have a rope swinging with its pivot point behind the leaves of the trees, and, if Harry gets a jump wrong, it will look like he falls down the hole in the ground. The order in which we draw these to the screen is background, rope, tree-tops, Harry, and finally the front of the pathway.

Now, let’s get our rope swinging. We can create an Actor and anchor it to the centre and top of its bounding box. If we rotate it by changing the angle property of the Actor, then it will rotate at the top of the Actor rather than the mid-point. We can make the rope swing between -45 degrees and 45 degrees by increments of 1, but if we do this, we get a rather robotic sort of movement. To fix this, we add an ‘easing’ value which we can calculate using a square root to make the rope slow down as it reaches the extremes of the swing.

Our homage to the classic Pitfall! Atari game. Can you add some rolling logs and other hazards?

Our Harry character will need to be able to run backwards and forwards, so we’ll need a few frames of animation. There are several ways of coding this, but for now, we can take the x coordinate and work out which frame to display as the x value changes. If we have four frames of running animation, then we would use the %4 operator and value on the x coordinate to give us animation frames of 0, 1, 2, and 3. We use these frames for running to the right, and if he’s running to the left, we just mirror the images. We can check to see if Harry is on the ground or over the pit, and if he needs to be falling downward, we add to his y coordinate. If he’s jumping (by pressing the SPACE bar), we reduce his y coordinate.

We now need to check if Harry has reached the rope, so after a collision, we check to see if he’s connected with it, and if he has, we mark him as attached and then move him with the end of the rope until the player presses the SPACE bar and he can jump off at the other side. If he’s swung far enough, he should land safely and not fall down the pit. If he falls, then the player can have another go by pressing the SPACE bar to reset Harry back to the start.

That should get Pitfall Harry over one particular obstacle, but the original game had several other challenges to tackle – we’ll leave you to add those for yourselves.

Pitfall Python code

Here’s Mark’s code for a Pitfall!-style platformer. To get it working on your system, you’ll need to  install Pygame Zero.  And to download the full code and assets, head here.

Get your copy of Wireframe issue 48

You can read more features like this one in Wireframe issue 48, available directly from Raspberry Pi Press — we deliver worldwide.
Wireframe issue 48
And if you’d like a handy digital version of the magazine, you can also download issue 48 for free in PDF format.
A banner with the words "Be a Pi Day donor today"

The post Swing into action with an homage to Pitfall! | Wireframe #48 appeared first on Raspberry Pi.

Coding on Raspberry Pi remotely with Visual Studio Code

Jim Bennett from Microsoft, who showed you all how to get Visual Studio Code up and running on Raspberry Pi last week, is back to explain how to use VS Code for remote development on a headless Raspberry Pi.

Like a lot of Raspberry Pi users, I like to run my Raspberry Pi as a ‘headless’ device to control various electronics – such as a busy light to let my family know I’m in meetings, or my IoT powered ugly sweater.

The upside of headless is that my Raspberry Pi can be anywhere, not tied to a monitor, keyboard and mouse. The downside is programming and debugging it – do you plug your Raspberry Pi into a monitor and run the full Raspberry Pi OS desktop, or do you use Raspberry Pi OS Lite and try to program and debug over SSH using the command line? Or is there a better way?

Remote development with VS Code to the rescue

There is a better way – using Visual Studio Code remote development! Visual Studio Code, or VS Code, is a free, open source, developer’s text editor with a whole swathe of extensions to support you coding in multiple languages, and provide tools to support your development. I practically live day to day in VS Code: whether I’m writing blog posts, documentation or Python code, or programming microcontrollers, it’s my work ‘home’. You can run VS Code on Windows, macOS, and of course on a Raspberry Pi.

One of the extensions that helps here is the Remote SSH extension, part of a pack of remote development extensions. This extension allows you to connect to a remote device over SSH, and run VS Code as if you were running on that remote device. You see the remote file system, the VS Code terminal runs on the remote device, and you access the remote device’s hardware. When you are debugging, the debug session runs on the remote device, but VS Code runs on the host machine.

Photograph of Raspberry Pi 4
Raspberry Pi 4

For example – I can run VS Code on my MacBook Pro, and connect remotely to a Raspberry Pi 4 that is running headless. I can access the Raspberry Pi file system, run commands on a terminal connected to it, access whatever hardware my Raspberry Pi has, and debug on it.

Remote SSH needs a Raspberry Pi 3 or 4. It is not supported on older Raspberry Pis, or on Raspberry Pi Zero.

Set up remote development on Raspberry Pi

For remote development, your Raspberry Pi needs to be connected to your network either by ethernet or WiFi, and have SSH enabled. The Raspberry Pi documentation has a great article on setting up a headless Raspberry Pi if you don’t already know how to do this.

You also need to know either the IP address of the Raspberry Pi, or its hostname. If you don’t know how to do this, it is also covered in the Raspberry Pi documentation.

Connect to the Raspberry Pi from VS Code

Once the Raspberry Pi is set up, you can connect from VS Code on your Mac or PC.

First make sure you have VS Code installed. If not, you can install it from the VS Code downloads page.

From inside VS Code, you will need to install the Remote SSH extension. Select the Extensions tab from the sidebar menu, then search for Remote development. Select the Remote Development extension, and select the Install button.

Next you can connect to your Raspberry Pi. Launch the VS Code command palette using Ctrl+Shift+P on Linux or Windows, or Cmd+Shift+P on macOS. Search for and select Remote SSH: Connect current window to host (there’s also a connect to host option that will create a new window).

Enter the SSH connection details, using user@host. For the user, enter the Raspberry Pi username (the default is pi). For the host, enter the IP address of the Raspberry Pi, or the hostname. The hostname needs to end with .local, so if you are using the default hostname of raspberrypi, enter raspberrypi.local.

The .local syntax is supported on macOS and the latest versions of Windows or Linux. If it doesn’t work for you then you can install additional software locally to add support. On Linux, install Avahi using the command sudo apt-get install avahi-daemon. On Windows, install either Bonjour Print Services for Windows, or iTunes for Windows.

For example, to connect to my Raspberry Pi 400 with a hostname of pi-400 using the default pi user, I enter pi@pi-400.local.

The first time you connect, it will validate the fingerprint to ensure you are connecting to the correct host. Select Continue from this dialog.

Enter your Raspberry Pi’s password when promoted. The default is raspberry, but you should have changed this (really, you should!).

VS Code will then install the relevant tools on the Raspberry Pi and configure the remote SSH connection.

Code!

You will now be all set up and ready to code on your Raspberry Pi. Start by opening a folder or cloning a git repository and away you go coding, debugging and deploying your applications.

In the remote session, not all extensions you have installed locally will be available remotely. Any extensions that change the behavior of VS Code as an application, such as themes or tools for managing cloud resources, will be available.

Things like language packs and other programming tools are not installed in the remote session, so you’ll need to re-install them. When you install these extensions, you’ll see the Install button has changed to Install in SSH:< hostname > to show it’s being installed remotely.

VS Code may seem daunting at first – it’s a powerful tool with a huge range of extensions. The good news is Microsoft has you covered with lots of hands-on, self-guided learning guides on how to use it with different languages and development tools, from using Git version control, to developing web applications. There’s even a guide to learning Python basics with Wonder Woman!

Jim with his arms folded wearing a dark t shirt
Jim Bennett

You remember Jim – his blog Expecting Someone Geekier is well good. You can find him on Twitter @jimbobbennett and on github.

The post Coding on Raspberry Pi remotely with Visual Studio Code appeared first on Raspberry Pi.

Visual Studio Code comes to Raspberry Pi

Microsoft’s Visual Studio Code is an excellent C development environment, and now it’s an easy install on Raspberry Pi. Here’s Jim Bennett from Microsoft to show you all how to get VS Code up and running on our tiny computer. Take it away, Jim…

There are a few products in the tech sphere that get me really excited. One of them is Raspberry Pi (obviously), and the other is Visual Studio Code or VS Code. I always hoped that the two would come together one day — and now, to my great pleasure, they have!

VS Code is a free, open source developer text editor originally released for Windows, macOS and x64 Linux. Out of the box it supports generic text editing and git source code control, as well as full web development with JavaScript, TypeScript and Node.js, with debugging, intellisense and all the goodness you’d expect from a full-featured IDE. What makes it super powerful is extensions — bringing a huge range of programming languages, developer tools and other capabilities.

For example my VS Code setup includes a Python extension so I can code and debug in Python, a set of Microsoft Azure extensions so I can manage my cloud services, PlatformIO to allow me to program micro-controllers like Arduino boards coupled with a C++ extension to support coding in C and C++, and even some Docker support. Not a bad setup for a completely free developer tool.

Jim’s Raspberry Pi 400 running VS Code

I’ve been hoping for years VS Code would come to Raspberry Pi, and finally it’s here. As well as supporting Debian Linux on x64, there are now builds for ARM and ARM64 – both of which can run on Raspberry Pi OS (the ARM build on Raspberry Pi OS, the ARM64 on the beta of the 64-bit Raspberry Pi OS). And yes — I am writing this right now on a Raspberry Pi 400 running VS Code!

Why am I so excited about this?

Well, there are a couple of reasons.

Firstly, it brings an exceptional developer tool to Raspberry Pi. There are already some great editors, but nothing of the calibre of VS Code. I can take my $35 computer, plug it into a keyboard and mouse, connect a monitor and a TV and code in a wide range of languages from the same place.

I see kids learning Python at school using one tool, then learning web development in an after-school coding club with a different tool. They can now do both in the same application, reducing the cognitive load – they only have to learn one tool, one debugger, one setup. Combine this with the new Raspberry Pi 400 and you have an all-in-one solution to learning to code, reminiscent of my ZX Spectrum of decades ago, but so much more powerful.

The second reason is to me the most important — it allows kids to share the same development environment as their grown-ups. Imagine the joy of a 10-year-old coding Python using VS Code on their Raspberry Pi plugged into the family TV, then seeing their Mum working from home coding Python in exactly the same tool on her work laptop as part of her job as an AI engineer or data scientist. It also makes it easier when Mum has to inevitably help with unblocking the issues that always come up with learners.

As a young child it was mind-blowing when my Dad brought home a work PC so he could write reports and I could use it to write up my school work – I was using what Dad used at work, making me feel important. I see this with my seven-year-old daughter, seeing her excitement that I use Microsoft Teams for work, the same as she uses for her virtual schooling (she’s even offered to teach me how to use it if I get stuck). To be able to bring that unadulterated joy of using ‘grown-up tools’ to our young learners is priceless.

Installing VS Code

The great news is VS Code is now available as part of the Raspberry Pi OS apt packages. Launch the Raspberry Pi Terminal and run the following commands:

sudo apt update 
sudo apt install code -y

This will download and install VS Code. If you’ve got your hands on a Pico, then you may not even need to do this – VS Code is installed as part of the Pico setup from the Getting Started guide.

After installing VS Code, you can run it from the Programming folder in the Raspberry Pi menu.

Getting started with VS Code

VS Code may seem daunting at first – it’s a powerful tool with a huge range of extensions. The good news is Microsoft has you covered with lots of hands-on, self-guided learning guides on how to use it with different languages and development tools, from using Git version control, to developing web applications — there’s even a guide to learning Python basics with Wonder Woman.

Go grab it and happy coding!

Jim with his arms folded wearing a dark t shirt
There he is – that’s the real life Jim!

Brilliant Jim Bennett shares loads of Raspberry Pi builds and tutorials over on Expecting Someone Geekier and tweets @jimbobbennett. He also works in Developer Relations at Microsoft. You can learn pretty much everything there is to know about him on github.

The post Visual Studio Code comes to Raspberry Pi appeared first on Raspberry Pi.

Code a Light Cycle arcade minigame | Wireframe #47

Speed around an arena, avoiding walls and deadly trails in this Light Cycle minigame. Mark Vanstone has the code.

At the beginning of the 1980s, Disney made plans for an entirely new kind of animated movie that used cutting-edge computer graphics. The resulting film was 1982’s TRON, and it inevitably sparked one of the earliest tie-in arcade machines.

Battle against AI enemies in the original arcade classic.

The game featured several minigames, including one based on the Light Cycle section of the movie, where players speed around an arena on high-tech motorbikes, which leave a deadly trail of light in their wake. If competitors hit any walls or cross the path of any trails, then it’s game over.

Players progress through the twelve levels which were all named after programming languages. In the Light Cycle game, the players compete against AI players who drive yellow Light Cycles around the arena. As the levels progress, more AI Players are added.

The TRON game, distributed by Bally Midway, was well-received in arcades, and even won Electronic Games Magazine’s (presumably) coveted Coin-operated Game of the Year gong.

Although the arcade game wasn’t ported to home computers at the time, several similar games – and outright clones – emerged, such as the unsubtly named Light Cycle for the BBC Micro, Oric, and ZX Spectrum.

The Light Cycle minigame is essentially a variation on Snake, with the player leaving a trail behind them as they move around the screen. There are various ways to code this with Pygame Zero.

 

Our homage to the TRON Light Cycle classic arcade game.

 

In this sample, we’ll focus on the movement of the player Light Cycle and creating the trails that are left behind as it moves around the screen. We could use line drawing functions for the trail behind the bike, or go for a system like Snake, where blocks are added to the trail as the player moves.

In this example, though, we’re going to use a two-dimensional list as a matrix of positions on the screen. This means that wherever the player moves on the screen, we can set the position as visited or check to see if it’s been visited before and, if so, trigger an end-game event.

For the main draw() function, we first blit our background image which is the cross-hatched arena, then we iterate through our two-dimensional list of screen positions (each 10 pixels square) displaying a square anywhere the Cycle has been. The Cycle is then drawn and we can add a display of the score.

The update() function contains code to move the Cycle and check for collisions. We use a list of directions in degrees to control the angle the player is pointing, and another list of x and y increments for each direction. Each update we add x and y coordinates to the Cycle actor to move it in the direction that it’s pointing multiplied by our speed variable.

We have an on_key_down() function defined to handle changing the direction of the Cycle actor with the arrow keys. We need to wait a while before checking for collisions on the current position, as the Cycle won’t have moved away for several updates, so each screen position in the matrix is actually a counter of how many updates it’s been there for.

We can then test to see if 15 updates have happened before testing the square for collisions, which gives our Cycle enough time to clear the area. If we do detect a collision, then we can start the game-end sequence.

We set the gamestate variable to 1, which then means the update() function uses that variable as a counter to run through the frames of animation for the Cycle’s explosion. Once it reaches the end of the sequence, the game stops.

We have a key press defined (the SPACE bar) in the on_key_down() function to call our init() function, which will not only set up variables when the game starts but sets things back to their starting state.

Here’s Mark’s code for a TRON-style Light Cycle minigame. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

So that’s the fundamentals of the player Light Cycle movement and collision checking. To make it more like the original arcade game, why not try experimenting with the code and adding a few computer-controlled rivals?

Get your copy of Wireframe issue 47

You can read more features like this one in Wireframe issue 47, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 47 for free in PDF format.

The post Code a Light Cycle arcade minigame | Wireframe #47 appeared first on Raspberry Pi.

Raspberry Pi Pico released and available at $4 only

Par : Vivek Gite

Raspberry Pi Pico released and available at $4 only
Last year, the Raspberry Foundation also released a brand new version of the Raspberry PI PC (personal computer), and it is directly built into a small-sized keyboard. Now there is more good news for hackers and hardware developers. They just announced their first microcontroller-based product named Raspberry Pi Pico. This small device is priced at only US $4. Unbelievable price. Let us find out about Raspberry Pi Pico hardware specs and software support.

The post Raspberry Pi Pico released and available at $4 only appeared first on nixCraft.

Code your own Pipe Mania puzzler | Wireframe #46

Create a network of pipes before the water starts to flow in our re-creation of a classic puzzler. Jordi Santonja shows you how.

A screen grab of the game in motion
Pipe Mania’s design is so effective, it’s appeared in various guises elsewhere – even as a minigame in BioShock.

Pipe Mania, also called Pipe Dream in the US, is a puzzle game developed by The Assembly Line in 1989 for Amiga, Atari ST, and PC, and later ported to other platforms, including arcades. The player must place randomly generated sections of pipe onto a grid. When a counter reaches zero, water starts to flow and must reach the longest possible distance through the connected pipes.

Let’s look at how to recreate Pipe Dream in Python and Pygame Zero. The variable start is decremented at each frame. It begins with a value of 60*30, so it reaches zero after 30 seconds if our monitor runs at 60 frames per second. In that time, the player can place tiles on the grid to build a path. Every time the user clicks on the grid, the last tile from nextTiles is placed on the play area and a new random tile appears at the top of the next tiles. randint(2,8) computes a random value between 2 and 8.

Our Pipe Mania homage. Build a pipeline before the water escapes, and see if you can beat your own score.

grid and nextTiles are lists of tile values, from 0 to 8, and are copied to the screen in the draw function with the screen.blit operation. grid is a two-dimensional list, with sizes gridWidth=10 and gridHeight=7. Every pipe piece is placed in grid with a mouse click. This is managed with the Pygame functions on_mouse_move and on_mouse_down, where the variable pos contains the mouse position in the window. panelPosition defines the position of the top-left corner of the grid in the window. To get the grid cell, panelPosition is subtracted from pos, and the result is divided by tileSize with the integer division //. tileMouse stores the resulting cell element, but it is set to (-1,-1) when the mouse lies outside the grid.

The images folder contains the PNGs with the tile images, two for every tile: the graphical image and the path image. The tiles list contains the name of every tile, and adding to it _block or _path obtains the name of the file. The values stored in nextTiles and grid are the indexes of the elements in tiles.

wfmag46code
Here’s Jordi’s code for a Pipemania-style puzzler. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

The image waterPath isn’t shown to the user, but it stores the paths that the water is going to follow. The first point of the water path is located in the starting tile, and it’s stored in currentPoint. update calls the function CheckNextPointDeleteCurrent, when the water starts flowing. That function finds the next point in the water path, erases it, and adds a new point to the waterFlow list. waterFlow is shown to the user in the draw function.

pointsToCheck contains a list of relative positions, offsets, that define a step of two pixels from currentPoint in every direction to find the next point. Why two pixels? To be able to define the ‘cross’ tile, where two lines cross each other. In a ‘cross’ tile the water flow must follow a straight line, and this is how the only points found are the next points in the same direction. When no next point is found, the game ends and the score is shown: the number of points in the water path, playState is set to 0, and no more updates are done.

Get your copy of Wireframe issue 46

You can read more features like this one in Wireframe issue 46, available directly from Raspberry Pi Press — we deliver worldwide.

wfcover

And if you’d like a handy digital version of the magazine, you can also download issue 46 for free in PDF format.

The post Code your own Pipe Mania puzzler | Wireframe #46 appeared first on Raspberry Pi.

bpytop – Awesome Linux, macOS and FreeBSD resource monitor

Par : Vivek Gite

byptop
The bashtop is an impressive Linux resource monitor that shows usage and stats for processor, memory, disks, and network. However, it suffers from bash itself, and cross-platform support is a nightmare. Now we have the Python port of bashtop. We can use a resource monitor that shows usage and stats for CPU, RAM, SSD (hard disk), network, and processes information in a lovely format.

The post bpytop – Awesome Linux, macOS and FreeBSD resource monitor appeared first on nixCraft.

Recreate Tiger-Heli’s bomb mechanic | Wireframe #45

Code an explosive homage to Toaplan’s classic blaster. Mark Vanstone has the details

Tiger-Heli was developed by Toaplan and published in Japan by Taito and by Romstar in North America.

Released in 1985, Tiger-Heli was one of the earliest games from Japanese developer Toaplan: a top-down shoot-’em-up that pitted a lone helicopter against relentless waves of enemy tanks and military installations. Toaplan would go on to refine and evolve the genre through the eighties and nineties with such titles as Truxton and Fire Shark, so Tiger-Heli served as a kind of blueprint for the studio’s legendary blasters.

Tiger-Heli featured a powerful secondary weapon, too: as well as a regular shot, the game’s attack helicopter could also drop a deadly bomb capable of destroying everything within its blast radius. The mechanic was one that first appeared as far back as Atari’s Defender in 1981, but Toaplan quickly made it its own, with variations on the bomb becoming one of the signatures in the studio’s later games.

For our Tiger-Heli-style Pygame Zero code, we’ll concentrate on the unique bomb aspect, but first, we need to get the basic scrolling background and helicopter on the screen. In a game like this, we’d normally make the background out of tiles that can be used to create a varied but continuous scrolling image. For this example, though, we’ll keep things simple and have one long image that we scroll down the screen and then display a copy above it. When the first image goes off the screen, we just reset the co-ordinates to display it above the second image copy. In this way, we can have an infinitely scrolling background.

Our Tiger-Heli homage in Python. Fly over the military targets, firing missiles and dropping bombs.

 

The helicopter can be set up as an Actor with just two frames for the movement of the rotors. This should look like it’s hovering above the ground, so we blit a shadow bitmap to the bottom right of the helicopter. We can set up keyboard events to move the Actor left, right, up, and down, making sure we don’t allow it to go off the screen.

Now we can go ahead and set up the bombs. We can predefine a list of bomb Actors but only display them while the bombs are active. We’ll trigger a bomb drop with the SPACE bar and set all the bombs to the co-ordinates of the helicopter. Then, frame by frame, we move each bomb outwards in different directions so that they spread out in a pattern. You could try adjusting the number of bombs or their pattern to see what effects can be achieved. When the bombs get to frame 30, we start changing the image so that we get a flashing, expanding circle for each bomb.

Here’s Mark’s code for a Tiger-Heli-style shooter. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

It’s all very well having bombs to fire, but we could really do with something to drop them on, so let’s make some tank Actors waiting on the ground for us to destroy. We can move them with the scrolling background so that they look like they’re static on the ground. Then if one of our bombs has a collision detected with one of the tanks, we can set an animation going by cycling through a set of explosion frames, ending with the tank disappearing.

We can also add in some sound effects as the bombs are dropped, and explosion sounds if the tanks are hit. And with that, there you have it: the beginnings of a Tiger-Heli-style blaster.

Get your copy of Wireframe issue 45

You can read more features like this one in Wireframe issue 45, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 45 for free in PDF format.

Baldur’s Gate III: our cover star for Wireframe #45.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 72% compared to newsstand pricing!

The post Recreate Tiger-Heli’s bomb mechanic | Wireframe #45 appeared first on Raspberry Pi.

Code your own Artillery-style tank game | Wireframe #44

Fire artillery shells to blow up the enemy with Mark Vanstone’s take on a classic two-player artillery game

Artillery Duel was an early example of the genre, and appeared on such systems as the Bally Astrocade and Commodore 64 (pictured).

To pick just one artillery game is difficult since it’s a genre in its own right. Artillery simulations and games have been around for almost as long as computers, and most commonly see two players take turns to adjust the trajectory of their tank’s turret and fire a projectile at their opponent. The earliest versions for microcomputers appeared in the mid-seventies, and the genre continued to develop; increasingly complex scenarios appeared involving historical settings or, as we saw from the mid-90s on, even offbeat ideas like battles between factions of worms.

To code the basics of an artillery game, we’ll need two tanks with turrets, a landscape, and some code to work out who shot what, in which direction, and where said shot landed. Let’s start with the landscape. If we create a landscape in two parts – a backdrop and foreground – we can make the foreground destructible so that when a missile explodes it damages part of the landscape. This is a common effect used in artillery games, and sometimes makes the gameplay more complicated as the battle progresses. In our example, we have a grass foreground overlaid on a mountain scene. We then need a cannon for each player. In this case, we’ve used a two-part image, one for the base and one for the turret, which means the latter can be rotated using the up and down keys.

Our homage to the artillery game genre. Fire away at your opponent, and hope they don’t hit back first.

For this code example, we can use the Python dictionary to store several bits of data about the game objects, including the Actor objects. This makes the data handling tidy and is quite similar to the way that JSON is used in JavaScript. We can use this method for the two cannons, the projectile, and an explosion object. As this is a two-player game, we’ll alternate between the two guns, allowing the arrow keys to change the angle of the cannon. When the SPACE bar is pressed, we call the firing sequence, which places the projectile at the same position as the gun firing it. We then move the missile through the air, reducing the speed as it goes and allowing the effects of gravity to pull it towards the ground.

We can work out whether the bullet has hit anything with two checks. The first is to do a pixel check with the foreground. If this comes back as not transparent, then it has hit the ground, and we can start an explosion. To create a hole in the foreground, we can write transparent pixels randomly around the point of contact and then set off an explosion animation. If we test for a collision with a gun, we may find that the bullet has hit the other player and after blowing up the tank, the game ends. If the impact only hit the landscape, though, we can switch control over to the other player and let them have a go.

So that’s your basic artillery game. But rest assured there are plenty of things to add – for example, wind direction, power of the shot, variable damage depending on proximity, or making the tanks fall into holes left by the explosions. You could even change the guns into little wiggly creatures and make your own homage to Worms.

Here’s Mark’s code for an artillery-style tank game. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 44

You can read more features like this one in Wireframe issue 44, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 44 for free in PDF format.

Wireframe #44, bringing the past and future of Worms to the fore.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 72% compared to newsstand pricing!

The post Code your own Artillery-style tank game | Wireframe #44 appeared first on Raspberry Pi.

New book: Create Graphical User Interfaces with Python

Laura Sach and Martin O’Hanlon, who are both Learning Managers at the Raspberry Pi Foundation, have written a brand-new book to help you to get more out of your Python projects.

Cover of the book Create Graphical User Interfaces with Python

In Create Graphical User Interfaces with Python, Laura and Martin show you how to add buttons, boxes, pictures, colours, and more to your Python programs using the guizero library, which is easy to use and accessible for all, no matter your Python skills.

This new 156-page book is suitable for everyone — from beginners to experienced Python programmers — who wants to explore graphical user interfaces (GUIs).

Meet the authors

Screenshot of a Digital Making at Home live stream session
That’s Martin in the blue T-shirt with our Digital Making at Home live stream hosts Matt and Christina

You might have met Martin recently on one of our weekly Digital Making at Home live streams for young people, were he was a guest for an ‘ooey-GUI’ code-along session. He talked about his background and what it’s like creating projects and learning resources on a day-to-day basis.

Laura is also pretty cool! Here she is showing you how to solder your Raspberry Pi header pins:

Hi Laura!

Martin and Laura are also tonnes of fun on Twitter. You can find Martin as @martinohanlon, and Laura goes by @codeboom.

10 fun projects

In Create Graphical User Interfaces with Python, you’ll find ten fun Python projects to create with guizero, including a painting program, an emoji match game, and a stop-motion animation creator.

A double-page from the book Create Graphical User Interfaces with Python
A peek inside Laura’s and Martin’s new book

You will also learn:

  • How to create fun Python games and programs
  • How to code your own graphical user interfaces using windows, text boxes, buttons, images, and more
  • What event-based programming is
  • What good (and bad) user interface design is
A double-page from the book Create Graphical User Interfaces with Python
Ain’t it pretty?

Where can I get it?

You can buy Create Graphical User Interfaces with Python now from the Raspberry Pi Press online store, or the Raspberry Pi store in Cambridge, UK.

And if you don’t need the lovely new book, with its new-book smell, in your hands in real life, you can download a PDF version for free, courtesy of The MagPi magazine.

The post New book: Create Graphical User Interfaces with Python appeared first on Raspberry Pi.

Code a Rally-X-style mini-map | Wireframe #43

Race around using a mini-map for navigation, just like the arcade classic, Rally-X. Mark Vanstone has the code

In Namco’s original arcade game, the red cars chased the player relentlessly around each level. Note the handy mini-map on the right.

The original Rally-X arcade game blasted onto the market in 1980, at the same time as Pac‑Man and Defender. This was the first year that developer Namco had exported its games outside Japan thanks to the deal it struck with Midway, an American game distributor. The aim of Rally-X is to race a car around a maze, avoiding enemy cars while collecting yellow flags – all before your fuel runs out.

The aspect of Rally-X that we’ll cover here is the mini-map. As the car moves around the maze, its position can be seen relative to the flags on the right of the screen. The main view of the maze only shows a section of the whole map, and scrolls as the car moves, whereas the mini-map shows the whole size of the map but without any of the maze walls – just dots where the car and flags are (and in the original, the enemy cars). In our example, the mini-map is five times smaller than the main map, so it’s easy to work out the calculation to translate large map co‑ordinates to mini-map co-ordinates.

To set up our Rally-X homage in Pygame Zero, we can stick with the default screen size of 800×600. If we use 200 pixels for the side panel, that leaves us with a 600×600 play area. Our player’s car will be drawn in the centre of this area at the co-ordinates 300,300. We can use the in-built rotation of the Actor object by setting the angle property of the car. The maze scrolls depending on which direction the car is pointing, and this can be done by having a lookup table in the form of a dictionary list (directionMap) where we define x and y increments for each angle the car can travel. When the cursor keys are pressed, the car stays central and the map moves.

A screenshot of our Rally-X homage running in Pygame Zero

Roam the maze and collect those flags in our Python homage to Rally-X.

To detect the car hitting a wall, we can use a collision map. This isn’t a particularly memory-efficient way of doing it, but it’s easy to code. We just use a bitmap the same size as the main map which has all the roads as black and all the walls as white. With this map, we can detect if there’s a wall in the direction in which the car’s moving by testing the pixels directly in front of it. If a wall is detected, we rotate the car rather than moving it. If we draw the side panel after the main map, we’ll then be able to see the full layout of the screen with the map scrolling as the car navigates through the maze.

We can add flags as a list of Actor objects. We could make these random, but for the sake of simplicity, our sample code has them defined in a list of x and y co-ordinates. We need to move the flags with the map, so in each update(), we loop through the list and add the same increments to the x and y co‑ordinates as the main map. If the car collides with any flags, we just take them off the list of items to draw by adding a collected variable. Having put all of this in place, we can draw the mini-map, which will show the car and the flags. All we need to do is divide the object co-ordinates by five and add an x and y offset so that the objects appear in the right place on the mini-map.

And those are the basics of Rally-X! All it needs now is a fuel gauge, some enemy cars, and obstacles – but we’ll leave those for you to sort out…

Here’s Mark’s code for a Rally-X-style driving game with mini-map. To get it running on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 43

You can read more features like this one in Wireframe issue 43, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 43 for free in PDF format.

Wireframe #43, with the gorgeous Sea of Stars on the cover.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

 

 

 

The post Code a Rally-X-style mini-map | Wireframe #43 appeared first on Raspberry Pi.

❌