This 2 hour workshop will gave you an introduction and overview to programming, programming with Clojure and developing simple games.
We will started with an existing game template and then made changes and saw the effects in real time.
Then we will talked about how simple 2D games are structured and introduce more technical game and programming concepts and aspects.
And then worked on making more changes and customizations.
Lenses, or more generally “optics”, are a technique that is indispensable to modern functional programming. However, implementations have veered between two extremes: incredible abstractive power with a steep learning curve; and limited domain-specific uses that can be picked up in minutes. Why can’t we have our cake and eat it too?
Goggles is a new Scala macro built over the powerful & popular Monocle optics library. It uses Scala’s macros and scandalously flexible syntax to create a compiler-checked mini-language to concisely construct, compose and apply optics, with a gentle, familiar interface, and informative compiler errors.
In this talk, I introduce the motivation for lenses, why lens usability is a problem that badly needs solving, and how the Goggles library, with Monocle, addresses this in an important way.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
A Development of Log-based Game AI using Deep LearningSuntae Kim
PyCon Korea 2018 발표자료입니다.
https://www.pycon.kr/2018/program/34
게임에서 AI는 빠질 수 없는 기능으로 그동안 다양한 장르와 플랫폼에서 사용되어 왔다.
특히 요즘 모바일 게임에서 자동 플레이 AI는 흔히 '노가다', '피로도'를 줄여주기 위한 매우 중요한 기능으로 자리잡고 있다. 하지만 지금까지의 자동 플레이 AI는 정해진 범위안에서 작동하는 FSM(Finite State Machine) 형태로 구현되다 보니 AI가 동작하는 경우의 수가 유한하고 한정적이라고 볼 수 있다. 때로는 이렇게 정해진 패턴의 AI가 유저들에게는 마치 로보트와 같은 느낌을 주기도 한다. 아무리 State를 추가하고 자연스럽게 구현해보려고 해도 어디까지 자연스럽게 해줘야 할 것인가에 대한 한계에 맞닥들이게 된다. 고려해야 할 경우의 수가 많기 때문이다.
하지만 이렇게 다양한 경우의 수를 로직으로 구현하지 않고 사용자가 플레이했던 데이터를 이용하여 학습시켜보면 어떨까? 이 호기심을 시작으로 LINE에서 자체 개발한 "리틀나이츠" 모바일 게임에 적용해보기로 했다. 게임 런칭 후 실제 사용자 플레이 로그를 수집하여 전처리하고 학습시켜서, 기획 의도에 맞게 유저가 Offline일 때 자신을 대신해서 플레이해 줄 수 있는 AI를 개발하였다. 이를 위해서 유저가 언제 어떤 카드를 선택했고 어디에 배치했는지, When, What, Where 3가지 상황에 대해서 학습시켰고 게임에 적용시켜 보았다.
단계별 과정을 간략하게 살펴보면, 먼저 로그 포멧을 게임 개발팀과 함께 정의했다. 두번째로 유저가 플레이했던 배틀 정보가 사전에 정의했던 로그 포맷 형태로 하둡에 쌓이게 했으며, 세번째로 Apache Spark을 이용하여 저장된 대용량 플레이 로그를 분산으로 전처리하여 데이터를 학습 가능한 형태로 가공하였다. 네번째로 AI 모델을 만들기 위한 뉴럴 네트워크를 설계하고, Python과 TensorFlow를 이용하여 데이터를 학습시켰다. 다섯번째로 학습에 반영되지 않는 순수한 테스트 데이터로 예측률을 구해본다. 이때 최적의 모델을 찾기 위해서 인내를 가지고 테스트하게 되는데, 먼저 하이퍼파라메터를 변경해보고 그래도 성능이 안나오면 뉴럴 네트워크와 데이터 전처리를 다양하게 변경해가며 테스트해 본다. 참고로 이러한 과정에 소비되는 Cost를 줄이고 싶다면 AutoML에 관심을 가져보아도 좋다. 여섯번째로 Python으로 개발된 AI 모델을 C# 기반의 유니티 환경에서 구동시키기 위해서 LineTensorFlow(가칭) 라이브러리를 개발해서 유니티 게임에 적용하였다.
발표 끝부분에서는 학습 지표를 공유하고, 알고리즘 기반의 AI와 딥러닝 기반의 AI에 대해서 플레이 비교 영상을 보고, 어떤 것이 딥러닝을 이용한 AI인지 맞춰보는 시간도 갖아본다. 이 발표에서는 로그 기반의 게임 AI가 개발되는 과정에서 파이썬이 어떻게 활용되었는지 살펴보고, 그 동안 겪었던 문제와 해결 방법에 대해서 공유하고자 한다.
Python là ngôn ngữ lập trình đơn giản và đang càng này càng trở lên phổ biến. Bài giảng này cung cấp cách tiếp cận đơn giản dễ hiểu với python một cách dễ dàng nhất
Lenses, or more generally “optics”, are a technique that is indispensable to modern functional programming. However, implementations have veered between two extremes: incredible abstractive power with a steep learning curve; and limited domain-specific uses that can be picked up in minutes. Why can’t we have our cake and eat it too?
Goggles is a new Scala macro built over the powerful & popular Monocle optics library. It uses Scala’s macros and scandalously flexible syntax to create a compiler-checked mini-language to concisely construct, compose and apply optics, with a gentle, familiar interface, and informative compiler errors.
In this talk, I introduce the motivation for lenses, why lens usability is a problem that badly needs solving, and how the Goggles library, with Monocle, addresses this in an important way.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
A Development of Log-based Game AI using Deep LearningSuntae Kim
PyCon Korea 2018 발표자료입니다.
https://www.pycon.kr/2018/program/34
게임에서 AI는 빠질 수 없는 기능으로 그동안 다양한 장르와 플랫폼에서 사용되어 왔다.
특히 요즘 모바일 게임에서 자동 플레이 AI는 흔히 '노가다', '피로도'를 줄여주기 위한 매우 중요한 기능으로 자리잡고 있다. 하지만 지금까지의 자동 플레이 AI는 정해진 범위안에서 작동하는 FSM(Finite State Machine) 형태로 구현되다 보니 AI가 동작하는 경우의 수가 유한하고 한정적이라고 볼 수 있다. 때로는 이렇게 정해진 패턴의 AI가 유저들에게는 마치 로보트와 같은 느낌을 주기도 한다. 아무리 State를 추가하고 자연스럽게 구현해보려고 해도 어디까지 자연스럽게 해줘야 할 것인가에 대한 한계에 맞닥들이게 된다. 고려해야 할 경우의 수가 많기 때문이다.
하지만 이렇게 다양한 경우의 수를 로직으로 구현하지 않고 사용자가 플레이했던 데이터를 이용하여 학습시켜보면 어떨까? 이 호기심을 시작으로 LINE에서 자체 개발한 "리틀나이츠" 모바일 게임에 적용해보기로 했다. 게임 런칭 후 실제 사용자 플레이 로그를 수집하여 전처리하고 학습시켜서, 기획 의도에 맞게 유저가 Offline일 때 자신을 대신해서 플레이해 줄 수 있는 AI를 개발하였다. 이를 위해서 유저가 언제 어떤 카드를 선택했고 어디에 배치했는지, When, What, Where 3가지 상황에 대해서 학습시켰고 게임에 적용시켜 보았다.
단계별 과정을 간략하게 살펴보면, 먼저 로그 포멧을 게임 개발팀과 함께 정의했다. 두번째로 유저가 플레이했던 배틀 정보가 사전에 정의했던 로그 포맷 형태로 하둡에 쌓이게 했으며, 세번째로 Apache Spark을 이용하여 저장된 대용량 플레이 로그를 분산으로 전처리하여 데이터를 학습 가능한 형태로 가공하였다. 네번째로 AI 모델을 만들기 위한 뉴럴 네트워크를 설계하고, Python과 TensorFlow를 이용하여 데이터를 학습시켰다. 다섯번째로 학습에 반영되지 않는 순수한 테스트 데이터로 예측률을 구해본다. 이때 최적의 모델을 찾기 위해서 인내를 가지고 테스트하게 되는데, 먼저 하이퍼파라메터를 변경해보고 그래도 성능이 안나오면 뉴럴 네트워크와 데이터 전처리를 다양하게 변경해가며 테스트해 본다. 참고로 이러한 과정에 소비되는 Cost를 줄이고 싶다면 AutoML에 관심을 가져보아도 좋다. 여섯번째로 Python으로 개발된 AI 모델을 C# 기반의 유니티 환경에서 구동시키기 위해서 LineTensorFlow(가칭) 라이브러리를 개발해서 유니티 게임에 적용하였다.
발표 끝부분에서는 학습 지표를 공유하고, 알고리즘 기반의 AI와 딥러닝 기반의 AI에 대해서 플레이 비교 영상을 보고, 어떤 것이 딥러닝을 이용한 AI인지 맞춰보는 시간도 갖아본다. 이 발표에서는 로그 기반의 게임 AI가 개발되는 과정에서 파이썬이 어떻게 활용되었는지 살펴보고, 그 동안 겪었던 문제와 해결 방법에 대해서 공유하고자 한다.
Python là ngôn ngữ lập trình đơn giản và đang càng này càng trở lên phổ biến. Bài giảng này cung cấp cách tiếp cận đơn giản dễ hiểu với python một cách dễ dàng nhất
https://www.dmdiploma.com/studymaterial?id=5/python-for-data-science
This Python course provides a beginner-friendly introduction to Python for Data Science.
Presented at JAX London 2013
Clojure is the most interesting new language on the horizon, but many developers suffer from the Blub Paradox when they see the Lisp syntax. This talk introduces Clojure to developers who haven’t been exposed to it yet, focusing on the things that truly set it apart from other languages.
Помните легендарные Java Puzzlers? Да-да, те самые, с Джошом Блохом и Нилом Гафтером? Ну, по которым ещё книжку написали? Так вот, в Groovy всё ещё веселее.
В смысле — задачки ещё более странные, и ответы ещё более поразительные. Этот доклад для вас, Groovy-разработчики, мы покажем вам настоящие, большие и красивые подводные камни! И для вас, Java-разработчики, потому что таких вещей на Java-подобном синтакисе вы точно никогда не видели! И для вас, PHP-разработчики… хотя, нет, не для вас :)
Всем точно будет весело — ваши ведущие Женя и Барух будут зажигать, шутить, спорить, бросаться футболками в публику, и самое главное — заставят вас офигевать от Groovy.
project 6/cards.py
import random
class Card( object ):
""" Model a playing card. """
# Rank is an integer (1-13), where aces are 1 and kings are 13.
# Suit is an integer (1-4), where clubs are 1 and spades are 4.
# Value is an integer (1-10), where aces are 1 and face cards are 10.
# List to map integer rank to printable character (index 0 used for no rank)
rank_list = ['x','A','2','3','4','5','6','7','8','9','10','J','Q','K']
# List to map integer suit to printable character (index 0 used for no suit)
# The commented-out list prints symbols rather than characters. You may use either.
suit_list = ['x','c','d','h','s']
#suit_list = ['x',u'\u2660',u'\u2665',u'\u2666',u'\u2663']
def __init__( self, rank=0, suit=0 ):
""" Initialize card to specified rank (1-13) and suit (1-4). """
self.__rank = 0
self.__suit = 0
# Verify that rank and suit are integers and that they are within
# range (1-13 and 1-4), then update instance variables if valid.
if type(rank) == int and type(suit) == int:
if rank in range(1,14) and suit in range(1,5):
self.__rank = rank
self.__suit = suit
def rank( self ):
""" Return card's rank (1-13). """
return self.__rank
def value( self ):
""" Return card's value (1 for aces, 2-9, 10 for face cards). """
# Use ternary expression to determine value.
return self.__rank if self.__rank < 10 else 10
def suit( self ):
""" Return card's suit (1-4). """
return self.__suit
def __eq__( self, other ):
""" Return True if ranks are equal. """
return self.__rank == other.__rank
def __ne__( self, other ):
""" Return True if ranks are not equal. """
return self.__rank != other.__rank
def __le__( self, other ):
""" Return True if rank of self <= rank of other. """
return self.rank() <= other.rank()
def __lt__( self, other ):
""" Return True if rank of self < rank of other. """
return self.rank() < other.rank()
def __ge__( self, other ):
""" Return True if rank of self >= rank of other. """
return self.rank() >= other.rank()
def __gt__( self, other ):
""" Return True if rank of self > rank of other. """
return self.rank() > other.rank()
def __str__( self ):
""" Convert card into a string (usually for printing). """
# Use rank to index into rank_list; use suit to index into suit_list.
return "{}{}".format( (self.rank_list)[self.__rank], (self.suit_list)[self.__suit] )
def __repr__( self ):
""" Convert card into a string for use in the shell. """
return self.__str__()
class Deck( object ):
""" Model a deck of 52 playing cards. """
# Implement the deck as a list.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
11. Change Player
1. Open core.clj go to line 25.
2. Change "player.png" to "tram.png"
3. Save the file
(defscreen main-screen
:on-show
(fn [screen entities]
(update! screen :renderer (stage) :camera (orthographic))
(add-timer! screen :spawn-enemy 0 2)
(assoc (texture "player.png") ;; make this "tram.png"
:player? true
:x (/ (game :width) 2)
:y 10
:width 64
:height 64))
11 / 57
12. Change the enemy
1. Open entities.clj
2. Go to line 57
3. Change "enemy.png" to "needle.png"
(defn create-enemy
"Returns an enemy at a random position."
[]
(assoc (texture "enemy.png") ;; make this "needle.png"
:enemy? true
:x (rand (game :width))
:y (game :height)
:width 6 4
:height 64))
12 / 57
13. Change the missile
Starts on line 24 in entities.clj
(defn create-missile
"Returns a missile at the same x position as the mouse."
[]
(assoc (shape :filled
:set-color (color :blue) ;; make :red
:circle 0 0 10) ;; :ellipse 0 0 10 50
:missile? true
:x (game :x)
:y 50 ;; make 70
:width 10
:height 10)) ;; make 50
13 / 57
14. Play a sound when the missile
fires
(defn create-missile
"Returns a missile at the same x position as the mouse."
[]
(sound "laser.wav" :play) ;; Add this
(assoc (shape :filled
:set-color (color :red)
:ellipse 0 0 10 70)
:missile? true
:x (game :x)
:y 70
:width 20
:height 70))
14 / 57
15. Play background music
Back in core.clj around line 21
(defscreen main-screen
:on-show
(fn [screen entities]
(sound "music.wav" :loop) ;; Add this
(update! screen :renderer (stage) :camera (orthographic))
(add-timer! screen :spawn-enemy 0 2)
(assoc (texture "tram.png")
:player? true
:x (/ (game :width) 2)
:y 10
:width 64
:height 64))
...
*Originally called http://ccmixter.org/files/djlang59/37792
15 / 57
21. The game loop - Hollywood
principle
Don't call us we'll call you.
Every time its time to draw a new screen :on-render (line 32) is called
:on-render
(fn [screen entities]
(clear!)
(->> entities
(move-missiles)
(move-enemies)
(update-score!)
(remove-missiles)
(remove-enemies)
(remove :remove?)
(render! screen)))
21 / 57
22. Move missiles
entities.clj line 37
(defn move-missiles
"Moves the missiles up."
[entities]
(for [e entities]
(if (:missile? e)
(assoc e :y (+ (:y e) 5))
e)))
22 / 57
23. Move enemies
entities.clj line 65
(defn move-enemies
"Moves the enemies down."
[entities]
(for [e entities]
(if (:enemy? e)
(assoc e :y (- (:y e) 3))
e)))
23 / 57
24. Clojure Maps - A little bundle of
information
Other languages call them hash maps, hash or dictionary.
Maps associate keys and values.
Curly braces, {}, denote maps.
;; a map or record for a person
{:first-name "Julio"
:last-name "Barros"
:age 29}
;; a map for a game entity
{:texture-info "some stuff the system builds for us"
:missile? true
:x 23
:y 30
:color :red}
24 / 57
25. The REPL
Open the repl and type (+ 2 4) and {:name "your name here"}
25 / 57
26. assoc
Associates (adds or updates) a key and value in one map creating a new map.
(assoc {:name "Julio" } :loves "Clojure")
;; results in - ie outputs
{
:name "Julio"
:loves "Clojure"
}
(assoc {:x 10, :color :red} :x 11)
;; results in
{
:color :red
:x 11
}
26 / 57
27. Getting values from a map
(get {:y "because"} :y) ;; gets the value of y
(:y {:y "because"}) ;; same thing just shorter
({:y "because"} :y) ;; this works too
27 / 57
28. What's with all those round ()
things?
Parentheses (round braces) denote lists. Lists are a sequence of things.
The special thing about lists is that usually the first item is executed.
(action argument1 argument2)
(function parameter1 parameter2)
(+ 3 4)
(assoc e :x 33)
(assoc {:x 22, :color :red} :x 33)
quote or ' keeps the list from being executed
'(1 2 3) ;; [1 2 3] more common
28 / 57
29. What's up with the square []
things?
Square brackets, [] denote a vector (array). Vectors are also a sequence.
[1 2 3]
[1 2 [3 4]]
(count [5 5 5])
=> 3
(get [1 2 3] 1) ;; Note: zero based.
=> 2
You can have any length vector (or list) made up of any "type"
[3 {:name "Joe"} [1 2 3] '(1 2 [3 5])]
'(3 {:name "Joe"} [1 2 3] '(1 2 [3 5]))
29 / 57
30. Other interesting types
"I'm a string" ;; strings
:name ;; keyword
3 ;; integer
3.0 ;; double
;; Note: 3.0 is different than "3.0"
0.5 ;; must start with a number
{} ;; map
[] ;; vectors
() ;; lists
#{} ;; set - unordered collection with no duplicates
30 / 57
32. for
Walks through vector/sequence giving each element the name "e" and using it in the steps
that follow.
"e" can be any name.
Returns a vector.
(for [e [1 2 3]]
(+ e e))
=> (2 4 6)
(for [current-n [1 2 3]]
(even? current-n))
=> (false true false)
(for [e entities]
(if (:missile? e)
(assoc e :y (+ (:y e) 5))
e))
32 / 57
33. Functions
Takes zero or more input parameters and returns a single value.
The return value could be a list or map or vectors of multiple things.
Returns the result of the last expression executed.
(defn my-function-name
"A documentation string"
[param1 param2]
(functionA param1)
(functionB param1 param2))
(defn increment
"Adds one to the parameter"
[a-number]
(+ 1 a-number))
(increment 3)
=> 4
33 / 57
35. Create an enemy
(defn create-enemy
"Returns an enemy at a random position."
[]
(assoc (texture "needle.png")
:enemy? true
:x (rand (game :width))
:y (game :height)
:width 64
:height 64))
(create-enemy)
{:object "... some stuff about com.badlogic.gdx.graphics.g2d.TextureRegion"
:height 64,
:width 64,
:y 965,
:x 173.37581878372418,
:enemy? true}
35 / 57
36. Random numbers
Random numbers are super useful in games.
(rand-int n) returns a random integer between 0 (inclusive) and n (exclusive).
(rand-int 10)
=> 3 ;; or 0 or 1 or 2 .. or 9
36 / 57
37. Exercise: Our own Function -
choose-one
Write a function called choose-one that randomly chooses one element from a vector
(choose-one [3 6]) chooses either 3 or 6 randomly. Put the function at the top of entities.clj
Things to think about:
1. How do you know how many things are in the vector?
2. How do you pick an index between 0 and the last index in the vector?
3. How do you get the item in the vector at that index?
37 / 57
39. Step 1
Figure out how many things we have to choose from.
(defn choose-one
"Pick and return one thing from v. Well just the number of things in v."
[v]
(count v))
39 / 57
40. Step 2
Pick a random index - a number from 0 to the number of things we have to choose from.
40 / 57
41. Step 2
Pick a random index - a number from 0 to the number of things we have to choose from.
(defn choose-one
"Pick and return one thing from v. Well a random valid index into v."
[v]
(rand-int (count v)))
41 / 57
42. Step 3
Get the item at that index in the vector.
42 / 57
43. A solution
Get the item at that index in the vector
(defn choose-one
"Pick and return one thing from v."
[v]
(get v (rand-int (count v))))
43 / 57
44. Use choose-one to pick different
enemies
(defn create-enemy
"Returns an enemy at a random position."
[]
(assoc (texture (choose-one ["enemy.png","needle.png"]))
:enemy? true
:x (rand (game :width))
:y (game :height)
:width 6 4
:height 64))
44 / 57
45. Exercise: one-in
Write a function called one-in that takes a number, n, and returns true 1 in n times. (one-in
5) returns true ~20% (1 in 5) of the time
Use it to create an old style enemy 1 out of 10 times.
Can you use choose-one to do the same thing?
45 / 57
46. Back to the game loop
Every function takes a list of entities and returns a list of entities.
May be the same list. More likely a new list made from the old list with a few changes.
(->> entities
(move-missiles)
(move-enemies)
(update-score!)
(remove-missiles) ;; mark missiles for removal
(remove-enemies) ;; mark enemies for removal
(remove :remove?) ;; actually do the remove
(render! screen)))
The remove step logic is a little tricky.
Homework: Study it to see if you can figure out how it works.
46 / 57
48. Programmable Music - Sonic Pi
http://sonic-pi.net
http://vimeo.com/113811476
48 / 57
49. Today's Parts Review
Clojure - Modern LISP targeting the Java Virtual Machine (JVM). http://clojure.org
Java / JVM - Mature enterprise programming language and the system that runs it.
https://www.java.com/
Nightmod - Tool for making live-moddable games using Clojure and play-clj.
https://nightmod.net
play-clj - Clojure game library that uses libGDX. https://github.com/oakes/play-clj
libGDX - Game development framework written in Java. http://libgdx.badlogicgames.com
49 / 57
50. Clojure Resources
Clojure Cheat Sheet
http://clojure.org/cheatsheet
Clojure From The Ground Up
https://aphyr.com/tags/Clojure-from-the-ground-up
Clojure For the brave and true
http://www.braveclojure.com
ClojureBridge
https://github.com/ClojureBridge/curriculum
Nightmod / Nightcode - thank Zach
https://nightmod.net
Emacs, Clojure Cursive, LightTable - other environments (IDEs).
50 / 57
51. Other popular languages
Javascript - Runs in the browser.
ClojureScript - Clojure for Javascript.
Ruby - Popular language with startups.
Python - Popular for data science.
Many many more.
Find one you (and your friends) like and form a
study group.
51 / 57
55. Thank You
Julio Barros - http://twitter.com/JulioBarros
Justin Holguin
Jed Clinger
Nuatu Tseggai
55 / 57
56. Feedback
1. What went well?
2. What can be improved?
3. How do we reach more people?
56 / 57
57. Exercise: Better Motion
1) Make the enemies drift to the right as they fall.
2) Make some enemies go much faster than other enemies
3) Make enemies zig zag in a smooth(ish) manner as they fall.
57 / 57