Jump to content


Check out our Community Blogs

chili5

Member Since 12 Mar 2008
Offline Last Active Dec 02 2017 05:41 PM
-----

#505429 SQL Functions - SQL Encryption Functions

Posted by chili5 on 03 September 2009 - 02:27 AM

SQL Encryption Functions


When you want to store really sensitive data in a database, you will want to encrypt it. This is especially important on web sites with passwords and credit card numbers. You wouldn't want a bad person looking at all your passwords would you?

There are two ways of securing data in a database: hashing and encryption. Hashing usually prevents you from obtaining the original string. Encryption allows you to obtain the original string (through decrypting). This is only possible if you know the encryption method, and the key that was used to encrypt it.


The encryption functions return a binary string, so you should use a binary column to store it. Ex: VARBINARY or BLOB. If you use things like VARCHAR, you might run into problems with a character set changing values. Making it impossible to get your data back.

Advanced Encryption Algorithm (AES)



The first algorithm, we are going to look at is the AES algorithm. The function prototype is:

AES_ENCRYPT(str,key)

With encryption functions we need a key to encrypt the string. This is something that only you should know. On our web site, we may ask the user to input a key that is used to encrypt their password or some other information. As long as they don't give out the key, then all is fine. Another thing we could do is use a really complicated string as a key, and this would allow us to retrieve passwords from the database.

Let us use this below as our key:

happyPepper


We want to encrypt a password and say my password is:

cheeseFries


I would call this function:

SELECT AES_ENCRYPT("cheeseFries","happyPepper");

The output is:

http://forum.codecal...=1&d=1251984069

I had to use the MySQLWiki command prompt to show this because notice how there is a lot of really weird characters? My PHPMyAdminWiki software ran into problems displaying the characters.


Advanced Encryption Algorithm - The Decryption Method



As long as we know the encrypted string, and the key we can get the original text back.

The syntax for this method is:

AES_DECRYPT(encrypted,key)

So applying the AES_DECRYPTWiki method to the result of AES_ENCRYPTWiki will return the original string.

SELECT AES_DECRYPT(AES_ENCRYPT("cheeseFries","happyPepper"),"happyPepper")

Output:

cheeseFries


Note: this only works if you know the key. Let us try changing the key even slightly.

Try this:

SELECT AES_DECRYPT(AES_ENCRYPT("cheeseFries","happyPeppr"),"happyPeppr")

Output:

http://forum.codecal...=1&d=1251984069

Notice, how just slightly changing the keys used produces totally different results.


Hashing Methods



An alternative to encryption is hashing functions. The difference being with hash functions you can't get the plain text back. Two hash algorithms are md5 and sha1.


MD5



The MD5Wiki function returns a binary string of 32 hex digits. One thing you might want to do with this function is use it as a key for the AES encryption function. It is pretty hard to guess a string of 32 hexadecimalWiki digits. :) This function implements the message digest algorithm.

In PHPWiki, this function is often used to hash passwords so we are not storing plain text passwords in the database.

Example:

SELECT MD5("hiii");

Output:

14e1f4b73f7d55ecf03b55f0c46fd235



SHA1



The SHA1 function uses the Secure Hash AlgorithmWiki. Given a string as a parameter, it returns a binary string of 40 digits. This is also used for storing passwords in a database and storing other sensitive information.

The return values here are going to be a lot larger than the return values of MD5.

Example:

SELECT SHA1("hiii")

Output:

1abedcd9967cc42ea624432d356a5f0bce7ae3a9


This value also makes a good key to use for encryption functions. Note, there is another encryption function called DES. This function uses the Triple-DESWiki algorithm. I didn't go over this function because I like AES.

Hope this helps.

Attached Thumbnails

  • AES_Encrypt.JPG
  • decrypt.JPG

  • 2


#505362 SQL: String Functions

Posted by chili5 on 02 September 2009 - 03:39 PM

SQL Functions - String Functions

SQL provides a large amount of functions for string manipulations.

ASCII

The ASCII function is used to return a numeric value for the leftmost character. Each character has a numeric value that represents it.

Example:

SELECT ASCII('A')

Output:

[QUOTE]
65
[/QUOTE]

65 is the numeric representation. An interesting property of characters is that each letter is one integer value away. This makes it great for adding and subtracting other values. You can perform math with characters.

So:

SELECT CHAR(ASCII('A')+1)

Returns B. This converts A to it's ascii value and adds 1. Then it converts it back to a character. This shows that the letters are exactly one integer value away.

Thus we can use this method to convert chars from upper to lowercase by observing patterns in an ASCII chart.

SELECT CHAR(ASCII('A')+ASCII('a')-ASCII('A'))

This code converts A to lowercase "a".

Character Length

The character length function returns the number of letters in the string.

SELECT CHARACTER_LENGTH("Hiii")

This function returns the number of characters in the string.

Output:

[QUOTE]
4
[/QUOTE]

Another method that does the same thing is CHAR_LENGTH.

CONCAT method

This method is used to join strings together.

SELECT CONCAT("James","Hi","There");

The function takes a variable number of arguments and joins them together.

The returning value is:

[QUOTE]
Jame****here
[/QUOTE]

Format Function

Returns a number formatted to a certain amount of decimals. The function prototype is:

[QUOTE]
FORMAT(num,D)
[/QUOTE]

The number num is formatted in a format similar to '#,###.##'. The number of decimals is D values.

Example:

SELECT FORMAT(1234.343332,3)

Output:

[QUOTE]
1,234.343
[/QUOTE]

Lowercase Functions

The function LCASE returns a string in lower case. This function does the same thing as the LOWER function.

Example:

SELECT LOWER("Test");

Output:

[QUOTE]
test
[/QUOTE]

Trim Functions

There are three functions:

  • LTRIM
  • RTRIM
  • TRIM

that remove the space from around the string. The LTRIM function removes all leading spaces before the left side of the string. The RTRIM function removes all trailing spaces after the right side of the string. The TRIM function removes all leading and trailing spaces.

Examples:

SELECT LTRIM("      Test");
SELECT RTRIM("Test       ");
SELECT TRIM("       Test      ");
SELECT RTRIM("         Test          ");

Output:

[QUOTE]
Test
Test
Test
Test
[/QUOTE]

Replace

The generic function is:

REPLACE(str,replace,new)

The replace function replaces all instances of a string replace with new.

Example:

SELECT REPLACE("Test  this is just a test test test","test","yo!");

The output:

[QUOTE]
Test this is just a yo! yo! yo!
[/QUOTE]

All instances of "this" will be replaced with "yo". This method is case-sensitive. Notice, how Test was not replaced?

Reverse Function

This function returns a string that is reversed.

Example:

SELECT REVERSE("test");

The output is:

[QUOTE]
tset
[/QUOTE]

Substring Function

There are two versions of this function:

SUBSTR(str,pos)

and

SUBSTR(str,pos,len)

The first function copies all the characters from index pos to the end of the string. One thing to note, the index of the first character is one.

Example:

SELECT SUBSTR("test",2);

Output:

[QUOTE]
est
[/QUOTE]

The second version specifies how many characters to copy and where to start copying from.

Example:

SELECT SUBSTR("test",1,2);

This function starts at the first character and copies two characters.

Output:

[QUOTE]
te
[/QUOTE]

Uppercase Function

The UPPER function converts a string into upper case.

Example:

SELECT UPPER("test");

Output:

[QUOTE]
TEST
[/QUOTE]
  • 2


#505229 SQL Functions - Math Functions

Posted by chili5 on 02 September 2009 - 05:28 AM

SQL Functions - Math Functions

Just like how programming languages have functions built-in to allow you to do common tasks easily. So does SQL. A lot of these functions are mathematical. Some of them are more useful than others.


ABS Function

The absolute value. The absolute value can be thought of as the distance from 0 on a number line to whatever number you have. So say your number is -5. The distance from 0 to -5 is 5. The distance from 0 to 5 is also 5. This is why the absolute value is simply the argument without any negative sign.

In math we write the absolute value as:

|a|

Now a formula for the absolute function is:

[QUOTE]
|a| = a, a >= 0
a*-1, otherwise
[/QUOTE]

Programmatically, this can be written as

int abs(int a) {
	if (a >= 0) {
		return a;
	}
	return a / -1;
}	

Let us take a look at how the abs function works.

Example:

SELECT ABS(-1) AS absolute;

Output:

[QUOTE]
1
[/QUOTE]

Let us try passing a positive value instead.

SELECT ABS(5) AS absolute;

Output:

[QUOTE]
5
[/QUOTE]

Trig Functions

The available trig functions are:

ACOS
ASIN
ATAN
TAN
COS
SIN

The first three are the inverse functions. So given a tangent value the resulting value is the angle with that tangent. The return value will be an angle in radians.

Example of COS:

SELECT COS(5.5) AS cosine;

Output:

[QUOTE]
0.70866977429126
[/QUOTE]

You can confirm the results by setting your calculator to radians and taking the cosine of 5.5.

While we are looking at cosine, let us look at ACOS. This function is the inverse cosine.

Example of SIN:

SELECT SIN(3.55) AS sine;

The SIN function also takes a parameter representing an angle in radians. The resulting value is then the sine of that angle.

Output:

[QUOTE]
-0.39714816728596
[/QUOTE]


Tangent

This function TAN also takes a parameter being the angle in radians. The output is the tangent of that angle.

Example:

SELECT TAN(3.5553) AS tangent;

Output:

[QUOTE]
0.43904601857096
[/QUOTE]

Granted, I'm not sure why you would need trig functions in a database application but they are there. Perhaps for games?

Rounding Functions

Two functions are CEIL and CEILING. These both take a floating point parameter. These functions return the smallest integer value that is not less than the parameter.

Example:

SELECT CEIL(5.35) AS roundedUp;

Output:

[QUOTE]
6
[/QUOTE]

You can think of this method as round up to the nearest integer. As for whichever you use, CEIL or CEILING they are both same function, so it comes down to personal choice.

Example of CEILING:

SELECT CEILING(5.35) AS roundedUp;

Output:

[QUOTE]
6
[/QUOTE]

These functions might be useful if you have a program that keeps track of how much you send and receive from the internet. However, you want to keep the values to the nearest megabyte. So you use ceiling to get the value to the nearest megabyte.

Floor Function

The floor function allows you to round a number to the largest integer value that is less than the parameter. You can think of this function as "rounding down".

Example:

SELECT FLOOR(5.35) AS roundedDown;

The output:

[QUOTE]
5
[/QUOTE]

Rounding

The function is ROUND.

This function allows you to specify how many digits you want to.

The generic formula is:

ROUND(X,Y)

This states that we are going to round X to Y decimal places.

SELECT ROUND(5.334333,2);

The result is:

[QUOTE]
5.33
[/QUOTE]

Converting Radians to Degrees

For one reason or another all programming languages seem to use radians to represent angles. However, from a young age we are brought up with the concept of degrees. So degrees naturally make more sense to us. To convert from radians to degrees we use the function DEGREES.


Let's say that we have a value in radians of 0.4567 and we want to convert it to degrees.

Example:

SELECT DEGREES(0.4567) AS deg;

Output:

[QUOTE]
26.1669825036247
[/QUOTE]

0.4567 radians is the same as 26.1669825036247 degrees. If we convert 26.1669825036247 back to radians, the resulting value should be 0.4567.

Converting Degrees to Radians

The function to convert to back to radians is RADIANS.

Example:

SELECT RADIANS(26.1669825036247) AS rad;

The output is:

[QUOTE]
0.4567
[/QUOTE]

This confirms that radians and degrees are inverse functions.

So:

SELECT RADIANS(DEGREES(x));

The resulting value is x.

Exponents

An exponent is simply multiplying a number by itself x times. So x^n means to multiply x by itself n times. So 5^3 = 5*5*5. This is what the POW function does for us.

Example:

SELECT POW(5,3) AS pow;

Output:

[QUOTE]
125
[/QUOTE]


Greatest and Max Functions

The greatest function takes a variable number of arguments and returns the largest value in the set.

Example:

SELECT GREATEST(5,3,8.5,9,-2,5,63,323,34,333);

Output:

[QUOTE]
333
[/QUOTE]

If you look at the values, you will have noticed that 333 is the largest value in the set.

To demonstrate the MAX function we actually need to create a table and populate it with some data.

In a database called test, create this table:

CREATE TABLE IF NOT EXISTS `nums` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Then populate it with this data:

INSERT INTO `nums` (`id`, `age`) VALUES
(1, 3),
(2, 5);

The result:

SELECT MAX(age) FROM nums;

The output is:

[QUOTE]
5
[/QUOTE]

I wish I knew about this a long time ago. It is more efficient than my method. What I would always do is use ORDER BY to sort the list in descending order and LIMIT 1 would make the result at the top the largest value.

Example:

SELECT age FROM nums ORDER BY age DESC LIMIT 1;

Output:

[QUOTE]
5
[/QUOTE]

You can see the results are the same, but to get my answer I have to sort it. What if they are a lot of values? Granted I'm assuming that MAX also creates a temporary array of sorted values also, but I don't know.

Least and MIN Functions

This functions are very similar to the above functions. The MIN function selects the smallest value in a column. The least function takes a set of values and returns the smallest value in the set.

Example of least:

SELECT LEAST(5.5,3.5,2,4,-1) AS smallest;

Output:

[QUOTE]
-1
[/QUOTE]

Now we can use the table we created above to demonstrate the MIN function.

SELECT MIN(age) FROM nums;

Output:

[QUOTE]
3
[/QUOTE]

Looking at the table, we created, we can confirm that 3 is the smallest value in the list.

I didn't know a whole lot about SQL functions, so what I would do when I needed to do this was:

SELECT age FROM nums ORDER BY age ASC LIMIT 1;

Output:

3

This function sorts the column in ascending order and the first item is the smallest value in the column which is why I use LIMIT 1.

PI

This function simply returns the value of PI.

Example:

SELECT PI();

Output:

[QUOTE]
3.141593
[/QUOTE]

Random Number

This function chooses a random floating point number between 0 and 1. We can then manipulate this number with multiplication and addition to get a seemingly random number in a range.

SELECT RAND()

One possible output:

[QUOTE]
0.234685802119491
[/QUOTE]

Then we can multiply this value by some value and truncate the decimal. This allows us to limit the biggest value possible.

Example:

SELECT FLOOR(10*RAND())

We use FLOOR to truncate the decimal.

One possible output:

[QUOTE]
2
[/QUOTE]

Now by adding a value to the end, allows us to control the smallest possible value generated.

SELECT FLOOR(10*RAND())+1

One possible output:

[QUOTE]
5
[/QUOTE]

This function can be really useful in games.

Total Values

One really useful function is SUM. This function lets you find the total values in a column in a table. Going back to the table we created above, let us find the sum of all the ages.

SELECT SUM(age) FROM nums;

Output:

[QUOTE]
8
[/QUOTE]

Average

Now, say we want to know what the average age is. This is where the AVG function is useful.

SELECT AVG(age) FROM nums;

Output:

[QUOTE]
4.0000
[/QUOTE]

We get this value by adding up all the values in the column and dividing by the number of terms. In our case: (5+3)/2 = 4.

You can see how this function is more efficient than making a query to count the number of items. Then a query to find the sum. Then dividing them yourself. That is how I would have done it because I didn't know about this function.

Example:

SELECT SUM(age) / (SELECT COUNT(age) FROM nums) FROM nums;

Output:

[QUOTE]
4.0000
[/QUOTE]

My method isn't wrong, it is just a bad way to do it. Why iterate twice, when you can iterate and count at the same time? I don't have that kind of control with my method. I never actually did use that code above but it is a functional but poor way of doing it.

Modulus Function

This function simply returns the remainder of integer division.

We know that 5/2 = 2. This is because with integers there is no decimal point.

If we want the remainder, wecan use the mod function to determine the remainder.

Example:

SELECT MOD(5,2);

Result:

[QUOTE]
1
[/QUOTE]

Final notes

These are a lot that I didn't know about SQL. When I started my first project, I didn't know there was functions so I used other (possibly less efficient) methods to do what I wanted.

If I could, I would go back and change my program to use these functions. Granted, a lot of the functions I see no purpose for. Then again, my program was a database manager not a game or anything highly mathematical. The most math I did was adding and subtracting values. However, now I see how I could cut out a lot of queries from my program with these simple functions.

Another day we will look at inverse trigonometric functions and a more practical application of these functions.
  • 1


#504921 SQL Date

Posted by chili5 on 01 September 2009 - 09:49 AM

SQL Date

SQL provides a lot of functions for manipulating dates in a database. You can store values in a date field or a datetime field. If you store the dates as unix_timestamps you can get a lot more flexibility with dates. In fact, this is usually what is done when you are using PHP with the database.

It might even make sense to store them as timestamps anyways. This is because I always convert them to timestamps before I use them.


Creating the Database

We are going to create a test database with a people table. The people table will contain these fields:

  • id
  • name
  • date

First, the code to create the database:

CREATE DATABASE `test` ;

Now, we need to create the table.

CREATE TABLE `test`.`people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`date` DATE NOT NULL
) ENGINE = MYISAM ;

This table contains 3 fields just like we said it would. Now let us add some data. The format for the date needs to be yyyy-mm-dd.

The date could be when they registered to a web site or when they first made an order, or whatever.

Populating the table

INSERT INTO `people` (`id`, `name`, `date`) VALUES
(1, 'James', '2009-09-16'),
(2, 'Joe', '2009-09-30'),
(3, 'Jack', '2009-09-18');

We are going to insert 3 rows of data.


UNIX_TIMESTAMP function

Like I said earlier, it is easier to work with dates as numbers. This number is the unix timestamp which is the number of milliseconds that have past since January 1st, 1900.

To see how this works let us select all the UNIX_TIMESTAMPS from the database.

SELECT UNIX_TIMESTAMP(date) AS theDate FROM people;

The resulting output is:

http://forum.codecal...=1&d=1251838133

These values are the unix timestamps representing the dates that we inserted above. We can use these values to compare dates. This allows us to select rows that occur between the two days.

A date occurs between two dates if the unix_timestamp is >= the test date and <= the test date.

BETWEEN clause


We use the BETWEEN clause to test if a date occurs between two dates.

Let us return all results that occur between '2009-09-16' and '2009-09-18'.


The SQL query is simply:

SELECT * FROM people WHERE UNIX_TIMESTAMP(date) BETWEEN UNIX_TIMESTAMP('2009-09-16') AND UNIX_TIMESTAMP('2009-09-18')

The result is:

http://forum.codecal...=1&d=1251838133

I convert the date field that I am comparing to a unix_timestamp and I also convert the dates that I am testing it to a unix timestamp. This makes comparing easy.

Attached Thumbnails

  • dates.JPG
  • between.JPG

  • 2


#504895 SQL: Select Queries

Posted by chili5 on 01 September 2009 - 09:04 AM

Writing SELECT queries for SQL databases

When you want to get results from a database you issue a select query. With this query you can limit the results based on certain criteria, sort it, and subsort it. You can do a lot with this including selecting data from multiple tables. This is done using joins which is a topic for another day.


First we are going to create a database called test with a people table.

The code to create our database is:

CREATE DATABASE test;

Now we need to create a table, and populate it with some data.

CREATE TABLE `test`.`people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`age` SMALLINT NOT NULL
) ENGINE = MYISAM ;

This SQL code creates a table with 3 fields in it. The id field is a unique field that we can use to refer to any records we want. Then we have a name field that is a variable character field. The age field is an integer field to hold a persons age.

Since this is just a tutorial on select queries, I am going to give you some queries that we can use to demonstrate select queries.


INSERT INTO `people` (`id`, `name`, `age`) VALUES
(1, 'James', 16),
(2, 'Joe', 5),
(3, 'Jack', 9),
(4, 'Bill', 15),
(5, 'Topa', 93);

Selecting all the data

To select all data we simply use the * to mean select all. Then we name the table.

The basic syntax is:

SELECT field names | * FROM tableName;

This code is to select all the data:

SELECT * FROM people;

The result set will look like this:

http://forum.codecal...=1&d=1251835336

Specifying the Columns

You can specify what columns you want to return also.

Example:

SELECT name, age FROM people;

The resulting output is:

http://forum.codecal...=1&d=1251835336


Where Conditions

Using the WHERE clause you can limit the results that are returned. You might want to return all names of people who are less than 18? How about all names that start with J? All the math operators like less than, greater than, and so on you can use here.

Example:

SELECT name, age FROM people WHERE age < 18

The result is:

http://forum.codecal...=1&d=1251835336

Notice how all the ages are less than 18?

How about all names that start with J? This is where pattern matching is important.

SELECT name, age FROM people WHERE name LIKE 'J%'

The result is:

http://forum.codecal...=1&d=1251835336

Notice, how all the names start with J. That is what are where clause says.

Try this:

SELECT name, age FROM people WHERE name LIKE 'j%'

Notice, how the result is the same as above? The pattern matching does not depend on case.

ORDER BY and Sorting

When we use the ORDER BY clause we can sort our results by any field we want. Let us see how it works when we sort by age. You can also specify if you want to sort in ascending order or in descending order.

SELECT name, age FROM people ORDER BY age DESC;

Output:

http://forum.codecal...=1&d=1251835336

The code said to select all the names and ages from people and to order it by age in descending order. So the first row is the largest age and so n.

We can easily sort by ascending order:

SELECT name, age FROM people ORDER BY age ASC;

The output is:

http://forum.codecal...=1&d=1251835336

Attached Thumbnails

  • where2.JPG
  • selectAll.JPG
  • where1.JPG
  • orderByDesc.JPG
  • orderByAsc.JPG
  • limitResults.JPG

  • 2


#504813 Java: Character Class

Posted by chili5 on 01 September 2009 - 06:07 AM

Java: The Character Class

Every primitive data type has a wrapper class that provides methods for manipulating the data type. There is a lot of really useful functions in the Character class that we are going to look at.

These methods are all static methods, and thus you do not have to create an instance of the character class. Also, you do not have to import anything.

We are going to use this string below to play around with the Character class and the available methods:

String s = "Hello.There!!!3233 67yt$";

We are going to do these things:

1. Count the number of upper case letters
2. Count the number of lower case letters
3. Count the number of spaces
4. Count the number of digits

The Character class provides methods to do all of these things. To check if letters are in uppercase, we use the method isUpperCase? To count the lowercase letters, we use the method isLowerCase. To count the number of spaces, we use the method isSpaceChar.

As a matter of efficiency, you can do all these operations in one iteration of the String. However, I am going to use several iterations to emphasis the different methods.

All of these methods return true or false indicating what the current character is.

A method we are going to use a lot is the s.charAt method. This returns an individual char from the string.You can think of this as a direct-access to an item in an array.

Counting Upper Case Letters

The method we are going to use is the method Character.isUpperCase. We need a counter for the upper case letters.

int nUpper = 0;

This variable is going to count how many upper case letters there are.

for (int i=0;i<s.length();i++) {
	if (Character.isUpperCase(s.charAt(i))) {
		nUpper++;
	}
}
System.out.println("s contains " + nUpper + " upper case letters.");

The output is:

s contains 2 upper case letters.


All we have to do is iterate through the String, checking if each letter is upper case and if it is then we update the counter by 1.

Count Lower Case Letters

We need another counter to count the number of lower case letters.

int nLower = 0;

Again, a simple iteration and if structure works well here.

for (int i = 0; i < s.length(); i++) {
            if (Character.isLowerCase(s.charAt(i))) {
                nLower++;
            }
        }
System.out.println("s contains " + nLower + " lower case letters.");

Output:

s contains 10 lower case letters.


Counting Spaces

Note, that there is a method isSpace but it is a deprecated method and you shold use isSpaceChar instead. This again is just a simple iteration and counting task.

int nSpaces = 0;

for (int i=0;i<s.length();i++) {
	if (Character.isSpaceChar(s.charAt(i))) {
		nSpaces++;
	}
}
System.out.println("s contains " + nSpaces + " spaces.");

Output:

s contains 1 spaces.


Counting Digits

int nDigit = 0;

for (int i=0;i<s.length();i++) {
	if (Character.isDigit(s.charAt(i))) {
		nDigit++;
	}
}
System.out.println("s contains " + nDigit + " numbers.");

Output:

s contains 6 numbers.


This is just the same as above. I don't need to comment on it any. If Character.isDigit returns true then we find a digit and we increment the counter.

These methods provide a great and fast way to manipulate characters. There are lots of available methods. You just have to take a look and see what is there. This is a vary useful class.
  • 4


#504775 AS: External Style Sheets

Posted by chili5 on 01 September 2009 - 03:38 AM

External Style Sheets with Flash

It is great that we can add CSS to our movie clips as we need them, but if you want to reuse the styles? You would have to copy and paste the code where you need it.

An external CSS file allows you to store your style definitions outside of the code. This has a few benefits:

1. You can reuse the style definitions
2. You can change them without recompiling your movie.

For this tutorial, we are going to apply a style sheet to several links. First, we need to create a new text file called styles.css. Open this file in whatever editor you like to use. Whether it be Notepad, or wordpad or whatever. It doesn't matter as long as you can save as plain text.

For now, let us go back to the flash environment. We are going to use the text tool to add two links to the stage. One of them will link to Code Call. The other one will link to Question Bin. In the properties window, change the instance name of the code call text field to txtCC. Similarly, change the instance name of the QuestionBin to txtQB. Under the field to change the instance name, is a field to change the type of the text field. Make sure that it is set to Dynamic Text.

The properties for txtCC should look like this:

http://forum.codecal...=1&d=1251815776

Likewise, the properties for txtQB should look like this:

http://forum.codecal...=1&d=1251815776

The last thing we need to do in the properties window is set the link.

The properties window looks like this:

http://forum.codecal...=1&d=1251815776

What we are interested in is, the the section "Options". It is circled in the above screen shot.

In the link text box for txtCC type:

http://www.codecall.net


Now, on the stage select the question bin text box. In a similar manner to the above type this:

http://www.questionbin.com


When you run the movie clip, you will notice that you can click on the links and a browser will open taking you to that web site.

This is what it looks like when you run it.

http://forum.codecal...=1&d=1251815776


Resize the text fields so they cover most of the stage. This will allow us to view the content when we use bigger font sizes.

Notice, how there is no styles on the links? This is what we are going to change next. This is where we need the file styles.css. This isn't the point of the tutorial so I will put some CSS code (it will be simple and easy to understand).

You can do so much more by using the htmlText property to set the values. However, I am just going to look at what we can do using the toolbox.

Here is some CSS to copy to styles.css:

a {
    color: #FF3366; /** A slightly red color. */
    text-decoration: none;
    font-size: 38px;
}

a:hover {
    color: #00F44D; /* A green-ish color.*/
    text-decoration: underline;
}

When the user puts the mouse over, the link the color is going to change to a green-ish color.

Loading the CSS file

Now the rest of what we need to do is in the ActionScript code.

We have to load the style sheet using a URLLoader object. Then we need to parse the CSS into a format that we can use with a style sheet object. Then all we need to do is apply the style sheet to the text fields.

First the URLloader.

var cssLoader:URLLoader = new URLLoader();

Now we can use the load method, to load in the CSS file. This requires a URL Request object.

cssLoader.load(new URLRequest("styles.css"));

That line loads all the CSS from the file styles.css.

What we want to do now is apply it to the text fields. First though, we are going to add a method that checks when the file is done loading. We don't want to apply the styles when they haven't finished being loaded yet.

The event for this is Event.COMPLETE. So we will add an event listener to cssLoader listening for this event. We will then call the callback function: loadCSS.

cssLoader.addEventListener(Event.COMPLETE,loadedCSS);

The call back function is simply:

function loadedCSS(e:Event):void {
    styles = new StyleSheet();
    
    styles.parseCSS(cssLoader.data);
    txtCC.styleSheet = styles;
    txtQB.styleSheet = styles;
}

The parseCSS method converts the loaded data into a format that we can use with the style sheet object. Now all that we have to do is apply it to the text fields. You can modify your styles without actually recompiling the movie clip.

Attached Thumbnails

  • txtQB-Properties.JPG
  • txtCC-Properties.JPG
  • properties.JPG
  • run1.JPG

  • 2


#504568 Flash: Timers Part I

Posted by chili5 on 31 August 2009 - 09:22 AM

Timers

You create a new Timer by creating a new Timer object. The constructor takes two parameters: the number of milliseconds to run and the number of events to cause.

One use of a timer is to create a clock. This Timer would run forever and would generate an event every second.

Creating a new timer

var clockTimer:Timer = new Timer(1000); // this timer generates an event every one second
var timer2:Timer = new Timer(2000,2); // this timer generates an every every 2000 seconds. It only generates 2 events before stopping.

The Date

To get the current date, we create a date object and use methods like getHours(), getMinutes, getSeconds() and other methods.

This code gets the time in the format h:mm:ss

var systemDate:Date = new Date();
var minutes:int = systemDate.getMinutes();
var hours:int = systemDate.getHours();
var seconds:int = systemDate.getSeconds();
var sSuffix:String;
var sMinutes:String;
var sSeconds:String;

if (hours > 12) {
    // time is in 24 hour time, so subtracting 12
    // puts it in 12 hour time
    hours -= 12;
    sSuffix = "P.M."; 
} else {
    sSuffix = "A.M.";
}

if (minutes < 10) {
    sMinutes = "0" + String(minutes);
} else {
    sMinutes = String(minutes);
}

if (seconds < 10) {
    sSeconds = "0" + String(seconds);
} else {
    sSeconds = String(seconds);
}

trace("The current time is " + String(hours) + ":" + sMinutes + ":" + String(sSeconds) + " " + sSuffix);

Example output:

The current time is 1:06:59 P.M.



Notice, how I subtract 12 from the hours? This is because time is given in 24 hour time. If we want to display it in 12 hour time, we subtract 12 hours and append a suffix to the end.

Now instead of tracing the command to the output, we can display the time in a label. Then all we need to do is put that code in a callback function for a timer and we will have ourselves a live clock in action script.

So, add a label to the stage and change it's name to lblTime. Feel free to change the formatting of the label to anything you want.

Creating a new timer:

var clockTimer:Timer = new Timer(1000);

The time changes every second. So we set the interval to every 1000 milli seconds. This timer generates events forever.

Now we to add an event listener so we can call a function everytime the timer generates an event.

clockTimer.addEventListener(TimerEvent.TIMER,updateTime);

The updateTime function is simply going to contain the code from above. However, instead of showing text in the output window we are going to update the label.

Here is the function:

function updateTime(e:TimerEvent):void {
    var systemDate:Date = new Date();
    var minutes:int = systemDate.getMinutes();
    var hours:int = systemDate.getHours();
    var seconds:int = systemDate.getSeconds();
    var sPrefix:String;
    var sMinutes:String;
    var sSeconds:String;
    
    if (hours > 12) {
        // time is in 24 hour time, so subtracting 12
        // puts it in 12 hour time
        hours -= 12;
        sPrefix = "P.M."; 
    } else {
        sPrefix = "A.M.";
    }
    
    if (minutes < 10) {
        sMinutes = "0" + String(minutes);
    } else {
        sMinutes = String(minutes);
    }
    
    if (seconds < 10) {
        sSeconds = "0" + String(seconds);
    } else {
        sSeconds = String(seconds);
    }
    
    lblTime.text =String(hours) + ":" + sMinutes + ":" + sSeconds + " " + sPrefix;
}

Now, all we have to do is start the timer outside of the function.

clockTimer.start();

In the next tutorial, we will look at how to stop timers. We will also look at how to create timers that don't run forever.
  • 1


#504533 File Input and Output

Posted by chili5 on 31 August 2009 - 07:17 AM

File Input and Output

When you need a way to store data even after the program has stopped running you use files. When I use databases, these are just text files. I just don't know the details of how it handles the reading and writing.

Text files are used in contests because it is makes for easy grading and testing of multiple test cases.

Reading Files

There are two main ways to read from files. The Scanner and the BufferedReader. I like using these two methods because they provide methods for reading until end of file. Thus I don't have to worry about reading past the end of file.

For these cases, you need these imports:

import java.util.*;
import java.io.*;

When you use all of these methods, you need to either catch IOException or declare main to throw IOException.

public static void main(String[] args) throws IOException {

}

The IOException is thrown when there is an error with input or output.

Scanner

This method is used as a tokenizer to read things token at a time. This method is great when you know what the format of the data is that you are going to be reading. With methods like hasNext and hasNextInt I can check what the type of the next token is. The hasNext method allows me to read until end of file. When I am at the end of the file hasNext will return false and the loop will terminate.

Declaring a Scanner

Scanner fin = new Scanner(new FileReader("file.txt"));

Looping until end of file

while (fin.hasNext()) {

}

This loop runs until you reach the end of the file. In the loop body, you can read and store the values from the file. Alternatively, you can read the values and then process the values. There is not always a need to store values.

Reading

String s = fin.next();
int x = fin.nextInt();

The fin.next method reads the next token as a String until a delimeter is found. The default delimter is a space. Alternatively, you can choose the delimeter using setDelimeter.


fin.setDelimeter("\\s");

There is a read method for pretty much any data type you can think of. The nextLine method reads an entire line.

When you are done, don't forget to close the Scanner.

fin.close();

BufferedReader

Alternatively, the BufferedReader always reads the entire line. Then you can split the string into an array at whatever delimeter you specify.

Declaring a Buffered Reader

BufferedReader fin = new BufferedReader(new FileInputReader("data.txt"));

Reading with this method of input is as simple as:

String sLine = fin.readLine();

To process individual tokens, you can either use a StringTokenizer or split it into an array.

String[]  arsWords = sLine.split(" ");

Writing Files

Writing to the file is as simple as using a PrintWriter. Then calling the print or println functions.

Example:

PrintWriter fout = new PrintWriter(new FileWriter("OUT.txt"));
Scanner fin = new Scanner(new FileReader("IN.txt"));
String sLine;

while (fin.hasNext()) {
	sLine = fin.next();
	
	fout.println(sLine.toUpperCase());
}
fout.close();
fin.close();

Always make sure, you close your input and output streams. This is just a functional introduction to input and output streams. There is a lot of details that I did not go into here.
  • 3


#504498 Flash: Sprite Animation

Posted by chili5 on 31 August 2009 - 03:48 AM

Basic Animation of Sprites

Since we can change the location of sprites by changing the x or y coordinates, animation is easy. All that we have to do is constantly change the x or y positions. To do this, we can use the ENTER_FRAME event. This event runs when we enter a frame. Once one frame ends, a new one begins and this event occurs again. Thus the method is called again. This allows for a method to animate a sprite.

First, we need to draw something to animate. Again I am going to draw a smiley because they are simple and easy to draw. :)

My image:

http://forum.codecal...=1&d=1251729870

The next thing we need to is convert it to a symbol. To do this, select the smiley on the stage. Right click and go to "convert to symbol". Make sure you change the name of the symbol, make it a movie clip and export for action script. This will place a symbol in your library.

On the stage, you have an instance of the symbol. In the properties window, you need to change the instance name.

http://forum.codecal...=1&d=1251729870

Now, we can start entering our code. Go to the timeline, and on the first layer, go to the first keyframe and press F9. This opens the window for you to start writing your action script code.

First the event listener:

stage.addEventListener(Event.ENTER_FRAME,moveSmile);

This function is called everytime, we enter a new frame. Once the frame is done, we enter a new frame and this calls the method again. Now the method simply has to change the coordinates of the image.

function moveSmile(e:Event):void {
    smile.x ++;
}

This function makes him move left to right, at a rate of 1 unit(pixel) per frame. You can see what this looks like here.

To make him move down, you just increase the y coordinate.

function moveSmile(e:Event):void {
    smile.y++;
}

Notice, that it just keeps moving forever. Eventually it will move off the stage. Even when it is moved off of the stage, it is still moving.

Diagonal Movement

This is as simple as changing both the x any coordinates.

Example:

function moveSmile(e:Event):void {
    smile.y++;
    smile.x++;
}

This is going to make him move diagonally to the bottom right.

Instead of having the sprite slide across the stage, we can actually animate it. This is something that we will look into another day. This requires creating several frames for the movie clip. Then we can use code to tell us what frame we should go to next. This we will look at on a later day. However, this animation technique uses the same concepts as we are using here.

Keyboard Movement

Similary, we can use the concepts to make something move, when the user presses a key. The first thing we have to do is add an event listener at the stage level. This will listen for a key press. We will then use a callback function to determine which key the user pressed and move accordingly.

Go back to your actions panel, and erase whatever you have there.

The event listener we need is:

stage.addEventListener(KeyboardEvent.KEY_DOWN,moveSmile);

Everytime the user presses a key, we will call the moveSmile function. However, we don't want to move our smiley everytime we press a key. Why would we move if the key pressed is A? Since this is just a demonstration I am calling it moveSmile but a better name for the function would be keyPressed. All this function should do is determine which key was pressed and call an appropriate function for that key.

I'm not going to do that though.

function moveSmile(e:KeyboardEvent):void {
    switch (e.keyCode) {
        case Keyboard.UP:
            smile.y -= 5;
            break;
        case Keyboard.DOWN:
            smile.y += 5;
            break;
        case Keyboard.LEFT:
            smile.x -= 5;
            break;
        case Keyboard.RIGHT:
            smile.x += 5;
            break;
    }
}

The switch structure is more like a generalized if structure that assesses one variable. The movement code should make sense just by reading it. By including only the keys we care about, nothing happens when the user presses any other key.

Mouse Movement

The last thing we are going to do is make him follow the mouse. There are two variables mouseX and mouseY that keep track of the location of the mouse's cursor. So we add an event listener for mouse move and in the callback function, we simply assign the mouseX and mouseY variables to the x and y variables of the smile. Easy, and it is cool. :)

stage.addEventListener(MouseEvent.MOUSE_MOVE,moveSmile);

function moveSmile(e:MouseEvent):void {
    smile.x = mouseX;
    smile.y = mouseY;
}

Once we find out how to hide the user's mouse cursor, we could easily use this technique to create our own cursors.

Attached Thumbnails

  • properties.JPG
  • smile.JPG

  • 2


#504228 Flash: Sprites and Sprite Groups

Posted by chili5 on 30 August 2009 - 11:14 AM

Sprites

Just like you can add things to the stage with addChild, you can also add things (like shapes and other things) to other containers.

In this tutorial, we are going to make a few sprites on the stage. Then we are going to add some sprites on to the other sprites. This will get us a lot closer to being able to make some nifty games with depth.

First, you want to create a new flash file called sprites.

On the timeline, go to layer 1 and open the actions window. We are going to add two sprites to the stage.

var box1:Sprite = new Sprite();
var box2:Sprite = new Sprite();

This creates 2 sprite objects that we are going to put on the stage.

stage.addChild(box1);
stage.addChild(box2);


Now we are going to draw two boxes.

box1.graphics.beginFill(0xE3FE34);
box1.graphics.drawRect(50,30,200,200);
box2.graphics.beginFill(0xE3FE34);
box2.graphics.drawRect(260,30,200,200);

This will look like this:

http://forum.codecal...=1&d=1251670405

Now what we are going to do is add a sprite onto the two rectangles. When the user moves the mouse over the sprite, the sprite will move to the other sprite. I am going to draw a smiley on the stage, and have him move around the two rectangles when the user puts the mouse on him.

Using the tools in the flash environment, draw something that you like to draw. When you draw a smiley, follow these instructions to convert it to a symbol:

1. Select your drawing using the selection tool
2. Right click, and go to convert to symbol
3. In the window that appears, you need to give the symbol an appropriate name. I called mine "smiley".
4. You need to set it to a movie clip.
5. Click the box export for action script.
6. Click okay.
7. Clear the stage.

Now, you can go back to your action panel on the first frame. We need to create an instance of the object we just created and add it to box1.

We can easily create an instance like this:

var smile:smiley = new smiley();

Now, we can add it to the box1 sprite.

box1.addChild(smile);

Here I specify that I want to add smile as a child of box1. Now, you will see why I say stage.addChild instead of addChild. Even though I don't have to say stage.addChild it makes sense if I can read it, and understand what I am adding the component/sprite to.

Let us change the position of the smile.

smile.x = 50;
smile.y = 40;

Note, that the coordinates are relative to the top left of the container. In this case, box1 not box2.

Now the event listener.

box1.addEventListener(MouseEvent.MOUSE_OVER,moveSprite);
box2.addEventListener(MouseEvent.MOUSE_OVER,moveSprite);

Notice, how the two sprites use the same callback function? This is useful because we can use the callback function to determine which sprite caused the event. Then we just move the simile sprite to that box.

The event.currentTarget property will hold a reference to the item that caused the event. We can then use this to add the smiley to the other box. A sprite can only be a child of one object, which is why it is seemingly removed from one box and added to a second one.

The final code is:

var box1:Sprite = new Sprite();
var box2:Sprite = new Sprite();
var smile:smiley = new smiley();

box1.graphics.beginFill(0xE3FE34);
box1.graphics.drawRect(50,30,200,200);

box1.x = 50;
box1.y = 50;

box2.graphics.beginFill(0xE3FE34);
box2.graphics.drawRect(80,60,200,200);

box2.x = 250;
box2.y = 20;

smile.x = 100;
smile.y = 100;

stage.addChild(box1);
stage.addChild(box2);
box1.addChild(smile);


box1.addEventListener(MouseEvent.MOUSE_OVER,moveSprite);
box2.addEventListener(MouseEvent.MOUSE_OVER,moveSprite);

function moveSprite(event:MouseEvent) {
    event.currentTarget.addChild(smile);
}

Attached Thumbnails

  • sprites.JPG

  • 2


#504178 Linked Lists

Posted by chili5 on 30 August 2009 - 07:33 AM

Linked Lists in Java

The java.util package provides a linked list class. A linked list is a structure where you have a bunch of nodes that contain pointers to the next item in the list. When you take a data structures class you use a Node class to implement this structure.

A node class might look like this:

class Node {
	int data;
	Node next;
}

Then the only way to iterate is with an 0(n) scan of the list. However, these structures provide 0(1) access to add and remove any items from any point in the list.

Adding an item is as simple as this:

Node new = new Node();
Node temp;

temp = old.next;
old.next = new;
new.next = temp;

In theory a linked list would have a pointer to the previous and first items. Meaning we wouldn't have to keep track of the position we are inserting the new item at and the node before the location of the new item. However, this tutorial is not about implementing linked structures.

You should know that the linked list is not a direct-access container.

The Java class

The nice thing about the java linked list class is it is a direct-access container. I know I just said that these structures aren't. The Java ones are.

The constructor for this class is:

public LinkedList() {
        header.next = header.previous = header;
    }

This shows that each node simply references another node. I don't quite know how it provides direct access with this structure. The reality is to provide direct-access items must reside in adjacent memory blocks. Which in these types of structures, is not always the case. The header original points to itself indicating that the list is done. You will either have a node that reference itself as the next node or a null value indicating the end of the list.

Okay I was wrong, it doesn't provide direct access. Each node is given an index but to find it the class must do an iterative scan. Thus you get an 0(n) scan to find the item. The use of a get method appears to provide direct-access but it does not.

The code is this:

private Entry<E> entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;
        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else {
            for (int i = size; i > index; i--)
                e = e.previous;
        }
        return e;
    }

Basically if the index is less than the size than we keep moving forward until we have found the item with that index. This is the return value, otherwise we move backwards until we have found the item with that index.

Creating a new Linked List

The Linked List is a generic class so it can hold any type of data you want. Note, it can only hold objects. It cannot hold primitives like you can in C++.

Example of creating a new linked list:

LinkedList<String> out = new LinkedList<String>();

Returning the first item in the list. Since the linked list maintains a reference to the first item in the list, all you have to do is call getFirst() which returns a reference to the first item in the list. This methods throws a NoSuchElementException of the list is empty.

Node start = list.getFirst();


Getting the Last Item in the List


Similary, the list contains a reference to the last node. Giving you 0(1) access to the end of the list. All you have to do is call getLast. The getFirst and getLast give you fast access to elements making this structure perfect for implementing a stack and a queue. However, there are two methods that are even better for implementing queues and stacks.

Node last = list.getLast();

That simply returns the last item (well a reference to it). It doesn't remove it from the structure, which disqualifies it for using in implementing queues and stacks.

These two methods leave the item in the structure.

Removing the last item

You simply call the removeLast method which returns the last item from the structure and removes it.

Example:

Node last = list.removeLast();


Removing the first item in the list.

Node start = list.removeFirst();

This method, removes the first item from the list. It also returns a reference to the item.

Since these methods remove the first and last items. It makes them perfect for using in implementing stacks and vectors. Which brings up the question, why did the Java developers use a vector? You can get 0(1) access for adding items to the front and the end, and removing items from the front and the end. So you don't need access to items in the middle, so why even use a vector?

addFirst and addLast methods

Since we have a reference to the first and last items, it is quick and fast to add items to the last item. These methods are called addFirst and addLast respectively.

To add a new item to the list, I do this:

Node newNode = new Node();
list.addFirst(newNode);

This method assumes, that I have a list that is holding Node objects.

Similarly, to add an item at the end of the list I simply write:

Node newNode = new Node();
list.addLast(newNode);


Number of elements

The class maintains a counter of how many items are in the list. So to find out how many items are in the list, you simply call list.size().

Example:

System.out.println(list.size());


Removing items

To remove an item, you simply pass the item you want to remove to the remove method. The method then looks for the item and removes it once it finds it. It will return true if it found the item, and removed it. Otherwise, it will return false. The method has to find it because there is no direct-access.

if (list.remove(5)) {
	System.out.println("Five was removed.");
} else {
	System.out.println("Not found.");
}

Get method

You can access items using an index and get the get method. This method searches for the item with that index. The indices are assigned in the order that you added the items. Alternatively, you can specify an index to use.

Add Method

You can use the add method to add items to the structure. You can either pass in the index you want to use, along with the element or just pass the element you want to add.

Examples:

list.add(5); // chooses it's own index
list.add(3,2); 

There are other methods, push, pop and others that let you treat this like a stack and queue. It also contains methods contains, indexOf and others.

Final thoughts?

At several parts of this tutorial, I have said things and then immediately said something that contradicts what I just said. Why? As I was writing this I was learning about the structure of these structures by reading the code by the java developers. I learn a lot about different structures this way. Instead of removing the false information, I decided to make a node about the learning process and show how I've learned lots by looking at the implementation of the linked list.

For instance, I saw a get method so I assumed direct-access with some incredible trick but looking at the method proved my assumption false. Nothing wrong with making assumptions, and finding out that you were wrong. Not very many people probably learn about a structure by looking at the JDK source code. :)

I like this structure best. It is great when you don't require direct-access. You can even use it for cases where direct-access would be nice, if you need fast insertion and deletion.
  • 1


#504043 Flash: Creating Buttons

Posted by chili5 on 30 August 2009 - 04:06 AM

Flash: Creating Buttons

I know that the button included with Flash works well. It has a simple interface. What if you want a button with a cooler interface?

This is what we are going to do, make a button that has a better interface.

Go to the insert menu, and click new symbol. You will see a form like the image below.

http://forum.codecal...=1&d=1251644669

We need to do a few things, rename the symbol, change the type of symbol and export for ActionScript.

In the name text field, change the name to "new button". This isn't a very descriptive name but we are just demonstrating how to create new buttons. In the combo box, below the text field name change that to say Button.

The last thing you need to do is check the checkbox that says "export for ActionScript". This will let us program the button in ActionScript code.

Your form should now look this:

http://forum.codecal...=1&d=1251644669

Notice, that the class name doesn't have any spaces? It can't have any spaces for use in the ActionScript code.

Now you can click okay.

The flash environment will now look like this:

http://forum.codecal...=1&d=1251644669

This is where you are going to design your button. Notice, that the timeline has changed. There are four frames:

  • Up
  • Over
  • Down
  • Hit

Each of these frames is one state of the button. The up frame runs when the mouse is not on the frame. This for the most time, will do very little (if anything). The over frame runs when the mouse is moved over the button. You might want to change the color of the button when the user puts the mouse over. The down frame runs when the user presses the mouse on the button and holds the mouse down.

The hit frame runs when the user clicks the button.

We aren't going to use the hit frame in this tutorial.

Drawing the Up Frame

We are going to make a button in the shape of an oval. So using the oval tool, draw a circle on the stage.

The stage should look like this:

http://forum.codecal...=1&d=1251644669

Notice, on the picture how there is a crosshair? The cross hair should be relatively close to the center of your image. Now, let us add some text to the button using the text tool. We want to make it a dynamic text field also. Change the instance name of the dynamic text field to "theText". This will eventually allow us to change the text on the button.

Drawing the Over Frame

In the time line for the button, click on the over frame. This is the frame that will run when we put the mouse over the button. What we need to do is insert a new keyframe on this frame. Right click on the frame, and go to "Insert Keyframe". Now on this frame, we are going to change the background color of the frame.

In the toolbox, look for the bucket tool. Click on the rectangle below the bucket. Now you can find a color that you like. Consider changing the text color also. :) Have fun with this, you can do anything that you want. I'm even going to change the size of the button and the size of the text.


This is what my over state looks like:

http://forum.codecal...=1&d=1251644669


Drawing the Down Frame

We now need to add a keyframe on the down frame in the timeline. This is the frame that runs when the user presses down on the button and holds the mouse down.

When this happens, I am going to make the button move. I'm also going to change the button back to the state it was in when the mouse wasn't over it. I just copied the keyframe from the up frame and pasted it on the down frame.

You can do this by right clicking on a frame, and going to copy frames. Then on the down frame, right click and press paste frames. Move it slightly but the crosshair still has to be on the image.

Using ActionScript

Since, we checked export for ActionScript we can use code to create instances of are button and do all sorts of things. We can even program events on our own button.

Back on the main timeline, open the actions window for frame 1.

var btnOne:newbutton = new newbutton();

This code creates an instance of the button that we just created.

btnOne.x = 50;
btnOne.y = 100;

stage.addChild(btnOne);

This code sets the location of our button and adds it to the stage.

btnOne.addEventListener(MouseEvent.CLICK,yo);

function yo(e:MouseEvent):void {
    trace("Yo! You clicked me!");
}

The addEventListener sets up a callback function yo that is called everytime the button is clicked.

Next steps?

First, hope this is a useful start for creating your own buttons. There are still a few things that I have to figure out. Just remember that this is an extension of SimpleButton so anything you can do with SimpleButton you can do with your button as well. This includes using ActionScript code. This is just an intro, you can do more with them.

I have to find out how to do things with my button at runtime. Things like changing the text, and changing color. Though I think it would be simple.

When I do this:

btnOne.theText.text = "HAI!";

I get this message:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at button_fla::MainTimeline/frame1()

So obviously, I am doing something wrong since I am getting a null reference. I will assess this issue for the next tutorial.

Attached Thumbnails

  • up.JPG
  • newbutton.JPG
  • over.JPG
  • new symbol.JPG
  • flash.JPG

  • 2


#503925 Flash Variables and Operators

Posted by chili5 on 29 August 2009 - 04:12 PM

Flash Variables and Operators

This is a simple concept but it is really important. Programming without variables and operators is useless.

Declaring Variables

Before we look at operators, we are going to look at how to declare variables. We use the var statement to declare variables. We have to provide the variable a name, and follow the variable name with a data type.

Example:

var sName:String = "";

After the var line you provide the name followed be a semi-colon. After the semi-colon you specify the data type. Optionally, you can specify a default value for the variable. In the above line I create a String variable called sName and it is defaulted to an empty string.

Some other data types include:

int - An integer variable. You can use them to perform math but they can not contain a decimal value. Ex. 5, 3, 2, 4. Not an int: 5.5
Number - The floating point variable. Ex. 5.5, 3.5, 4.2
boolean - A true or false value.

Creating instance of objects is a little different. You must call the constructor to initalize an object. A constructor is a special function in a class that is used to set up an object.

Example:

var txtInput:TextField = new TextField();

The constructor is called when you see a new keyword. We will look into objects later.

Operators

The addition operator simply adds two items together.

Ex:

trace(String(5 + 3));

The output is going to be 8.

Subtraction

The subtraction operator simply subtracts two values.

Ex:

trace(String(5 - 3));

Multiplication

The multiplication operator simply multiples two values.

trace(String(5 * 3));

Division

The division operator allows you to divide two values. If you divide two integers any floating point value will be truncated. This makes division great for us in accessing items in arrays.

5  / 2

What is the result? 2.5? Wrong. It is 2. Since 5 and 2 are integers, this is integer division and there is no decimal value. If this was 5.0 / 2.0 the result would be 2.5. Since there is a decimal value.


Equality

To test equality of variables, we use the == operator. The = operator is the assignment operator. If you do this:

if (test = 5) {
	trace("test = 5.");
} else {
	trace("test != 5.");
}

You will always get test = 5 because the assignment operation will always return true.

The way to test this is as follows:

if (test == 5) {
	trace("test = 5.");
} else {
	trace("test != 5.");
}

This tests the equality of the test variable. Assuming that test is an integer variable.

Inequality

The inequality operator is !=.

Example:

if (test != 5) {
	trace("test != 5.");
} else {
	trace("test = 5.");
}

Greater than and less than operators

These test if an operand is greater than or less than some other operand. One use of these is in sorting an array.

Ex.

if (test < 5) {
	trace("test < 5");
} else if (test > 5) {
	trace("test > 5");
} else {
	trace("Test must be equal to 5.");
}

Similary, we have greater than or equal to operators (>=) and less than or equal to operators (<=).

Modulus operator

The modulus operator returns the remainder of a division. If you divide 5 by 2, this is integer division and the result is 2. However, there is 1 remaining.

This operator allows you to test the divisiblity of a number. This might be useful in determine if a number is prime or not. :)

Example:

if (n % 2 == 0) {
	return true;
} else {
	return false;
}

If when you divide by 2, there is no remainder the number is even. Otherwise, the number is not even.

This tutorial is simple, but the concepts of variables and operators is really important.
  • 2


#503917 ActionScript: Drawing with the Toolbox

Posted by chili5 on 29 August 2009 - 01:41 PM

Using the Drawing Tools

The tool box contains a lot of tools that you can use to create pretty much anything that you will ever need.

The tool box looks like this:

http://forum.codecal...=1&d=1251592733

In this tutorial, we are going to look at these tools:

1. The line tool
2. The rectangle tool (and other shape tools)
3. The pencil tool

The Line tool

This tool is used to draw lines. In the tool box, click on the line tool. Now click somewhere on the stage and then drag the mouse. After awhile let go of the mouse and you will have drawn a line. As you move the mouse around you can see how the line is going to look. When you let go a line is drawn on the stage.

Example:
http://forum.codecal...=1&d=1251592733

Your line may have a different color depending on what stroke color you currently have selected. A line without a stroke color you cannot see.

The Rectangle Tool

This tool is located immediately below the line tool. Notice, the little black arrow in the corner? You can use this to change the type of shape you want to draw. For now, we are going to draw rectangles. So set the tool to the Rectangle tool. Again, just click somewhere on the mouse and move the mouse around to size the rectangle until you have it sized and positioned like you want. Then you can release the mouse to draw the rectangle.

Example:

http://forum.codecal...=1&d=1251592733

The color beside the fill color is the fill color of the rectangle. By clicking on the fill color in the tool box, you can change the fill color. Similarly, the stroke color is the color of the border.

You can change this tool to draw ovals and other shapes including ovals and polygons. I'm not going to go into the different tools because they are a lot a like.

The Pencil Tool

This tool is located right below the draw shapes tools that we just looked at. You can use this tool to draw whatever you want to draw. The color of the stuff you draw is whatever you have the stroke color set to. If you press down shift, you can draw straight lines. Otherwise, you get lines that are drawn exactly as you draw them.

I'm not very good at using this tool but I will give you an example of drawing a simple dog house. :)

http://forum.codecal...=1&d=1251592733

I drew that using the pencil and text tool. I apologize for the terrible drawing but I am NAFGA. :) Others might have the eye for graphical drawing but I do not. :)

Attached Thumbnails

  • toolbox.JPG
  • pencil drawing.JPG
  • rect.JPG
  • line.JPG

  • 1




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download