#python tuples
Explore tagged Tumblr posts
Text
https://tpoittech.stck.me/post/932098/Understanding-Python-Tuples-Immutable-Data-Made-Simple
0 notes
Text
Master Polymorphism in Java – Scientech Easy
Dive into Polymorphism in Java with easy-to-follow guides at Scientech Easy. Learn how Java supports method overloading and overriding, enabling flexible and dynamic behavior in your programs. Perfect for enhancing your OOP skills!

#constructor in java#collection framework in java#Exception handling in Java#inheritance in java#Interface in Java#Python tuple#bca course subjects
0 notes
Text
How to Access Tuple Elements in Python
Python is a versatile programming language that simplifies handling data through its built-in data structures, including tuples. Tuples are immutable sequences, meaning their contents cannot be altered once created. Despite this immutability, tuples offer efficient ways to access and manipulate data when needed. In this blog, we’ll explore how to access tuple elements in Python effectively and why mastering this concept is essential for every Python learner.
If you're just starting your programming journey, understanding how tuple elements in Python work is a fundamental step. With their immutability and ability to store multiple values in a single variable, tuples are a practical tool for organizing data. At our free e-learning tutorial portal, we break down such concepts with live examples to make programming accessible and engaging for students.
Accessing Tuple Elements by Index
In Python, you can access tuple elements by their index position. Indexing in Python starts at 0, so the first element of a tuple is accessed with index 0, the second element with 1, and so on. You can also use negative indexing to access elements from the end of the tuple, where -1 refers to the last element.
Here’s an example:
Define a tuple
my_tuple = ('apple', 'banana', 'cherry')
Access the first element
print(my_tuple[0]) # Output: apple
Access the last element
print(my_tuple[-1]) # Output: cherry This simple approach to accessing tuple elements in Python is intuitive and efficient, especially when you need specific values in a dataset.
Accessing Multiple Tuple Elements Using Slicing Slicing allows you to retrieve multiple elements from a tuple in a single operation. With slicing, you define a range of indices separated by a colon :.
Define a tuple
my_tuple = (10, 20, 30, 40, 50)
Access elements from index 1 to 3
print(my_tuple[1:4]) # Output: (20, 30, 40)
Access elements from the start to index 2
print(my_tuple[:3]) # Output: (10, 20, 30)
Access elements from index 2 to the end
print(my_tuple[2:]) # Output: (30, 40, 50) Slicing is a powerful technique to work with tuple elements in Python when you need a subset of the data for further processing.
Iterating Through Tuple Elements
Another common way to access tuple elements in Python is by iterating through them. Using a for loop, you can process each element in the tuple without worrying about its index.
Iterate over a tuple
my_tuple = ('Python', 'Java', 'C++')
for item in my_tuple: print(item) This approach is particularly useful when working with larger datasets or when you need to perform operations on every element of the tuple.
Why Learn Tuple Accessing?
Mastering how to access tuple elements in Python is a crucial skill for anyone learning programming. Tuples are widely used in real-world applications for storing immutable data, such as configurations, coordinates, or function returns. They help keep your data safe from accidental changes while ensuring quick retrieval when needed.
At our free online e-learning tutorial portal, we teach programming concepts like these in an easy-to-understand way, complete with live examples. Designed specifically for students and beginners, our platform simplifies programming with hands-on exercises and engaging explanations. Whether you’re new to programming or looking to refine your skills, our tutorials provide the perfect starting point.
Tuples are a powerful yet simple feature in Python, and learning to access tuple elements effectively can open up endless possibilities in your programming projects. Dive into our tutorials today to explore this concept and many more with clarity and confidence!
0 notes
Text
Getting Started with Python: A Beginner's Guide (pt 2)
They say teaching is the best way to learn. Consider subscribing to the website!
Expanding Your Knowledge: Collections and Control Flow In Part 1 of our beginner’s guide to Python, we covered the basics of variables, data types, and conditional statements. Now, let’s dive deeper into collections like lists, tuples, and dictionaries, as well as control flow mechanisms such as loops and functions. Lists: More Than Just Arrays As mentioned earlier, a list is a collection of…
#Beginner#Coding#Dictionaries#Functions#Getting started with Python#Introduction to Python programming#Learn Python#Lists#Loops#Programming#Python#Python basics#Python conditional statements#Python control structures#Python data types#Python for beginners#Python operators#Python variables#Tuples
0 notes
Text

Morn~~ ⛅
gotta get done with collection data types today!! 🐍🖥️
0 notes
Text
The Art of Using Tuples in Python
Python is a versatile and high-level programming language that is used for a wide range of applications. One of the most important data structures in Python is the tuple. In this article, we will discuss the concept of tuples in Python, how to create them, and various operations that can be performed on them. What are Tuples in Python? A tuple is an immutable, ordered collection of items, which…
View On WordPress
#accessing elements in tuple#how to use tuple in python#python programing#python tuple#python tutorial#tuple concatenation#tuple example#tuple in python#unpacking tuple
0 notes
Text
The #1 thing keeping me from making more actual studyblr content is that all my actual studying is so unaesthetic. Yes I memorized the difference between python sets, lists, dictionaries, arrays, and tuples. No I cannot post it on my aesthetic blog, because the way I memorized it was by making little characters for each of them like they were ocs and then writing rhyming poems about them w/ a relationship chart (tuples and lists are good friends)
#studyblr#personal#university#programming#chaotic academia#catch me out here doing anything but memorizing the content in a hinged manner
22 notes
·
View notes
Text
dark secrets of the elders (more under the cut)
making python obligatory at my university was a mistake
ok, this is a very simple code with like. VERY limited ideas, but, in my defense, we only had 5 classes + i made this randomly.
the code has lists (actually tuples but who tf cares) of 10 names, 10 verbs and 15 more words for objects (hence the numbers in the prompts). it basically just chooses the elements the based on the numbers the user inputted and mashes them together. nothing extraordinary but a fun way to practice, i guess
some other weird results:
- Resh is currently ignoring mantas - Sah is afraid of Teth (who isn't?) - Daleth loves krills
the code (there must be a better way to do this but i'm a noobie):
names = ('Daleth', 'Ayin', 'Teth', 'Sah', 'Mekh', 'Tsadi', 'Lamed', 'Alef', 'Resh', 'Megabird') verbs = ('plays 4d chess with', 'loves', 'despises', 'eats', 'regularly goes to the pub with', 'is afraid of', 'is currently ignoring', 'gets drunk with', 'secretely loves', 'wants to kill') objs = ('Daleth', 'Ayin', 'children', 'Teth', 'Sah', 'chicken', 'birds', 'mantas', 'Mekh', 'Tsadi', 'Lamed', 'Alef', 'Resh', 'krills', 'Megabird') print('Welcome to the awful headcanon generator!') yes = input('Type yes to continue') if yes == 'yes': name = int(input('Type a number from 1 to 10')) verb = int(input('Type a number from 1 to 10')) obj = int(input('Type a number from 1 to 15')) print(names[name - 1], verbs[verb - 1], objs[obj - 1])
#idk if this is anything#i just wanted to share my masterpiece#idk how to export this thing properly so you'll have to trust me that this works i guess#wow this post is very random#sky children of the light#sky cotl#samekh#technically???#not tagging others though#runaway codes#have i just made up a tag for this specific post? hell yeah
7 notes
·
View notes
Text
Python Operator Basics
x or y - Logical or (y is evaluated only if x is false)
lambda args: expression - Anonymous functions (I don't know what the fuck is this, I have to look into it)
x and y - Logical and (Y is evaluated only if x is true)
<, <=, >, >=, ==, <>, != - comparison tests
is, is not - identity tests
in, in not - membership tests
x | y - bitwise or (I still have to learn bitwise operation)
x^y - bitwise exclusive or (I read this somewhere now I don't remember it)
x&y - bitwise and (again I have to read bitwise operations)
x<;<y, x>>y - shift x left or right by y bits
x+y, x-y - addition/concatenation , subtraction
x*y, x/y, x%y - multiplication/repetition, division, remainder/format (i don't know what format is this? should ask bard)
-x, +x, ~x - unary negation, identity(what identity?), bitwise complement (complement?)
x[i], x[i:j], x.y, x(...) - indexing, slicing, qualification (i think its member access), function call
(...), [...], {...} `...` - Tuple , list dictionary , conversion to string
#kumar's python study notes#study notes#study blog#coding#programmer#programming#python#studyblr#codeblr#progblr
67 notes
·
View notes
Text
GDScript vs C# in Godot
GDScript pros:
the built-in ID is way better at highlighting GDScript syntax and pointing out mistakes as you go. it doesn't do this at all for C#
you can negatively index arrays in GDScript, which is really nice
the engine is actually fully documented for GDScript, which it most certainly isn't for C#.
GDScript cons:
the modulo operator works wrong, i.e., it doesn't work for negative numbers. -1%5 == -1. it took me ages to figure out why i couldn't index this damn string correctly.
i fucking hate gdscript. why do i have to type "var" before each new variable if we're not doing static typing? why do you only have two types of collection, "array" (really "list") and "dictionary"? i could sure use stuff like tuples and sets and so forth. why can't functions return multiple values? you also can't unpack arrays like in python (var1, var2, var3 = array_with_three_values), which is annoying as shit.
you can't overload functions. or define operators for custom classes. all the time you are saving me by not having to type semicolons and curly braces is being wasted writing the most ungainly shit known to man.
fuck this noise. i'm going back to C#. yes, i have to wait for your rickety ass to compile it every time, but the better integration to the engine is not worth having to use your weird fucked-up python wanna be scripting language.
14 notes
·
View notes
Text
What is Data Structure in Python?
Summary: Explore what data structure in Python is, including built-in types like lists, tuples, dictionaries, and sets, as well as advanced structures such as queues and trees. Understanding these can optimize performance and data handling.

Introduction
Data structures are fundamental in programming, organizing and managing data efficiently for optimal performance. Understanding "What is data structure in Python" is crucial for developers to write effective and efficient code. Python, a versatile language, offers a range of built-in and advanced data structures that cater to various needs.
This blog aims to explore the different data structures available in Python, their uses, and how to choose the right one for your tasks. By delving into Python’s data structures, you'll enhance your ability to handle data and solve complex problems effectively.
What are Data Structures?
Data structures are organizational frameworks that enable programmers to store, manage, and retrieve data efficiently. They define the way data is arranged in memory and dictate the operations that can be performed on that data. In essence, data structures are the building blocks of programming that allow you to handle data systematically.
Importance and Role in Organizing Data
Data structures play a critical role in organizing and managing data. By selecting the appropriate data structure, you can optimize performance and efficiency in your applications. For example, using lists allows for dynamic sizing and easy element access, while dictionaries offer quick lookups with key-value pairs.
Data structures also influence the complexity of algorithms, affecting the speed and resource consumption of data processing tasks.
In programming, choosing the right data structure is crucial for solving problems effectively. It directly impacts the efficiency of algorithms, the speed of data retrieval, and the overall performance of your code. Understanding various data structures and their applications helps in writing optimized and scalable programs, making data handling more efficient and effective.
Read: Importance of Python Programming: Real-Time Applications.
Types of Data Structures in Python
Python offers a range of built-in data structures that provide powerful tools for managing and organizing data. These structures are integral to Python programming, each serving unique purposes and offering various functionalities.
Lists
Lists in Python are versatile, ordered collections that can hold items of any data type. Defined using square brackets [], lists support various operations. You can easily add items using the append() method, remove items with remove(), and extract slices with slicing syntax (e.g., list[1:3]). Lists are mutable, allowing changes to their contents after creation.
Tuples
Tuples are similar to lists but immutable. Defined using parentheses (), tuples cannot be altered once created. This immutability makes tuples ideal for storing fixed collections of items, such as coordinates or function arguments. Tuples are often used when data integrity is crucial, and their immutability helps in maintaining consistent data throughout a program.
Dictionaries
Dictionaries store data in key-value pairs, where each key is unique. Defined with curly braces {}, dictionaries provide quick access to values based on their keys. Common operations include retrieving values with the get() method and updating entries using the update() method. Dictionaries are ideal for scenarios requiring fast lookups and efficient data retrieval.
Sets
Sets are unordered collections of unique elements, defined using curly braces {} or the set() function. Sets automatically handle duplicate entries by removing them, which ensures that each element is unique. Key operations include union (combining sets) and intersection (finding common elements). Sets are particularly useful for membership testing and eliminating duplicates from collections.
Each of these data structures has distinct characteristics and use cases, enabling Python developers to select the most appropriate structure based on their needs.
Explore: Pattern Programming in Python: A Beginner’s Guide.
Advanced Data Structures

In advanced programming, choosing the right data structure can significantly impact the performance and efficiency of an application. This section explores some essential advanced data structures in Python, their definitions, use cases, and implementations.
Queues
A queue is a linear data structure that follows the First In, First Out (FIFO) principle. Elements are added at one end (the rear) and removed from the other end (the front).
This makes queues ideal for scenarios where you need to manage tasks in the order they arrive, such as task scheduling or handling requests in a server. In Python, you can implement a queue using collections.deque, which provides an efficient way to append and pop elements from both ends.
Stacks
Stacks operate on the Last In, First Out (LIFO) principle. This means the last element added is the first one to be removed. Stacks are useful for managing function calls, undo mechanisms in applications, and parsing expressions.
In Python, you can implement a stack using a list, with append() and pop() methods to handle elements. Alternatively, collections.deque can also be used for stack operations, offering efficient append and pop operations.
Linked Lists
A linked list is a data structure consisting of nodes, where each node contains a value and a reference (or link) to the next node in the sequence. Linked lists allow for efficient insertions and deletions compared to arrays.
A singly linked list has nodes with a single reference to the next node. Basic operations include traversing the list, inserting new nodes, and deleting existing ones. While Python does not have a built-in linked list implementation, you can create one using custom classes.
Trees
Trees are hierarchical data structures with a root node and child nodes forming a parent-child relationship. They are useful for representing hierarchical data, such as file systems or organizational structures.
Common types include binary trees, where each node has up to two children, and binary search trees, where nodes are arranged in a way that facilitates fast lookups, insertions, and deletions.
Graphs
Graphs consist of nodes (or vertices) connected by edges. They are used to represent relationships between entities, such as social networks or transportation systems. Graphs can be represented using an adjacency matrix or an adjacency list.
The adjacency matrix is a 2D array where each cell indicates the presence or absence of an edge, while the adjacency list maintains a list of edges for each node.
See: Types of Programming Paradigms in Python You Should Know.
Choosing the Right Data Structure
Selecting the appropriate data structure is crucial for optimizing performance and ensuring efficient data management. Each data structure has its strengths and is suited to different scenarios. Here’s how to make the right choice:
Factors to Consider
When choosing a data structure, consider performance, complexity, and specific use cases. Performance involves understanding time and space complexity, which impacts how quickly data can be accessed or modified. For example, lists and tuples offer quick access but differ in mutability.
Tuples are immutable and thus faster for read-only operations, while lists allow for dynamic changes.
Use Cases for Data Structures:
Lists are versatile and ideal for ordered collections of items where frequent updates are needed.
Tuples are perfect for fixed collections of items, providing an immutable structure for data that doesn’t change.
Dictionaries excel in scenarios requiring quick lookups and key-value pairs, making them ideal for managing and retrieving data efficiently.
Sets are used when you need to ensure uniqueness and perform operations like intersections and unions efficiently.
Queues and stacks are used for scenarios needing FIFO (First In, First Out) and LIFO (Last In, First Out) operations, respectively.
Choosing the right data structure based on these factors helps streamline operations and enhance program efficiency.
Check: R Programming vs. Python: A Comparison for Data Science.
Frequently Asked Questions
What is a data structure in Python?
A data structure in Python is an organizational framework that defines how data is stored, managed, and accessed. Python offers built-in structures like lists, tuples, dictionaries, and sets, each serving different purposes and optimizing performance for various tasks.
Why are data structures important in Python?
Data structures are crucial in Python as they impact how efficiently data is managed and accessed. Choosing the right structure, such as lists for dynamic data or dictionaries for fast lookups, directly affects the performance and efficiency of your code.
What are advanced data structures in Python?
Advanced data structures in Python include queues, stacks, linked lists, trees, and graphs. These structures handle complex data management tasks and improve performance for specific operations, such as managing tasks or representing hierarchical relationships.
Conclusion
Understanding "What is data structure in Python" is essential for effective programming. By mastering Python's data structures, from basic lists and dictionaries to advanced queues and trees, developers can optimize data management, enhance performance, and solve complex problems efficiently.
Selecting the appropriate data structure based on your needs will lead to more efficient and scalable code.
#What is Data Structure in Python?#Data Structure in Python#data structures#data structure in python#python#python frameworks#python programming#data science
6 notes
·
View notes
Text
Learn Inheritance in Java – Scientech Easy
Master the concept of Inheritance in Java with step-by-step tutorials on Scientech Easy. Understand how Java classes inherit methods and fields, and explore types like single, multilevel, and hierarchical inheritance. Perfect for beginners and advanced learners alike!

#bca course subjects#Interface in Java#Python tuple#Exception handling in Java#collection framework in java#constructor in java#Polymorphism in Java
1 note
·
View note
Text
What is Python, How to Learn Python?
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in various fields like: ✅ Web Development (Django, Flask) ✅ Data Science & Machine Learning (Pandas, NumPy, TensorFlow) ✅ Automation & Scripting (Web scraping, File automation) ✅ Game Development (Pygame) ✅ Cybersecurity & Ethical Hacking ✅ Embedded Systems & IoT (MicroPython)
Python is beginner-friendly because of its easy-to-read syntax, large community, and vast library support.
How Long Does It Take to Learn Python?
The time required to learn Python depends on your goals and background. Here’s a general breakdown:
1. Basics of Python (1-2 months)
If you spend 1-2 hours daily, you can master:
Variables, Data Types, Operators
Loops & Conditionals
Functions & Modules
Lists, Tuples, Dictionaries
File Handling
Basic Object-Oriented Programming (OOP)
2. Intermediate Level (2-4 months)
Once comfortable with basics, focus on:
Advanced OOP concepts
Exception Handling
Working with APIs & Web Scraping
Database handling (SQL, SQLite)
Python Libraries (Requests, Pandas, NumPy)
Small real-world projects
3. Advanced Python & Specialization (6+ months)
If you want to go pro, specialize in:
Data Science & Machine Learning (Matplotlib, Scikit-Learn, TensorFlow)
Web Development (Django, Flask)
Automation & Scripting
Cybersecurity & Ethical Hacking
Learning Plan Based on Your Goal
📌 Casual Learning – 3-6 months (for automation, scripting, or general knowledge) 📌 Professional Development – 6-12 months (for jobs in software, data science, etc.) 📌 Deep Mastery – 1-2 years (for AI, ML, complex projects, research)
Scope @ NareshIT:
At NareshIT’s Python application Development program you will be able to get the extensive hands-on training in front-end, middleware, and back-end technology.
It skilled you along with phase-end and capstone projects based on real business scenarios.
Here you learn the concepts from leading industry experts with content structured to ensure industrial relevance.
An end-to-end application with exciting features
Earn an industry-recognized course completion certificate.
For more details:
#classroom#python#education#learning#teaching#institute#marketing#study motivation#studying#onlinetraining
2 notes
·
View notes
Text
Day 4-6
29|05|2024
My Python Learning
I learn tuples and sets in python.
1.Tuples access, update, unpack etc
2. Sets access, add items, remove items, loop
You can learn with me...



#100 day challenge#codeblr#coding#learning#my python learning#programming#spotify#python#study aesthetic#studyblr#collage#study motivation#studyspo#college#Spotify
7 notes
·
View notes
Text
RenPy: Defining Characters
One of the first things RenPy does upon initialization (the boot-up period before the start label executes the game) is read your custom-made character strings to determine what character dialogue will look like.
Although defining usually takes place under the init block, I've chosen to make a separate pre-start label for organization purposes. Really, any time is fine as long as you make sure the pre-start label runs before the game actually executes, or else you're going to encounter errors.
Let's take a look at the code piece by piece.
$ a = Person(Character("Arthur", who_color="#F4DFB8", who_outlines=[( 3, "#2B0800", 0, 2 )], what_outlines=[( 3, "#2B0800", 0, 2 )], what_color="#F4DFB8", who_font="riseofkingdom.ttf", what_font="junicode.ttf", ctc="ctc", ctc_position="fixed", what_prefix='"', what_suffix='"'), "Arthur", "images/arthurtemp1.png") $ is a common symbol used by both Python and RenPy to define custom-made variables. Here in the pre-start label section of our script, we're using it to define our characters.
For the sake of propriety, it's probably better to define characters using define, but for ease of use, I've chosen $ instead.
It would be tiresome to have to write "Arthur" every time I wanted to call him in the script. Luckily, by assigning these parameters before initialization, RenPy will read "a" as Arthur.
Most scripts will suffice with assigning a Character object class to your character. If you open the script for The Tutorial, you'll find a basic string that looks like this: $ e = Character("Eileen") As you can see in my batch of code, however, I've done something different by nestling the Character object class within a Person object class. The reason why will become apparent in future posts.
For now, let's focus on the fundamentals.
---
who_color tells RenPy the color of the character's name, determined by a hexadecimal code (either three, four, or six digits). Its sister parameter what_color tells RenPy the color of a character's dialogue text.
If no values are given for these parameters, RenPy will look at your project's GUI file to determine them.
---
who_font tells RenPy the kind of font you want to use for your character's name, and likewise, what_font determines the font you want to use for your character's dialogue.
Note that these fonts do not have to match. They can be whatever font you wish.
The size of character names and dialogue text can be customized in the GUI file of your project:
---
who_outlines=[( 3, "#2B0800", 0, 2 )], what_outlines=[( 3, "#2B0800", 0, 2 )]
who_outlines and what_outlines add outlines or drop shadows to your text (character name and character dialogue, respectively). This string is expressed as a tuple, or four values enclosed by parentheses.
The first value expresses the width of the shadow in pixels. The second value is a hexadecimal value for your chosen color. The third value offsets the shadow along the X-axis (pixels to the right or left of the text). Because it's set to 0, my drop shadows do not appear to the right or the left of the text. The fourth value offsets the shadow along the Y-axis (pixels beneath/above the text). In this case, shadows appear 2 pixels beneath the text.
My outlines are a bit hard to see because they're only 3 pixels wide and 2 pixels offset.
---
Font files RenPy recognizes TrueType font files. You can download TTF fonts for free online - just be sure to unzip them and put them in your game folder.
If you intend to monetize your project, you absolutely need to make certain your fonts are royalty-free or, ideally, public domain. Most font families come with licenses telling you whether they are free use.
To be on the safe side, I would put the following code before the start label in your script, just so RenPy knows which files to look for:
init:
define config.preload_fonts = ["fontname1.ttf", "fontname2.ttf", "fontname3.ttf"]
---
ctc stands for "click to continue." It's a small icon commonly seen in visual novels, usually in one corner of the text box, that indicates the player has reached the end of a line. It's called "click to continue" because the program waits for the reader to interact to continue. To make a custom ctc icon, make a small drawing in an art program and save the image to your GUI folder. As seen above, I'm using a tiny moon as the ctc in my current project. ctc_position="fixed" means the ctc icon will stay rooted in whatever place you specify in the code. Like with most everything else in RenPy, you can apply transforms to the ctc if you so wish. Fun fact: because the ctc is determined on a character-by-character basis in initialization, you can give different characters custom ctcs!
---
what_prefix="" and what_suffix="" add scare quotes to the beginning and end of a character's dialogue.
One thing you'll notice as you work with RenPy is that "the computer is stupid." That is to say, the program will not execute code you don't explicitly spell out. Things which seem intuitive and a given to us are not interpreted by the program unless you write them into the code.
That is why, in this case, you need to specify both prefix and suffix, otherwise RenPy may begin lines of dialogue with " but not end with ", or vice-versa.
Note that unless you apply these parameters to the narrator character, ADV and NVL narration will not have them.
---
** Note: the next two tags following these ones are extraneous and therefore ignored.
9 notes
·
View notes
Text
RPG DE TERMINAL
Fala galera! Eu sou o FaaF e aqui está um projeto que eu criei em PYTHON! Chamado de "RPG de Terminal". Eu me inspirei no Easter Egg de Call of Duty Black Ops onde você consegue acessar um joguinho de texto secreto ao digitar "ZORK" em um terminal de computador:
E me inspirando nisso eu decidi fazer a coisa mais Nerd possível, criar um RPG usando programação, onde toda a história seria contada em forma de texto e o jogador tomaria ações que levariam ele a finais diferentes dentro do jogo.
Lembrando que se quiser ver o vídeo onde eu explico todo esse código é só acessar o canal:
Meu GIT-HUB para os interessados em ver algum código meu:
CHEGA DE ENROLAÇÃO!!!! VAMOS CODAR!
Lembrando que não vou acrescentar o código TODO aqui, vou apresentar aspectos que podem te ajudar a criar um RPG, se quiser a versão completa é só pegar no repositório do meu Git-Hub.
1 - CONFIGURANDO A ESCRITA DEVAGAR
Como vocês sabem, ao dar um PRINT em Python é normal que ele cole as informações muito rápidas no terminal, então aqui vai uma função simples que fará com que a escrita do seu terminal possa ser mais devagar, criando esse aspecto de uma história sendo contada:
Após criar essa função, não será mais necessário usar o print('') para fazer seus textos e diálogos, basta usar dessa forma:
Você pode regular a velocidade do seu texto mexendo na variável "intervalo".
2 - USANDO A BIBLIOTECA SYS
É muito importante importar a biblioteca Sys porque ela é responsável por criar funções para o interpretador do Python, e ao criar o RPG eu a usei para 2 finalidades: Limpar a tela do terminal e finalizar o código a qualquer momento.
Para evitar que fique muita informação poluída na tela, eu usei a função:
Assim quando ela for executada, a tela é limpa e seu diálogo/texto segue normalmente.
Em casos de muitos finais paralelos do jogo e várias vias de caminhos, eu me vi em situações onde eu precisava dar um "GAMEOVER" e fechar o código na hora, mesmo que ele ainda tivesse linhas a executar. Pra isso é usado a seguinte função:
3 - ADICIONANDO ANIMAÇÕES E UM DADO DE 20 LADOS
Uma das partes mais complexas do código se da pelas "belíssimas" artes em ASCII e um dado de 20 lados funcional que é usado em uma batalha que ocorre em um final secreto do RPG.
É realmente difícil você conseguir fazer uma arte linda para rodar no seu terminal de PRG, mas esse 1D20 que eu fiz quebrou o galho na hora de fazer uma rolagem, como vocês podem ver ele usa a biblioteca RANDOM para puxar valores aleatórios, fazer uma mini animação de números e no final exibe a rolagem do dado. Lembrando que para ver o teste real é só assistir no Youtube que eu tiro quaisquer dúvidas.
4- CONSIDERAÇÕES FINAIS DO CÓDIGO
Eu gostei muito de criar um joguinho com Python, recomendo muito vocês que querem aprender a mexer com IF/ELSE, LIST, MATHCASE, TUPLE...tentem fazer um RPG de Terminal e me marquem porque eu adoraria ver e apresentar em vídeo o projeto de vocês!
Se forem usar o meu código de inspiração eu faço uma última recomendação: Não usem tantos "While True" no código para não perderem, recomendo criarem funções e ir as chamando conforme o caminho do jogo seja acionado. MUITO OBRIGADO PELA ATENÇÃO AO MEU BLOG!!!!!
Ass.: FaaF
5 notes
·
View notes