| |
Begginers Guide
Page history last edited by bonbon 1 yr ago
Beginners Guide
Description
This tutorial will give beginner coders a brief overview of python, and how to code.
Difficulty
Beginner to Advanced
Length
2-6+ hours
Covers
Downloading Python
Basic Syntax
Beginners tutorials
Where to get extra help
Various Modules
One race with almost every line commented on
Requires
Python IDLE
Lots of free time, and I mean lots
A basic knowledge of computers if you can't find the download link, I suggest you leave
Optional (Highly recommended) some program with syntax highlighting such as Notepad++ (what I will be using for this tutorial Crimson Editor or many other editors if you already have one
Optional (Recommended for further help with python) An IRC Chat client such as Chatzilla(for firefox users), mIRC (One of the most talked about don't get confused, if anyone says theres no difference between IRC and mIRC I will hate you forever) once you install one of those, or one of many others out there, type /join #eventscripts, If Im on my computer, Ill be there.
Contributers
Me
A lot of these tutorials or from Python Eventscripts Wiki and the contributers there are awsome
Version
1.0
Note:
Races are coded in python, and you will not actually start coding a race for a while. You probably wont start making your first race today in fact. Before you start making a race, youre going to need to learn the basics of python. This will take you a while, so if you are not 100% serious about learning python, and spending numerous hours upon hours learning python, I suggest that you go back to playing your games. Also, I will imediatly delete this topic if anyone pms me asking for help continuesly, if I dont want to tell you a simple answer or something like that and I end up getting interupted while playing a game, or coding. I will delete this topic, and itll all be on you and everyone will hate you. And yes, many of this does repeat, I am aware of that and it is on purpose. If it didn't repeat youd never get it and I know that so if you think "nah, I got this I'll just skip over it" you're wrong, don't do that, it's a nub mistake to do you'll forget very quickly if you don't go over and over stuff
Getting Started
Python For Begginers
Part 1: Programs in a file, and variables
Introduction
Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.
Editing in Notepad
Writing programs in python to a file is VERY easy. Python programs are simply text documents - you can open them up in notepad, and have a look at them, just like that. So, go and open notepad. Type the following:
[python]
- A simple program.
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."[/python]
Keep this exactly the same, down to where the commas are placed. Save the file as 'mary.py' - and make sure Notepad doesn't add .txt to the end of the filename; You will have to tell it to save as any file, to avoid this. Turn off 'Hide known file extensions' in Windows Explorer, if it makes it easier.
Using the IDLE Enviroment
Now, open up the Python IDLE program (if you don't have it, download Python 2.5 here.). Click 'File > Open' and find mary.py and open it. if you cant find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run>Run Module' (or just press F5). Your program will now run in the main Python screen (Titled *Python Shell*) and will look like this:
Mary had a little lamb,
it's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.
You can also use IDLE to create Python programs, like what you did in notepad. Simply click 'File > New'. We will be writing all of our programs now in the python IDLE program - the notepad thing is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.
There are a couple of things to notice here:
• First of all, the comment wasn't shown. That is good, because remember - comments aren't compiled. (try compiling it after removing the # - it comes out messy)
• Second, is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text. In the 'print' command, this stops the program from starting a new line on the screen when showing text.
• You can also run the program from your command line program (e.g. MSDOS) - Open the prompt up, type 'cd pathtoyourfile' then type 'python mary.py'. Your program will now execute in the command line.
Variables
Now lets start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE, click 'File>New Window' - a new window now appears, and it is easy to type in programs. Type the following (or just copy and paste - just read very carefully, and compare the code to the output that the program will make):
[python]
- Variables demonstrated
print "This program is a demo of variables"
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 51
print "v can store any numerical value, to be used elsewhere."
print "for example, in a sentence. v is now worth", v
print "v times 5 equals", v*5
print "but v still only remains", v
print "to make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "there you go, now v equals", v, "and not", v / 5[/python]
Strings
As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
[python]
- Giving variables text, and adding text.
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " +word3
print sentence[/python]
The output will be:
Good Morning
Good Morning to you too!
As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).
[b]Part 1: Conclusion[/b]
Well done! We now understand longer programs, and know the use of variables. In Part 2, we look at loops and conditions, about them and how to use them.
Part 2: Loops, Loops, Loops, Loops...
Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program, not to mention slow and pointless. Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. Such a thing is called a loop.
The 'while' loop
The following are examples of a type of loop, called the 'while' loop:
[python]a = 0
while a < 10:
a = a + 1
print a[/python]
How does this program work? Lets go through it in English:
[python]'a' now equals 0
As long as 'a' is less than 10, do the following:
Make 'a' one larger than what it already is.
print on-screen what 'a' is now worth.
What does this do? Lets go through what the computer would be 'thinking' when it is in the 'while' loop:
#JUST GLANCE OVER THIS QUICKLY
#(It looks fancy, but is really simple)
Is 'a' less than 10? YES (its 0)
Make 'a' one larger (now 1)
print on-screen what 'a' is (1)
Is 'a' less than 10? YES (its 1)
Make 'a' one larger (now 2)
print on-screen what 'a' is (2)
Is 'a' less than 10? YES (its 2)
Make 'a' one larger (now 3)
print on-screen what 'a' is (3)
Is 'a' less than 10? YES (its 3)
Make 'a' one larger (now 4)
print on-screen what 'a' is (4)
Is 'a' less than 10? YES (its 4)
Make 'a' one larger (now 5)
print on-screen what 'a' is (5)
Is 'a' less than 10? YES (its 5)
Make 'a' one larger (now 6)
print on-screen what 'a' is (6)
Is 'a' less than 10? YES (its 6)
Make 'a' one larger (now 7)
print on-screen what 'a' is (7)
Is 'a' less than 10? YES (are you still here?)
Make 'a' one larger (now 8)
print on-screen what 'a' is (8)
Is 'a' less than 10? YES (its 8)
Make 'a' one larger (now 9)
print on-screen what 'a' is (9)
Is 'a' less than 10? YES (its 9)
Make 'a' one larger (now 10)
print on-screen what 'a' is (10)
Is 'a' less than 10? NO (its 10, therefore isn't less than 10)
Don't do the loop
There's no code left to do, so the program ends
So in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (and a couple of examples):
while {condition that the loop continues}:
{what to do in the loop}
{have it indented, usually four spaces}
{the code here is not looped}
{because it isn't indented}[/python]
[python]
- EXAMPLE
- Type this in, see what it does
x = 10
while x != 0:
print x
x = x - 1
print "wow, we've counted x down, and now it equals", x
print "And now the loop has ended."
[/python]
Remember, to make a program, you open IDLE, click File > New Window, type your program in the new window, then press F5 to run.
Boolean Expressions
What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.
What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:
My age == the age of the person next to me
And the statement would be TRUE. If you were younger than the person opposite, you'd say:
My age < the age of the person opposite me
And the statement would be TRUE. If, however, you were to say the following, and the person opposite of you was younger than you:
My age < the age of the person opposite me
The statement would be FALSE - the truth is that it is the other way around. This is how a loop thinks - if the expression is true, keep looping. If it is false, don't loop. With this in mind, lets have a look at the operators (symbols that represent an action) that are involved in boolean expressions:
Exp. Function
< less than
<= less that or equal to
> greater than
>= greater than or equal to
= not equal to
<> not equal to (alternate)
== equal to
Conclusion
Hopefully you will now understand the basics of Python, how to make a simple program, knowledge of classes, all the different types of variables and why and how they are used. Also, please take a look at the next tutorial: ES_Python_for_Beginners.
Retrieved from "http://python.eventscripts.com/pages/Python_for_Beginners"
Lesson 1
Description
[b]Previous Lesson: n/a[/b]
[b]Next Lesson: Lesson 2[/b]
In this Lesson we will download, install and check Python is working. Python makes it easy to run single lines of code - one-liner programs under a program called IDLE (Integrated [DeveLopment] Environment) which we will also investigate. Also: Mathematics and Comments.
Tutorial Content
Download Python
Ok then, first off, we need to Download Python. You can visit the Python homepage here, then Download the latest Windows Binaries from here.
Installing Python
Now you have downloaded Python, you can go onto Installing it. Just simply open the python-2.5.1.msi file (for me) to initialize the Setup process. Once Python has installed, setup your Windows PATH so you can use the python.exe executable directly by doing the following:
? Goto the Control Panel (Start->Control Panel).
? Double-click the System icon.
? Click on the Advanced tab and then click on Environment Variables.
? In the bottom Listbox, find the Path variable and click Edit.
? At the end of the value, put: ;E:Python; (E:Python should be changed to where you installed python to)
Checking Python is installed
To make sure Python has installed correctly, launch the Command Prompt (Start->Run->cmd.exe) and then put in: python -V. You should get something like:
C:Documents and [SettingsRoot]>python -V
Python 2.5.1
Make sure you use a capital V, or you will launch Python in verbose mode; sounds scary, but go ahead, try it. You should get something like:
C:Documents and [SettingsRoot]>python -v
[python]
- installing zipimport hook
import zipimport
- builtin
- installed zipimport hook
- E:Pythonlibsite.pyc matches E:Pythonlibsite.py
import site
- precompiled from E:Pythonlibsite.pyc
- E:Pythonlibos.pyc matches E:Pythonlibos.py
import os
- precompiled from E:Pythonlibos.pyc
import nt
- builtin
- E:Pythonlibntpath.pyc matches E:Pythonlibntpath.py
import ntpath
- precompiled from E:Pythonlibntpath.pyc
- E:Pythonlibstat.pyc matches E:Pythonlibstat.py
import stat
- precompiled from E:Pythonlibstat.pyc
- E:PythonlibUserDict.pyc matches E:PythonlibUserDict.py
import [UserDict]
- precompiled from E:PythonlibUserDict.pyc
- E:Pythonlibcopy_reg.pyc matches E:Pythonlibcopy_reg.py
import copy_reg
- precompiled from E:Pythonlibcopy_reg.pyc
- E:Pythonlibtypes.pyc matches E:Pythonlibtypes.py
import types
- precompiled from E:Pythonlibtypes.pyc
import _types
- builtin
- E:Pythonliblocale.pyc matches E:Pythonliblocale.py
import locale
- precompiled from E:Pythonliblocale.pyc
import encodings
- directory E:Pythonlibencodings
- E:Pythonlibencodings__init__.pyc matches E:Pythonlibencodings__init__.
py
import encodings
- precompiled from E:Pythonlibencodings__init__.pyc
- E:Pythonlibcodecs.pyc matches E:Pythonlibcodecs.py
import codecs
- precompiled from E:Pythonlibcodecs.pyc
import _codecs
- builtin
- E:Pythonlibencodingsaliases.pyc matches E:Pythonlibencodingsaliases.py
import encodings.aliases
- precompiled from E:Pythonlibencodingsaliases.pyc
import _locale
- builtin
E:Pythonlibre.pyc matches E:Pythonlibre.py
import re
- precompiled from E:Pythonlibre.pyc
- E:Pythonlibsre_compile.pyc matches E:Pythonlibsre_compile.py
import sre_compile
- precompiled from E:Pythonlibsre_compile.pyc
import _sre
- builtin
- E:Pythonlibsre_constants.pyc matches E:Pythonlibsre_constants.py
import sre_constants
- precompiled from E:Pythonlibsre_constants.pyc
- E:Pythonlibsre_parse.pyc matches E:Pythonlibsre_parse.py
import sre_parse
- precompiled from E:Pythonlibsre_parse.pyc
import operator
- builtin
- E:Pythonlibencodingscp1252.pyc matches E:Pythonlibencodingscp1252.py
import encodings.cp1252
- precompiled from E:Pythonlibencodingscp1252.pyc
- E:Pythonlibwarnings.pyc matches E:Pythonlibwarnings.py
import warnings
- precompiled from E:Pythonlibwarnings.pyc
- E:Pythonliblinecache.pyc matches E:Pythonliblinecache.py
import linecache
- precompiled from E:Pythonliblinecache.pyc
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>[/python]
Your probably thinking, "What the hell...", yes, so am I. It means nothing at all for us folk, just press Ctrl-Z to close the Python program.
Opening IDLE
Now we will try using IDLE: Go to the start menu, find Python, and run the program labeled IDLE.
Now you are in the IDLE environment. This is the place you will be spending most time in. Here you can open a new window to write python modules / programs, or you can simply mess around with single lines of code, which is what we are going to do. Type the following and press enter: (don't type >>> as it should already be there)
>>> print "Hello, World!"
What happened? You just created a program, that prints the words 'Hello, World'. The IDLE environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though.
Math in Python
Take a look at the example code below; I've given explainations in brackets:
[python]>>> 1 + 1
2
>>> 20+80
100
>>> 18294+449566
467860
(These are additions)
>>> 6-5
1
(Subtraction)
>>> 2*5
10
(Multiply, rabbits!)
>>> 52
25
(Exponentials e.g. this one is 5 squared)
>>> print "1 + 2 is an addition"
1 + 2 is an addition
(the print statement, which writes something onscreen)
>>> print "one kilobyte is 2^10 bytes, or", 210, "bytes"
one kilobyte is 2^10 bytes, or 1024 bytes
(you can print sums and variables in a sentence.
The commas seperating each section are a way of
seperating clearly different things that you are printing)
>>> 21/3
7
>>> 23/3
7
>>> 23.0/3.0
7.6666...
(division, 2nd time ignoring remainder / decimals,
3rd time including decimals)
>>> 23%3
2
>>> 49%10
9
(the remainder from a division)[/python]
As you see, there is the code on one line, then the result of that code on the next. I then explain them in brackets. These are the basic commands of Python, and what they do. Here is a table to clarify them:
cmd name example output
======================================
+ Addition 4+5 9
- Subtraction 8-5 3
/ Division 19/3 6
% Remainder 19%3 5
======================================
Remember that thing called order of operation that they taught in maths? Well, it applies in python, too. Here it is, if you need reminding (BODMAS):
B: Brackets first
O: Orders (ie Powers and Square Roots, etc.)
DM: Division and Multiplication (left-to-right)
AS: Addition and Subtraction (left-to-right)
Order of Operations
Here are some examples that you might want to try, if you're rusty on this:
[python]>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9[/python]
In the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at lowly 4).
In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1) and addition comes in later than that.
Also remember that the math is calculated from left to right, UNLESS you put in parentheses. The innermost parentheses are calculated first. Watch these examples:
[python]>>> 4 - 40 - 3
-39
>>> 4 - (40 - 3)
-33[/python]
In the first example, 4 -40 is calculated,then - 3 is done. In the second example, 40 - 3 is calculated, then it is subtracted from 4.
Comments
The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):
[python]>>>
- I am a comment. Fear my wrath!
>>>
A comment is a piece of code that is not run. In python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:
>>> print "Food is very nice" # Yum :p
Food is very nice
(Everything after the
- is not parsed)
>>>
- print "Food is very nice"
(Nothing happens, because the code was after a comment)
>>> print "Food is very nice" Yum :p[/python]
(You'll get a fairly harmless error message,
because you didn't put your comment after a hash)
Comments are important for adding necessary information for another programmer to read, but not the computer. For example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment bits of code by putting a # in front of it - if you don't want it to compile, but cant delete it because you might need it later.
Conclusion
There you go! Lesson 1 Completed. Next lesson, we make Python "Programs" with many lines of code, and save them, so we can actually send them to people. That's right, you don't have to retype every program you run! What an amazing innovation!
Lesson 2
[b]Description
Previous Lesson: Lesson 1
Next Lesson: Lesson 3[/b]
Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.
Content
Writing In Notepadd
Writing programs in Python to a file is very easy. Python programs (uncompiled) are simply text documents - you can open them up in Notepad, and have a look at them, just like that. So, go and open notepad. Type the following:
[python]
- A simple program.
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."[/python]
Keep this exactly the same, down to where the commas are placed. Save the file as mary.py.
Using the IDLE Environment
Now, open up the Python IDLE program again. Goto the Open file dialog (File->Open), find mary.py and open it. A new window will open, showing the program you just wrote. Run the module (same as program, just in Python terms): to do this, click Run and then Run Module (or just press F5). Your program will now run in the main Python screen, titled *Python Shell*; and will look like this:
Mary had a little lamb,
it's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.
You can also use IDLE to create Python programs, like what you did in Notepad. Simply click File->New. We will be writing all of our programs now in the python IDLE program - the Notepad example is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.
There are a couple of things to notice here:
? First of all, the comment wasn't shown. That is good, because remember - comments aren't compiled. (Try compiling it after removing the # -- it comes out errory [is that a word?])
? Second, is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text in the print command.
? You can also run the program from your command line program (e.g. MS-DOS) - Open the prompt up, type cd pathtoyourfile then type python mary.py. Your program will now execute in the command line.
Variables
Now lets start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE, click File->New Window -- a new window now appears, and it is easy to type in programs. Type the following (or just Copy and Paste -- just read very carefully, and compare the code to the output that the program will make):
[python]
- Variables demonstrated
print "This program is a demo of variables"
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 51
print "v can store any numerical value, to be used elsewhere."
print "for example, in a sentence. v is now worth", v
print "v times 5 equals", v*5
print "but v still only remains", v
print "to make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "there you go, now v equals", v, "and not", v / 5[/python]
Strings
As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text -- a variable that holds text is called a string. Try this program:
[python]<
- Giving variables text, and adding text.
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " +word3
print sentence[/python]
The output will be:
Good Morning
Good Morning to you too!
As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).
Conclusion
Well done! We now understand longer programs, and know the use of variables. In Lesson 3, we investiage at Loops and Conditionals. Take a look at the tutorial description to go onto the next lesson.
Lesson 3
Description
Previous Lesson: Lesson 2
Next Lesson: Lesson 4
In this lesson we will investiage "Loops and Conditionals": Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program, not to mention slow and pointless. Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. Such a thing is called a loop.
Tutorial Content
The 'while' loop
The following are examples of a type of loop, called the 'while' loop:
[python]a = 0
while a < 10:
a = a + 1
print a[/python]
How does this program work? Lets go through it in English:
'a' now equals 0
As long as 'a' is less than 10, do the following:
Make 'a' one larger than what it already is.
print on-screen what 'a' is now worth.
What does this do? Lets go through what the computer would be 'thinking' when it is in the 'while' loop:
#JUST GLANCE OVER THIS QUICKLY
#(It looks fancy, but is really simple)
Is 'a' less than 10? YES (its 0)
Make 'a' one larger (now 1)
print on-screen what 'a' is (1)
Is 'a' less than 10? YES (its 1)
Make 'a' one larger (now 2)
print on-screen what 'a' is (2)
Is 'a' less than 10? YES (its 2)
Make 'a' one larger (now 3)
print on-screen what 'a' is (3)
Is 'a' less than 10? YES (its 3)
Make 'a' one larger (now 4)
print on-screen what 'a' is (4)
Is 'a' less than 10? YES (its 4)
Make 'a' one larger (now 5)
print on-screen what 'a' is (5)
Is 'a' less than 10? YES (its 5)
Make 'a' one larger (now 6)
print on-screen what 'a' is (6)
Is 'a' less than 10? YES (its 6)
Make 'a' one larger (now 7)
print on-screen what 'a' is (7)
Is 'a' less than 10? YES (are you still here?)
Make 'a' one larger (now 8)
print on-screen what 'a' is (8)
Is 'a' less than 10? YES (its 8)
Make 'a' one larger (now 9)
print on-screen what 'a' is (9)
Is 'a' less than 10? YES (its 9)
Make 'a' one larger (now 10)
print on-screen what 'a' is (10)
Is 'a' less than 10? NO (its 10, therefore isn't less than 10)
Don't do the loop
There's no code left to do, so the program ends
So in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (and a couple of examples):
while {condition that the loop continues}:
{what to do in the loop}
{have it indented, usually four spaces}
{the code here is not looped}
{because it isn't indented}
[python]
- EXAMPLE
- Type this in, see what it does
x = 10
while x != 0:
print x
x = x - 1
print "wow, we've counted x down, and now it equals", x
print "And now the loop has ended."[/python]
Remember, to make a program, you open IDLE, click File > New Window, type your program in the new window, then press F5 to run.
Boolean Expressions
What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.
What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:
My age == the age of the person next to me
And the statement would be TRUE. If you were younger than the person opposite, you'd say:
My age < the age of the person opposite me
And the statement would be TRUE. If, however, you were to say the following, and the person opposite of you was younger than you:
My age < the age of the person opposite me
The statement would be FALSE - the truth is that it is the other way around. This is how a loop thinks - if the expression is true, keep looping. If it is false, don't loop. With this in mind, lets have a look at the operators (symbols that represent an action) that are involved in boolean expressions:
Exp. Function
==================================
< less than
<= less that or equal to
> greater than
>= greater than or equal to
= not equal to
<> not equal to (alternate)
== equal to
==================================
Dont get = and == mixed up -- the = operator makes what is on the left equal to what is on the right. the '==' operator says whether the thing on the left is the same as what is on the right, and returns true or false.
Conditional Statements
OK! Now we've covered while loops. Now let's look at something a little different: conditionals.
Conditionals are where a section of code is only run if certain conditions are met. This is similar to the while loop you just wrote, but only runs once. A conditional loop only runs when x doesn't equal y. The most common conditional in any program language, is the if statement. Here is how it works:
[python]if {conditions to be met}:
{do this}
{and this}
{and this}
{but this happens regardless}
{because it isn't indented}
- EXAMPLE 1
y = 1
if y == 1:
print "y still equals 1, I was just checking"
- EXAMPLE 2
print "We will show the even numbers up to 20"
n = 1
while n <= 20:
if n % 2 == 0:
print n
n = n + 1
print "there, done."[/python]
Example 2 there looks tricky. But all we have done is run an if statement every time the 'while' loop runs. Remember that the % just means the remainder from a division -- just checking that there is nothing left over if the number is divided by two - showing it is even. If it is even, it prints what n is.
else and elif - When it Ain't True
There are many ways you can use the 'if' statement, do deal with situations where your boolean expression ends up FALSE. They are else and elif. else simply tells the computer what to do if the conditions of if arent met. For example, read the following:
[python]a = 1
if a > 5:
print "This shouldn't happen."
else:
print "This should happen."[/python]
a is not greater than five, therefore what is under 'else' is done. elif is just a shortened way of saying else if. When the if statement fails to be true, elif will do what is under it IF the conditions are met. For example:
[python]z = 4
if z > 70:
print "Something is very wrong"
elif z < 7:
print "This is normal"
The if statement, along with else and elif follow this form:
if {conditions}:
{run this code}
elif {conditions}:
{run this code}
elif {conditions}:
{run this code}
else:
{run this code}
- You can have as many or as little elif statements as you need
- anywhere from zero to the sky.
- You can have at most one else statement
- and only after all other ifs and elifs.[/python]
One of the most important points to remember is that you MUST have a colon : at the end of every line with an if, elif, else or while in it.
Indentation
One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a while loop, you must put a set number of spaces at the beginning of each of the next five lines (this is usually 4 spaces or a tab). This is good programming practice in any language, but Python requires that you do it. Here is an example of both of the above points:
[python]a = 10
while a > 0:
print a
if a > 5:
print "Big number!"
elif a % 2 != 0:
print "This is an odd number"
print "It isn't greater than five, either"
else:
print "this number isn't greater than 5"
print "nor is it odd"
print "feeling special?"
a = a - 1
print "we just made 'a' one less than what it was!"
print "and unless a is not greater than 0, we'll do the loop again."
print "well, it seems as if 'a' is now no bigger than 0!"
print "the loop is now over, and without furthur adue, so is this program!"[/python]
Notice the three levels of indents there: 1. Each line in the first level starts with no spaces. It is the main program, and will always execute. 2. Each line in the second level starts with four spaces. When there is an if or loop on the first level, everything on the second level after that will be looped / ifed, until a new line starts back on the first level again. 3. Each line in the third level starts with eight spaces. When there is an if or loop on the second level, everything on the third level after that will be looped / ifed, until a new line starts back on the second level again. 4. This goes on infinitely, until the person writing the program has an internal brain explosion, and cannot understand anything he/she has written.
There is another loop, called the for loop, but we will cover that in a later lesson, after we have learnt about Lists and Tuples.
Conclusion
And that concludes Lesson 3! In lesson 4, we investigate User Interaction, and writing programs that actually serve a purpose. Can't wait? Goto the top of the page and click on the link next-to Next Tutorial.
Lesson 4
[b]Description
Previous Lesson: Lesson 3
Next Lesson: Lesson 5[/b]
Last lesson I said that we would delve into purposeful programming. Also we will be using user inputs, and user inputs require a thing called functions if you wish to use them complexy (is that a word?)
What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.
Tutorial Content
Using a function
Python has lots of pre-made functions, that you can use right now, simply by calling them. Calling a function involves you giving a function input if the function requires parameters, and it will return a value (like a variable would) as output (if it returns a value). Don't understand? Here is the general form that calling a function takes:
function_name(parameters)
See? Easy.
? Function_name identifies which function it is you want to use (You'd figure...). For example, the function raw_input, which will be the first function that we will use.
? Parameters are the values you pass to the function to tell it what is should do, and how to do it. For example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5, then return the answer.
Parameters, Returning Values and Communicating with Functions
Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?
Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Lets call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:
a = multiply(70)
The computer would actually see this:
a = 350
Note: Don't bother typing in this code -- multiply() isn't a real function, unless you create it.
The function ran itself, then returned a number to the main program, based on what parameters it was given.
Now let's try this with a real function, and see what it does. The function is called raw_input, and asks the user to type in something. It then turns it into a string of text. Try the code below:
- this line makes 'a' equal to whatever you type in
a = raw_input("Type in something, and it will be repeated on screen:")
- this line prints what 'a' is now worth
print a
Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:
a = "hello"
print "hello"
Remember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.
A Calculator program
Lets write another program, that will act as a calculator. This time it will do something more adventerous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the raw_input function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in python, there is a difference.).
Luckily, somebody wrote the function input, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc.
Now, lets design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.
We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a input) and an if loop.
Lets write it out in understandable English first:
START PROGRAM
print opening message
"""Calculator program"""
while we let the program run, do this:
#Print what options you have
print Option 1 - add
print Option 2 - subtract
print Option 3 - multiply
print Option 4 - divide
print Option 5 - quit program
ask for which option is is you want
if it is option 1:
ask for first number
ask for second number
add them together
print the result onscreen
if it is option 2:
ask for first number
ask for second number
subtract one from the other
print the result onscreen
if it is option 3:
ask for first number
ask for second number
multiply!
print the result onscreen
if it is option 4:
ask for first number
ask for second number
divide one by the other
print the result onscreen
if it is option 5:
tell the loop to stop looping
Print onscreen a goodbye message
END PROGRAM
Lets put this in something that Python can understand:
[python]loop = 1
- 1 means loop; anything else means don't loop.
choice = 0
- This variable holds the user's choice in the menu
while loop == 1:
- Print what options you have
s
print "Welcome to calculator.py"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
choice = int(raw_input("Choose your option: ").strip())
if choice == 1:
add1 = input("Add this: ")
add2 = input("to this: ")
print add1, "+", add2, "=", add1 + add2
elif choice == 2:
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print sub1, "-", sub2, "=", sub1 - sub2
elif choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print mul1, "*", mul2, "=", mul1 * mul2
elif choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
print div1, "/", div2, "=", div1 / div2
elif choice == 5:
loop = 0
print "Thank-you for using calculator.py!"[/python]
Wow! That is an impressive program! Paste it into python IDLE, save it as 'calculator.py' and run it. Play around with it -- try all options, entering in integers (numbers without decimal points), and floats (stuff after the decimal point). Try typing in text, and see how the program chucks a minor fit, and stops running (that can be dealt with, using error handling, which we can address in Lesson 10.)
define your own functions
Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and code. Maybe use them in other programs? This is where the def operator comes in. If you don't know, an operator is just something that tells python what to do. For example, the + operator tells Python to add things, the if operator tells Python to do something if conditions are met, etc.
The basics of a function:
- Remember to put a colon ":" at the end of any line that starts with an operator,
- in this case, use the : as we are using the "def" operator.
[python]def function_name( ):
return [/python]
function_name is the name of the function. You write the code that is in the function below that line, and have it indented. The code indented is the code that is ran when you do function_name(). This function also returns a value. This is what your program gets from the function, if you wish to do something like:
hello = function_name()
The hello variable will be what function_name returned.
A function is like a miniture program that some parameters are given to, it then runs itself, and then returns a value (OPTIONAL). Your main program sees the value it returned. Here is a function that prints the words "hello" onscreen, and then returns the number 1234 to the main program:
[python]
- Below is the function
def hello():
print "hello"
return 1234
- And here is the function being used
print hello()[/python]
Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:
The output: hello 1234
So what happened? 1. When def hello() was ran, a function called 'hello' was created 2. When the line 'print hello()' was ran, the function 'hello' was executed (The code inside it was run) 3. The function hello printed "hello" onscreen, then returned the number '1234' back to the main program 4. The main program now sees the line as 'print 1234' and as a result, printed '1234'.
Passing parameters to functions
There is one more thing we will cover in this lesson is passing parameters to functions. Think back to how we defined functions:
[python]def function_name( ):
return '(optional)'>[/python]
Where is (inbetween the parentheses), you put the names of variables that you want to put the parameters into. For example:
[python]
- def line the function
def function_name(parameter1, parameter2):
print parameter1
print parameter2
- Now call the function
function_name("hello", "world")[/python]
The output would be: hello world
There is no limit to how many parameters you can have in a function, or the name of them, you can put as many as you need, just have them seperated by commas.
Here is a basic adding function:
[python] # def line is the function
def add(value1, value2):
return value1 + value2
- Call it
print add(1, 2)[/python]
The output would be: 3
The basics of the above function is, parameter 1 (value1) is being added to parameter 2 (value2) and then being returned to the program. The print function then prints the return value of the add function we made.
Conclusion
That covers functions and parameters and other crap, next lesson we will be doing "Lists, Tuples and Dictionaries", three of the main multiple value data storage datatypes in Python.
(That last sentence did not make sense)
Modules
ES - The core of [EventScripts] Python
Effectlib - Some great effects, you'll probably just use es_tools effects, though
Playerlib - Great player managment, ex. getting health, cash setting speed ect.
Gamethread - Delay functions/commands really usefull
Keymenulib - Creates an easymenu popup menu using a keygroup or a [KeyValues] object.
Keyvalues - This module provides access to the [KeyValues] object which is used to provide full recursive access to Valve's [KeyValues] C++ class and file format.
Langlib - Multi Language Support. You'd generally not use this in any races
Msglib
Popuplib - Used to easily create popup menus
Repeat - Easy repeats
Services
Settinglib
Usermsg - Advanced ways to send messages to players
Vecmath - Advanced Vector math
Votelib - Easily Create votes
Your First Race Your First Race from future import division
Your First Race from future import division
import wcs, playerlib, es, random, gamethread
from wcs import wcs
'
Since A lot of people have been asking me "Bonbon, how do I code?" I'm going to go and
explain nearly every line of this for you.
'
w = 'Wicca' - Make w = 'Wicca' so we don't have to do wcs.GetLevel(userid, 'Wicca', 'level') we can do wcs.GetLevel(userid, w, 'level') it's pretty much a lasinzess thign lol
race = wcs.Race(w) - This is another thing that's lazyness
raceskill = wcs.Race(w).registerSkill - more lazyness
raceskill('Book of Spells', 5, 1, "A spell book has tought you how to respawn your teamates on death") - Register a skill claled book of spells with 5 maximum levels at an increase of 1 required to buy
raceskill('Deadly Potions', 6, 1, "A chance to become fast, slightly invisible, and have high health +ability to use or consequences") - register another skill
raceskill('Spying Beacon', 1, 3, "Beacon your enemies to always know their locations") - register another skill
raceskill('Healing Spring', 5, 2, "Heal yourself and those around you") - register another skill
race.registerUltimate("Invulnerable Teamates", 4, 4, 5, "Hold down your ultimate to make your teamates within range invulnerable") - Register an ultimate this is the skill that happens when people type +ultimate in console
race.registerMinLevel(125) - make it so that you can only use this race if you're level 125+
- est_effect 11 #a 0 sprites/purpleglow1.vmt server_var(wcs_x1) server_var(wcs_y1) server_var(wcs_z1) 1 3.5 150
- est_effect 11 #a 0 sprites/purpleglow1.vmt %s %s %s 4 2 255
beam_userids = [] - Create an empty list so that we can later append it and put userids in it for some cool laser effects
def player_ultimate_on(ev): - Every time a player types +Ultimate in console or presses their bind, this will activate
userid = int(ev['userid']) - Call userid as an integer by int() var being ev['userid'] you can use any event info that's passed through ev here
if wcs.GetRace(userid) == w: - Make sure that the person is w which in line 9 stats w = 'Wicca'
it = wcs.GetLevel(userid, w, 'Invulnerable Teamates') - This statement gets the players level for Invulnerable Teamates
if it: - Executes if it is not 0
player = playerlib.getPlayer(userid) - Have a little thing so we dont' have to type playerlib.getPlayer(userid). instead, we can just do player.
if player.attributes['teamid'] == 2: - player.attributes['teamid'] will return 2 if they're terrorist, and 3 if they're counter-terrorist
wcs.Command(userid).Near(80 + (it * 30), god_mode, '#t,#alive') - Executes on everyone that is wihtin 80 units plus it * 30 it'll do the block god_mode go to line 41 to find it
elif player.attributes['teamid'] == 3:
wcs.Command(userid).Near(80 + (it * 30), god_mode, '#ct,#alive')
effect_time = 10 + (it * 2) - set a variable to effect_time so we dont' keep having to use 10 + (it * 2)
gamethread.delayedname(0.1, 'ultimate_effect_%s'%userid, ultimate_effect_loop, args=(userid, effect_time)) - this will delay a command by 0.1 seconds and then run the block ultimate_effect_loop with the arguments userid and effect_time
es.server.queuecmd('est_freeze %s 1'%userid) - Freeze the player so it doesnt' look wierd when the effects are goin on
wcs.Effect().Ring2(userid, 50, 1.6, 191, 62, 255) - Stolen from Jeff

wcs.Effect().Misc1(userid, 1.6) - Stolen from Jeff

x, y, z = es.getplayerlocation(userid) - Set x, y, z to the players location. you could also do loc = es.getplayerlocation(userid) and then x would bne the same as loc[0] y would bne loc[1] and z would be loc[2]
wcs.Effect().Ring5(x, y, z, 0.5, 40, 240, 255) - This is an effect in an unreleased version of wcs, lol
wcs.Command(userid).SetCoolDown('Invulnerable Teamates', 10) - Set the cooldown for the persons invulnerable teammates so they can't use it 100% of the time
def god_mode(userid, attacker): - as mentioned above, this block of code will run on everyone that has been within specified game units
es.server.queuecmd('est_god %s 1'%userid) - Make them god mode
gamethread.delayed(0.05 + wcs.GetLevel(attacker, w, 'Invulnerable Teamates') / 100, es.server.queuecmd, 'est_god %s 0'%userid) - and make them un god mode so it's not cheap (this will delay it up to 0.09 seconds)
def appendlist(player, userid): - This is the block that's going to append the list beam_userids, we've callled it with a nearcoord function later on
global beam_userids - We have to global it because it's outside of this block, it's on line 20 outside of this def so to change it, we use the global statement
beam_userids.append(player) - beam_userids.append means that we're adding to that list, we're adding player to that list
def ultimate_effect_loop(userid, effect_time): - This is the effect loop that we've called on line 33 this will give some cool effects
if effect_time >= 0: - Make sure it'll only run if the time is bigger than or equal to 0
global beam_userids - We global beam_userids here 'cause two lines down, we're going to clear it
effect_time -= 0.1 - This is the same as efect_time = effect_time - 0.1
beam_userids = [] - Clear the list beam_userids
x, y, z = es.getplayerlocation(userid) - Get the player's location, for amore detailed thingy see line 37
it = wcs.GetLevel(userid, w, 'Invulnerable Teamates') - Again, this is the level of the person
player = playerlib.getPlayer(userid) - See line 27 for more details
if random.randint(1, 3) == 1: - random.randint(1, 3) will randomly chose a number between 1 and 3th if random.randint(1, 3) == 1: will only execute if that number equals 1
player.set('health', float(player.get('health')) - 0.01) - This will set the players health, we can on ly do player.set if we've made player = playerlib.getPlayer(userid)
- Float(player.get('health') calls player.get('health') as a float, a float is a number like 0.2 or 1.0 an int is 1 or 2
if player.attributes['teamid'] == 2: - see line 28 for more info
wcs.Command(userid).Near(120 + (it * 30), god_mode, '#t,#alive') - Run the block god_mode for every alive terrorist who's withing 120 + it * 30 game units of thist person
wcs.Command(userid).Near((120 + (it * 30)), appendlist, '#t,#alive') - This will append the list (line 45) so we can later use some cool effects
elif player.attributes['teamid'] == 3: - Same thing, except it executes for ct's so it doesn't end up healing ts!
wcs.Command(userid).Near(120 + (it * 30), god_mode, '#ct,#alive')
wcs.Command(userid).Near((120 + (it * 30)), appendlist, '#ct,#alive')
for a in beam_userids: - A for loop means that it'll run kinda like a while loop, but a will equal every item inside beam_userids. in python IDLE type:
- tacos = ('cow', 'bonbon', 'moo')
- for a in tacos:
- print a
- For a better understanding
x1,y1,z1 = es.getplayerlocation(a) - Get the location of a that we've called through the for loop
es.server.queuecmd('est_effect 3 #all 0 sprites/lgtning.vmt %s %s %s %s %s %s 0.1 25 1 0 255 0 255'%(x, y, z + 30, x1, y1, z1 + 30)) - Some effects here, not that important
es.server.queuecmd('est_effect 3 #all 0 sprites/lgtning.vmt %s %s %s %s %s %s 0.1 10 10 40 240 255 255'%(x, y, z, x, y, z + 100)) - More effects
if '.0' in str(effect_time / 1.6) and '6' not in str(effect_time / 1.6): - This will execute only if the effect_time divided by 1.6 is a perfect divided thingy
wcs.Effect().Ring2(userid, 50, 1.6, 191, 62, 255) - Stolen from Jeff
wcs.Effect().Misc1(userid, 1.6) - Stolen from Jeff
gamethread.delayedname(0.1, 'ultimate_effect_%s'%userid, ultimate_effect_loop, args=(userid, effect_time)) - Do the block again, this is a "Delayed" loop
if player.get('health') <= 0: - executes if the persons health is less than or equal to 0
wcs.Command(userid).Damage(1, 32) - Deal 1 damage to them, which slays them
es.server.queuecmd('est_freeze %s 0'%userid) - Unfreeze them so they can move around in spec
else: - run if effect time is smaller than 0
es.cexec(userid, '-Ultimate') - Make the user run the command -ultimate
def player_ultimate_off(ev): - Executes every time the person releases their ultimate bind
userid = int(ev['userid']) - Call userid to be an int
if wcs.GetRace(userid) == 'Wicca': - A check to make sure that the person is the right race
if wcs.GetLevel(userid, w, 'Invulnerable Teamates'): - Make sure they have levels in their ultimate
gamethread.cancelDelayed('ultimate_effect_%s'%userid) - Cancel the delay
es.server.queuecmd('est_freeze %s 0'%userid) - Unfreeze them
def player_death(ev): - Executes whenever a player dies
userid = int(ev['userid'])
if wcs.GetRace(userid) == 'Wicca':
bs = wcs.GetLevel(userid, w, 'Book of Spells') - Make bs = the userid's level for Book Of Spells
if bs: - Only runs the block of code if bs is not 0
es.tell(userid, '#green', 'Attempting to revieve a random teammate') - Send a "Private Message" to the person telling them that they're attempting to revieve a random teammate
if random.randint(1, 100) <= 35 + bs * 5: - that'll be a 40 - 60 % chance to revieve someone
x2, y2, z2 = es.getplayerlocation(userid) - Get their location
if playerlib.getPlayer(userid).attributes['teamid'] == 2: - Again, get what team they're on
random_t = random.choice(playerlib.getUseridList('#t,#dead')) - random.choice choses a random choice from something, so this is getting a random dead terrorist
x, y, z = es.getplayerlocation(random_t)
es.server.queuecmd('est_spawn %s'%random_t) - Spawn that random terrorist
wcs.Effect().Ring5(x, y, z, 0.5, 40, 240, 255) - Some cool effects
es.server.queuecmd('est_effect 10 #a 0 sprites/scanner.vmt %s %s %s 50 350 2 90 200 0 155 155 155 155 2'%(x, y, z)) - More cool effects
es.tell(userid, '#multi', '#greenYou have respawned #lightgreen%s #green with your book of spells!'%playerlib.getPlayer(random_t).attributes['name']) - Another private message, we make %s = to the players name
es.tell(random_t, '#multi', '#greenYou have been respawned by #lightgreen%s's #green book of spells!'%playerlib.getPlayer(userid).attributes['name']) - Tell the person who we respawned that they got respawned by person
elif playerlib.getPlayer(userid).attributes['teamid'] == 3: - Same code that's run as above, expect it only runs on cts
random_ct = random.choice(playerlib.getUseridList('#ct,#dead'))
x, y, z = es.getplayerlocation(random_ct)
es.server.queuecmd('est_spawn %s'%random_ct)
wcs.Effect().Ring5(x, y, z, 0.5, 40, 240, 255)
es.server.queuecmd('est_effect 10 #a 0 sprites/scanner.vmt %s %s %s 50 350 2 90 200 0 155 155 155 155 2'%(x, y, z))
es.tell(userid, '#multi', '#greenYou have respawned #lightgreen%s #green with your book of spells!'%playerlib.getPlayer(random_ct).attributes['name'])
es.tell(random_ct, '#multi', '#greenYou have been respawned by #lightgreen%s's #green book of spells!'%playerlib.getPlayer(userid).attributes['name'])
wcs.Effect().Ring5(x2, y2, z2, 0.5, 40, 240, 255)
gamethread.cancelDelayed('beacon_%s'%userid) - Cancel the beacon loop since they're dead
def player_disconnect(ev): - Executes whenever the player leaves the server
gamethread.cancelDelayed('beacon_%s'%ev['userid']) - Cancel the beacon loop since they're no longer here
def heal(): - This is our heal loop, this will end up healing people
if es.getplayercount(): - This will execute if there's more than 0 people in the server
for userid in es.getUseridList(): - Another for loop
player = playerlib.getPlayer(userid) - More lazyness
health = player.attributes['health'] - Get the health of the person
if wcs.GetRace(userid) == 'Wicca': - A race check
hs = wcs.GetLevel(userid, w, 'Healing Spring')
if hs: - A level check
if playerlib.getPlayer(userid).get('health') < 140: - Make sure they have less than 140 health
if playerlib.getPlayer(userid).attributes['teamid'] == 2: - Executes on t
wcs.Command(userid).Near(100 + hs * 50, heal_teamates, '#t,#alive') - Will run the block heal_teamates to every t who's within 100-300 game units
elif playerlib.getPlayer(userid).attributes['teamid'] == 3:
wcs.Command(userid).Near(100 + hs * 50, heal_teamates, '#ct,#alive')
playerlib.getPlayer(userid).set('health', playerlib.getPlayer(userid).get('health') + hs * 0.7) - Give them some extra health
gamethread.delayed(2, heal, args=()) - Re-do the delay
def heal_teamates(userid, attacker): - This is the block ran by the nearcoord we called earlier
hs = wcs.GetLevel(attacker, w, 'Healing Spring') - Attacker is the pesron who initiated it
if playerlib.getPlayer(userid).get('health') <= 127: - Make sure their health is less than 127 to stop OPness
playerlib.getPlayer(userid).set('health', playerlib.getPlayer(userid).get('health') + (hs / 2.0)) - Give them some extra health
def player_ability_on(ev): - Executes whenever the person uses their ability
userid = int(ev['userid'])
if wcs.GetRace(userid) == 'Wicca': - Race check
dp = wcs.GetLevel(userid, w, 'Deadly Potions')
if dp: - Level check
if not wcs.Command(userid).GetCoolDown('Deadly Potions'): - Will only execute if the person's Deadly Potions cooldown is 0
if random.randint(1, 100) <= 50 + dp * 5: - A random chance here to succeeed
player = playerlib.getPlayer(userid)
es.server.queuecmd('est_shake %s 2.2 55 55'%(userid)) - Shake the users screen for some cool effects
es.tell(userid, '#green', 'Success!') - Tell them that they succeeded
x, y, z = es.getplayerlocation(userid)
wcs.Effect().Ring5(x, y, z, 1.5, 40, 240, 255) - more cool effects
es.server.queuecmd('est_effect 11 #a 0 models/effects/splodecard2_sheet.vmt %s %s %s 2 2 255'%(x, y, z))
es.server.queuecmd('est_effect 10 #a 0 models/effects/splodecard2_sheet.vmt %s %s %s 250 190 3 150 100 1 155 115 100 200 3'%(x, y, z))
es.server.queuecmd('est_freeze %s 1'%userid) - Freeze them
gamethread.delayed(2.2, es.server.queuecmd, 'est_freeze %s 0'%userid) - Unfreeze them in 2.2 seconds
es.server.queuecmd('es_xfire %s !self addoutput "gravity %s"'%(userid, 1 - dp / 12.0)) - Change their gravity this isn't as good as est_gravity, but I'm using it 'cause I dont' want it to be too OP
if player.get('health') <= 150: - Make sure their health is lower than 150
player.set('health', player.get('health') + 15 + dp * 3.5) - Give them some health
else: - If their health is above 150, it'll give them less health to stop OP
player.set('health', player.get('health') + 5) - Give them less heatlh
if not player.get('speed') > 1.3: - Same idea as above
player.set('speed', player.get('speed') + dp / 15.0)
else:
player.set('speed', player.get('speed') + dp / 30.0)
wcs.Command(userid).Fade((255 - 100) - (dp * 11), 2) - Turn them slightly invisible
for a in ('m3', 'xm1014', 'tmp', 'mp5navy', 'ump45', 'p90', 'mac10', 'm249', 'scout', 'awp', 'sg550', 'g3sg1', 'm4a1', 'ak47', 'famas', 'galil', 'aug', 'sg552'): - Restrict every weapon in this tuple so that it's not too OP
es.server.queuecmd('est_restrict %s %s'%(userid, 'weapon_%s'%a))
else: - Their ability failed, so now we get to do some bad things to them
random_number = random.randint(1, 8) - Make random_number equal a number between 1 and 8
if random_number == 1: - This will explode the user
potion = 'Explosive'
es.server.queuecmd('es_give %s env_explosion'%userid)
es.server.queuecmd('es_xfire %s env_explosion addoutput "iMagnitude 80"'%userid)
es.server.queuecmd('es_xfire %s env_explosion addoutput "iRadiusoverride 30"'%userid)
es.server.queuecmd('es_xfire %s env_explosion explode'%userid)
wcs.Command(userid).Damage(80, 32)
elif random_number == 2: - This will posoin the user
potion = 'Poisonous'
wcs.Command(userid).Drain(10, 1, 9)
time = 0
gamethread.delayedname(1, 'drain_%s'%userid, drain_effect_loop, args=(userid, time)) - Do the poison effect loop
elif random_number == 3: - This will make the user "sleep"
potion = 'Sleep'
es.server.queuecmd('est_stripplayer %s 1'%userid) - Strip them
es.server.queuecmd('est_freeze %s 1'%userid) - Freeze them
gamethread.delayed(2, es.server.queuecmd, 'est_stripplayer %s 1'%userid) - Strip them again in case they picked up a weapon
es.server.queuecmd('es_xgive %s weapon_glock'%userid) - Give them a glock to fend themselves for 2 seconds (LOL So mean :)
elif random_number == 4 or random_number in range(6, 9): - in range(6, 9) means that it will execute if the random_number is 6, 7 or 8 this will make them a morph potion
potion = 'Morph Potion'
playerlib.getPlayer(userid).set('model', 'props/cs_office/plant01')
es.server.queuecmd('est_stripplayer %s 1'%userid)
es.server.queuecmd('est_freeze %s 1'%userid)
elif random_number == 5: - This will bury the player
potion = 'Bury'
player_loc = es.getplayerlocation(userid)
playerlib.getPlayer(userid).set('location', [player_loc[0], player_loc[1], player_loc[2] - 60])
es.tell(userid, '#green', 'OH NO! Your potion failed You accidently made a %s potion'%potion)
wcs.Command(userid).SetCoolDown('Deadly Potions', 15)
else: es.tell(userid, '#multi', '#greenSorry, you have to wait #lightgreen%s #greenseconds to use this again'%wcs.Command(userid).GetCoolDown('Deadly Potions')) - tell them that they have to wait however many seconds to use their ability, again
def drain_effect_loop(userid, time): - This is the effect loop for the poison failure
if time <= 8: - It'll only run if the time is smaller than 8, so it doesnt' last forever
wcs.Effect().Ring4(userid, 50, 100, 1, 40, 50, 64, 0, 128) - Some effects at their feet
es.server.queuecmd('est_fade %s 1 0.2 0.2 0 255 0 100'%userid) - Fade thier screen an erie green
time += 1 - Make time = 1 more than it is
gamethread.delayedname(1, 'drain_%s'%userid, drain_effect_loop, args=(userid, time)) - Re do the block in 1 second
def player_spawn(ev): - Whenever the player spawns
userid = int(ev['userid'])
es.server.queuecmd('est_UnrestrictAll %s'%userid) - Unrestrict all their weapons so they can use stuff, again
if wcs.GetRace(userid) == 'Wicca': - Race check
bl = wcs.GetLevel(userid, w, 'Spying Beacon')
if bl: - Level check
gamethread.delayedname(1, 'beacon_%s'%userid, beacon_loop, args=(userid)) - Do the beacon loop so they can see enemies
def beacon_loop(userid): - The beacon loop mentioned above will beacon everyone of the player's enemy
if es.exists('userid', userid): - Make sure the player hasnt' left the server
if playerlib.getPlayer(userid).attributes['teamid'] == 2: - If the person's a t, make filter = ct
filter = '#ct'
elif playerlib.getPlayer(userid).attributes['teamid'] == 3: - If the person's a ct, make the filter t
filter = '#t'
else: - If the person is in spec or unasigned make the filter = moo
filter = 'moo'
if not filter == 'moo': - Execute only if the person is a t or ct
for userid2 in playerlib.getUseridList('%s,#alive'%filter): - Executes on every alive filter
x, y, z = es.getplayerlocation(userid2)
es.server.queuecmd('est_effect 10 %s 0 "sprites/lgtning.vmt" %s %s %s 20 300 0.2 20 10 0 255 0 0 255 30'%(userid, x, y, z)) - Make the ring
es.server.queuecmd('est_effect 10 %s 0.1 "sprites/lgtning.vmt" %s %s %s 20 300 0.3 15 10 0 255 150 150 255 30'%(userid, x, y, z)) - Make the ring
gamethread.delayedname(1, 'beacon_%s'%userid, beacon_loop, args=(userid)) - Re-Do the loop in 1 second
def item_pickup(ev): - Executes every time a person picks up a weapon
if wcs.GetRace(ev['userid']) == 'Wicca': - Race check
if wcs.GetLevel(ev['userid'], w, 'Deadly Potions'): - Level Check
if not ev['item'] in ('glock', 'usp', 'deagle', 'elite', 'p228', 'fiveseven') and playerlib.getPlayer(ev['userid']).get('speed') > 1: - This will execute if the weapon they picked up wasn't a pistol, and they've used thier speed is above 1 (their speed gets increased when they use their ability)
es.server.queuecmd('est_removeweapon %s weapon_%s'%(ev['userid'], ev['item'])) - Remove the weapon so they can't use it
es.tell(ev['userid'], '#green', 'You may only have pistols after using your ability!') - Tell them that they can't use rifles after using their ability
heal() - as soon as the script is loaded, it will do the block heal()
Good Sites
Google - Google's our friend
Python EventScripts Wiki - Where you can check syntax for lots of stuff and find out details of ES Commands
EventScripts Shell Wiki - Hear you can find out how to use some commands in python from regular ESS
WCS: Python Wiki - The WCS: Python Wiki where you can find commands that you can use in race making
Event Referance - A site with all the listed events that fire, very usefull
ES 2.0 Code Examples - A "Cookbook" of code examples compiled over time
The EventScripts Forums - Have any questions about python? Ask there
s
Begginers Guide
|
|
Tip: To turn text into a link, highlight the text, then click on a page or file from the list above.
|
|
|
|
|
Comments (0)
You don't have permission to comment on this page.