Wednesday, December 5, 2012

When relative paths go bad

Problem:
Relative urls on your website are suddenly using the wrong domain.

Cause:
It’s XSS (sort of).
<base> element will change the target of all relative urls on the page.
<base> is supposed to be in <head>, but Chrome (and possibly other browsers) will respect it when in <body>.

Solution:
Add <base> to the blacklisted elements on all of your user inputs.
Check existing user content. 
Use absolute urls.

Monday, November 19, 2012

BlogPost blogPost = BlogPostFactory.MakeBlogPost(NewBlogPostOptions.BlogPostWithAbsurdTitle)

Don't leak useless implementation details in your variable, method, or class names. Just don't.

Sure, the name may be accurate and true, but so what? I don't need to see the class name 5 times in one line - that just clutters up the place. It also makes it harder to see similarities in code and opportunities for refactoring. These kinds of names also go against the entire point of polymorphism: you don't need to know the type, just it's capabilities. Hungarian notation obviously falls into this category of cluttering up the place with implementation details. I rarely need to know the exact type or inner working of something. What I need to know is the intent.

There is one place where a name should leak implementation details though: choosing a strategy. Not just the Strategy Pattern, but even between different methods that all do the same thing but in a different way. I'm thinking of things like depthFirst vs breadthFirst, MaximizeBenefitStrategy vs MinimizeCostStrategy vs MinimizeRiskStrategy, or calculateLevenshteinDistance vs calculateJaroWinklerDistance. These seem like good implementation leaking names to me since when I choose one, I need to choose the exact details. Of course they could be wrapped in intention revealing names which would be used most of the time:

public double PercentSimilarTo(this string myself, string other)
{
var longest = (double)Math.Max(myself.Length, other.Length);
return EditDistanceCalculations.CalculateLevenshteinDistance(myself, other) / longest;
}


Try it for a few weeks and see what happens. I think that replacing implementation revealing names with intention revealing names is one of the easiest ways to improve code.

var p = new Bp()

Don't use abbreviations in your variable, method, or class names. Just don't.

Sure, you save 2 or 3 seconds, and a few characters on the screen, but so what? You, or whoever is looking through your code, loose even more time when you have to look around to find out that cs is an array of Customers. Then you have to spend time trying to figure out why you have this array. Are they delinquent customers? New customers? Customers who have a birthday today? What's the intent of this thing? This is especially bad with primitives or collections of primitives because they have even less inherent meaning. It's also bad when the same variable is used for multiple things. If cs is an array of customer indexes on one line, an array of page numbers on another, and x, y, and z coordinates for an airplane on another line then you can't give it a good name and it should be split into three separate variables: customerIndexes, pageNumbers, and airplaneCoordinate.

Worst names:
cs
arr
sb
awos

Bad names:
custs
array
stringBuilder
accounts

Good names:
birthdaysToday
selectedIndexes
warningMessage
accountsWithoutOwners


A name is more than just a unique identifier: it's a way to express intent and meaning. The compiler doesn't care what you use - it's just as fine with zhqxv as it is with unwantedLocationNames - but I know which one I'd prefer.

I can only think of one reason to have a one character or abbreviated name: if it's a well known and commonly accepted part of that domain. Gui and hud may be acceptable names within a user interface domain and x and y sound acceptable when talking about cartesian coordinates. If you look at it a certain way, i and j could be considered valid names within the "looping through a collection with an index" domain, but even then, there's probably a better name.

Try it for a few weeks and see what happens. I think that replacing abbreviations with real, intention revealing names is one of the easiest ways to improve code.

Wednesday, October 31, 2012

What's next?

When planning ahead or deciding what to do next, how do you choose?

Work stack
By work stack I mean that when you think of something new, start working on it; when you're done, go back to what you were working on. If you've ever worked with someone who bursts into the room and shouts with joy, "I just got a great idea! Drop everything and work on this now!" then you'll be familiar with the result: you end up going nowhere. These constant interruptions are highly disruptive and cause unfocused thrashing and churning. The product owner doesn't get what they want because their next idea interrupts any progress on the current idea and they don't get what they need because the focus is always on something else. Most of the time is wasted on incomplete, buggy, useless features. I have nothing positive to say about doing things this way because in my experience, it's by far the most wasteful. This is like trying to swim across a river by jumping in and moving your arms and legs in every direction as fast as you can: you might make it across but you'll probably just suffer and die.

There's also a more subtle and personal work stack too. This is where you see something near what you're working on and you decide to take a short detour to fix it or clean it up. If you're especially prone to this then you can end up wandering from one little detour to another and not accomplishing what you set out to do. I've found that I've gotten much better at avoiding this by focusing on finishing one feature before starting on another and setting aside time specifically to refactor and payoff technical debt.

Work queue
A work queue is the opposite: new ideas are added to the end of the list and you'll get to it after you finish everything before it. This sounds a lot like Big Design Up Front and suffers the main drawback too: solutions you come up with probably will be bad since you know the least at the beginning of the project. If you have a long list then when you learn something new, it will be a long time until you can benefit from it. I think human nature and our eagerness to implement new ideas makes it just about impossible to stick to this method - which is for the best.

Horizontal slice: Front end first
You could try the tiered architecture approach and do the outside first. This gives early visible progress but there's a lack of functional progress. Unfortunately, non technical people often don't see the difference between "gui is done" and "app is done". Having such a large disconnect between the customer and team is a recipe for disaster.

Horizontal slice: Back end first
You could try the tiered architecture approach and do the outside first. This gives early functional progress but there's a lack of visible progress. Very few users understand the difference between "non existent app" and "98% of the use cases have passing automated tests". If the person paying your bills doesn't think they're getting anything for their money then it doesn't matter how close you are to really being done because you won't get a chance to finish.

Minimum cost
How about doing the smallest and easiest things first? This has a lot of good things going for it: you make quick and early progress, you're always doing the easiest work available, and you'll probably spend most of your time on things you enjoy and are good at. But as you go you'll find that everything becomes more difficult and risky since you've been putting it off. You may not have a usable product for a long time and what you do have will probably be missing important functionality. Or you can spend a lot of time and only too late discover that the hard parts will be too expensive and the whole thing was a waste of time. Unfortunately for those who prefer the easy way, the hard parts are often what solve the real problem and make software worth it.

Maximum cost
How about doing the most difficult or risky things first? This also has a lot of good things going for it: solving hard problems (or even working on them) can boost morale, you reduce risk over time, the pieces you work on will become easier over time, and if it's too difficult, risky, or expensive you cut your losses before making a huge investment. But there are downsides. Just like when working the minimum cost first, you may not have a usable product for a long time and what you do have will probably be missing important functionality. You'll also be making a lot of long term solutions to hard problems that may be bad since you know the least at the beginning of the project. And possibly the biggest drawback is that difficult problems require skilled teams with skilled people who work well together, which you may not have at the beginning.

Important and urgent first
It seems like thinking about things first works best so far. Hopefully that's not too surprising. Maybe we should try using two variables to categorize things instead of putting things on a high-to-low, inside-to-outside, or newest-to-oldest spectrum? You could use an importance and urgency matrix with 4 quadrants: high importance and high urgency, high importance and low urgency, low importance and high urgency, and low importance and low urgency. Everything that needs to be done is placed in one of those quadrants and you come up with some rules about working the important before the non-important and the urgent before the non-urgent. Sounds good in theory but from what I've seen, it really devolves into two categories: "get to it when we can" and "ignore". Eventually someone will say "this is very high importance!" and someone else will say their task is "critical importance" and another becomes "ultra critical importance" and before you know it, you get importance inflation where the only way to get something worked on is to say we're all going to die unless it gets done by tomorrow. Unfortunately, the difference between Important and Urgent (and sometimes even Nice To Have, or Just Putting Words Together With No Clear Thoughts) seems impossible for some people to understand.

Maximum value
Take your to do list, order it by how much value you'll get from each thing, and call it a backlog. By focusing on the most valuable things first you'll get usable software sooner and as we know, "working software is the primary measure of progress." One of the best things about the list as a developer is that the opportunity cost is clear and can't really be argued. Lets say someone tells me that a certain issue needs to be handled asap. Since two things can't be at the top of the list at the same time, I can ask them what items I should move down the list to make room for it. Should I delay the bugfix that's costing us thousands of dollars a day? How about the feature that the CIO himself asks be about each morning and evening? Or maybe the feature that will prevent our largest client from leaving in a month? Suddenly their request isn't as important as they thought is was. The biggest downsides are that deciding the relative value of things takes discipline and knowledge and that some clients have an all or nothing mentality. The idea that even the tiniest feature might be left out or is less valuable is unacceptable to them.


I've found that I'm most productive and happy when I change it up to maintain flow. I'm almost always trying to focus on maximum value but sometimes visible progress, easy wins, or tackling tough problems soon is important. After all, working software is the primary measure of progress but not the only.

Saturday, October 20, 2012

October 2012 challenge, Day 20

Well, I failed.

I got the core mechanics and everything done in just a couple days but I only had a few hours a week to work on music, sounds, graphics, and extra content. That just didn't happen. So, as tough as it is for me, I've admitted that I should cut my losses and stop worrying about it.

Retrospective time!

I should start learning the language, tool chain, graphics, music, and sound before committing to a project. I hadn't used haxe before (but I'm somewhat familiar with Actionscript) so the language, libraries, and compilation process and quirks took some time to get. Despite 6 or so years of piano lessons, I don't know anything about making good computer music either. Pixel graphics wouldn't fit the theme and good looking graphics are beyond what I can do. I had some good luck with procedurally generated plant graphics, but couldn't quite integrate it with my game code due to how the rendering code worked.

I should stop planning on spending all of my time working on a project with so many unknowns . I have less time than I expected and it's not sustainable. After a week of nothing but work, sleep, and this project, my place was a mess and it was hard to stay focused. If I picked a smaller project - like a platformer or turn based strategy - then I think I would have had a better chance of finishing. I can do old-school graphics and sound effects so that's what I should stick to.

I should continue writing well factored code and trying short term projects like this. Breaking it down into pieces that I could prioritize and implement in a couple hours helped me get started and make early progress. The simple and clean code meant that I could change my mind, try something different, and generally make progress much faster than some of the messier code bases I've crapped out.

If I follow these simple plans, then I'll be much better equipped for the next ludum dare.

Wednesday, October 10, 2012

October 2012 challenge, Day 10

I only had a few hours to program over the weekend but I managed to get saving and continuing to work - which took much longer than I expected. If you're looking for advice on how to save objects to the SharedObject with Flash or haxe and nme, I ended up relying on the Memento Pattern.

Here's the relevant part of the Fruit class:

public function toMemento():Dynamic
{
return {
x:x,
y:y,
vx:velocity.x,
vy:velocity.y,
maxSpeed: maxSpeed,
maxAge: maxAge,
type: type,
plantType: plantType,
age: age,
};
}

public static function fromMemento(o:Dynamic):Fruit
{
var c = new Fruit(o.x, o.y, o.type);
c.velocity.x = o.vx;
c.velocity.y = o.vy;
c.maxSpeed = o.maxSpeed;
c.maxAge = o.maxAge;
c.age = o.age;
c.plantType = o.plantType;
return c;
}

One place where this was tricky was with the creatures' needs. Each creature has a list of needs that implement the Need interface. Since I don't know the real class at design time, it has to be handled differently. When creating the memento for needs, the class name is included and when converting the memento to the real object, a separate class takes the memento, looks at the need field, and has a switch statement that tells the appropriate class to create an instance from the memento. Here's the relevant part of the NeedToEatFruit class:

public function toMemento():Dynamic
{
return {
need: "NeedToEatFruit",
target: target == null ? null : target.toMemento(),
}
}

public static function fromMemento(o:Dynamic):Need
{
var n = new NeedToEatFruit();
n.target = o.target == null ? null : Fruit.fromMemento(o.target);
return n;
}

Apart from that, I made some simple placeholder graphics for the plants and got the basic plant lifecycle to work. There's twelve species of plants. Some float to the surface, some are buoyant enough to float around, and others are planted in place. The simple ones are just a sprite but the more complex ones grow separate leaves. They can reproduce by budding, spores, seeds, or fruit. When a fruit-eating animal eats a fruit, it will wait 5 seconds or so then drop a seed of that plant. And that's why the Creature class has a pooCountdown field.
Next up is animal graphics, lifecycle, and more needs as well as changing the world structure. It's currently Perlin noise but when targeting the mac, it runs out of memory trying to make it. Really odd.

Friday, October 5, 2012

October 2012 challenge, Day 5

If you look at it a certain way, then I'm almost done. If you look at it the real way, then all that's left is the stuff I'm not good at.

After some late night work, pre-work work, and lunchtime work, I've got the core ideas working so now it's mostly a matter of adding content (graphics, sound, music, more game objects, etc) and fine tuning it. I'm sure there will be a round of performance optimizations, a round of cross-platform hacks, a round of feedback from beta testers, a round of panicked hacking, and a round of October 30th surprises. But not today. Today is good.

I don't want to give away too much of what the game is about (October is only 17% done after all) but here's the AI for other creatures:

package;

class CreatureController
{
public function new()
{

}

public function update(creature:Creature):Void
{
var lowestScore = 1.0;
var lowestNeed = creature.needs[0];

for (i in 0 ... creature.needs.length)
{
if (creature.needScores[i] > lowestScore)
continue;

lowestScore = creature.needScores[i];
lowestNeed = creature.needs[i];
}

lowestNeed.update(creature);
}
}

And here's a screenshot:

It's hard to see but there's two different background colors. The large squares are plants, the medium squares are animals, and the tiny squares are fruits. The green bar is your happiness. Later the squares will be things that look like what they are.

Thursday, October 4, 2012

October Ludum Dare challenge accepted

"Make a game — Take it to Market — Earn $1"

I'm in. I just got haxe setup on my computer and I'm ready to start working on an idea I've had for some time.

Things I still need to do:

  1. Make the game.
  2. Make it not suck.
  3. Make it look good.
  4. Make it sound good.
  5. Make an attractive website for it.
  6. Make sure it works on iPhone, iPad, and Android.
  7. Submit to the Apple App Store.
  8. Submit to the Android Market.
  9. Submit to some flash game site.
That's only nine things. I can do nine things in one month.

Thursday, August 30, 2012

Objectives that don't suck

It seems that most résumés have a generic objective copied from one of many "how to write a résumé" articles. You know the kind; "To utilize and expand my skills in blah blah blah". I think that's lame. Why start your résumé with some vague cookie-cutter bullshit that you copy-and-paste then forget about? My objective is "To work on a project that users want to use and maintainers want to maintain.". It's nothing fancy but it's honest and to the point and I actually believe it. I'm glad when something I create is useful to others and they want to use it. I'm glad when someone, usually myself or a coworker, is able to extend or change it to do something else.

But not everyone wants those things. Recent experiences with clients who are more concerned with making sure the software looks like it works rather than actually works reminded me that working software is the primary measure of progress. Because of that, I updated my objective to say "To create working software that users want to use and maintainers want to maintain." Even more true and even more to the point. And that's something I care about.

What's your resume objective? Do you actually believe it and try to live up to it?

Tuesday, August 28, 2012

Giáo trình Flash CS5 CS6 - Script và kĩ thuật hoat hình - Đặng Ngọc Hoàng Thành (version 2)



Thể loại: sách/giáo trình-PDF
Phiên bản: Flash CS5 (Cập nhật thêm CS6)
Tác giả: Ths. Đặng Ngọc Hoàng Thành.
Số trang: 330 trang.
CD đính kèm. 
Cập nhật: 28/8/2012
-------------------------------------------------
Flash là một kĩ thuật tạo các hiệu ứng động, các thước phim hoạt hình… Flash được giới thiệu đầu tiên bởi công ty MacroMedia vào năm 1999. Đến năm 2005, công ty này đã được Adobe mua lại với giá 3.4 tỉ đôla. Từ khi ra đời cho đến này, Flash đã có rất nhiều bước phát triển đáng chú ý. Nhiều tính năng mới đã liên tục được cập nhập trong các phiên bản của nó. Từ các phiên bản Macromedia Flash cho đến Adobe Flash hiện nay.
Với phiên bản Adobe Flash CS4, công ty Adobe đã bổ sung vào cho Flash những tính năng mạnh mẽ: hỗ trợ nhiều định dạng import dữ liệu; bổ sung các công cụ tạo hoạt hình mạnh mẽ như Bone, Bind, 3D Translation, 3D Rotation,…
Phiên bản mới nhất của Flash là CS5 (cho đến năm 2010). Hiện nay, Adobe cũng đã tạo ra một ấn bản mã nguồn mở cho Flash đó là công nghệ Flex. Một trong những công nghệ ra đời sớm nhất hỗ trợ tạo giao diện web – RIA. Flex là một công nghệ hứa hẹn đem lại nhiều lợi nhuận cho Adobe (nhờ vào trình phát triển Adobe Flex Buider). Nó là một đối thủ đáng gờm với Silverlight của Microsoft và JavaFx của Sun (nay được mua lại bởi Oracle).
Nội dung


PHỤ LỤC


LỜI NÓI ĐẦU ................................................................................3
CHƯƠNG 1. GIỚI THIỆU VỀ FLASH .......................................10
1.1. Sơ lược về đồ họa vector và lịch sử ra đời của Flash ...............10
1.2. So sánh Flash với Silverlight và JavaFx ...............................13
1.3. Cài đặt  Adobe Flash CS5 .......................................................14
1.4. Giới thiệu về Adobe Flash CS5 ...............................................17
1.4.1. Các chế độ tùy biến giao diện .......................................19
1.4.2. Tạo mới dự án cho desktop và mobile ...............................20
1.4.3. Layer, Frame, Scene và Movie .......................................22
1.4.4. Vùng thanh công cụ Tools ...............................................25
1.4.5. Vùng thuộc tính Properties ...............................................25
1.4.6. Vùng soạn thảo ActionScript .......................................26
1.4.7. Các vùng chức năng khác ...............................................28
Tổng kết chương 1 .......................................................................35
CHƯƠNG 2. CÁC CÔNG CỤ VẼ CƠ BẢN ...............................37
2.1. Các công cụ Pencil, Brush và Erase .......................................37
2.2. Công cụ vẽ hình cơ bản .......................................................39
2.3. Công cụ Text .......................................................................48
2.4. Công cụ chọn Selection và Lasso...............................................50
2.5. Các công cụ đổ màu Paint Bucket, Ink Bottle và bắt màu EyeDropper...51
2.6. Công cụ Free Transform và Gradient Transform.........................53
2.7. Các công cụ làm việc với đường Bezier......................................56
2.8. Làm việc với các đối tượng .......................................................59
Tổng kết chương 2 .......................................................................62
CHƯƠNG 3. CÁC BIỂU TƯỢNG TRONG FLASH .......................64
3.1. Biểu tượng Graphic ...............................................................64
3.2. Biểu tượng Button ...............................................................66
3.3. Biểu tượng MovieClip .......................................................68
3.4. Làm việc với Library ...............................................................69
Tổng kết chương 3 .......................................................................70
CHƯƠNG 4. TẠO HOẠT CẢNH ...............................................72
4.1. Tìm hiểu về TimeLine .......................................................72
4.2. Classic Tween .......................................................................79
4.3. Shape Tween .......................................................................81
4.4. Motion Tween .......................................................................83
4.5. Công cụ Bone và Bind .......................................................88
4.6. Công cụ Deco .......................................................................92
4.7. Công cụ 3D Translation và 3D Rotation .............................104
Tổng kết chương 4 .....................................................................107
CHƯƠNG 5. LẬP TRÌNH VỚI ACTIONSCRIPT .....................109
5.1. Các kiểu dữ liệu .....................................................................111
5.2. Biến và Hằng .....................................................................112
5.3. Toán tử và Biểu thức .............................................................113
5.4. Các cấu trúc lệnh điều khiển .............................................121
5.4.1. Câu lệnh if .....................................................................121
5.4.2. Câu lệnh switch .............................................................122
5.4.3. Các câu lệnh lặp for, while và do…while .....................123
5.4.4. Các lệnh continue, break và return .............................126
5.5. Hàm .....................................................................................127
5.6. Lớp và Đối tượng .............................................................130
5.6.1. Xây dựng lớp .............................................................130
5.6.2. Làm việc với đối tượng .............................................134
5.6.3. Sự kiện chuột .............................................................137
5.6.4. Sự kiện bàn phím .....................................................138
5.7. Đưa một đối tượng vào ActionScript .....................................139
5.8. Làm việc với XML .............................................................141
5.9. Vùng chức năng Code Snippets .............................................143
Tổng kết chương 5 .....................................................................170
CHƯƠNG 6.  CÁC HIỆU CHỈNH NÂNG CAO .............................172
6.1. Xử lý âm thanh, hình ảnh và video .....................................172
6.2. Tạo kĩ xảo điện ảnh với Flash .............................................177
6.3. Tạo thước phim Flash tựa 3D .............................................181
6.4. Ghép nối nhiều hoạt cảnh .....................................................188
6.5. Kĩ thuật mặt nạ mask .............................................................188
6.6. Tạo các nút nhấn điều khiển .............................................196
6.7. Xuất bản một Movie .............................................................198
6.8. Xuất bản một tập tin Flash trong suốt trên trình duyệt .............202
6.9. Tương tác giữa ActionScript 3.0 và JavaScript .......................202
Tổng kết chương 6 .....................................................................207
CHƯƠNG 7.  THƯ VIỆN PAPERVISION3D .............................209
7.1. Giới thiệu về PaperVision3D và Adobe Flex Builder .............209
7.2. Cấu hình và cài đặt PaperVision3D cho Adobe Flex Buider .....213
7.3. Chương trình Hello, PaperVision3D ! .....................................216
7.4. Các đối tượng trong PaperVision3D .....................................220
7.4.1. Các đối tượng hình thể .....................................................220
7.4.2. Đối tượng Material - Phối màu cho hình thể .....................228
7.4.3. Đối tượng Lights - Hiệu ứng ánh sáng .....................................232
7.4.4. Đối tượng Shader - Hiệu ứng đổ bóng .............................233
7.4.5. Đối tượng ShadedMaterial .....................................................233
7.4.6. Đối tượng CompositeMaterial .............................................233
7.4.7. Đối tượng MaterialsList .....................................................234
7.5. Import một mô hình 3D .....................................................234
Tổng kết chương 7 .....................................................................236
BÀI TẬP THỰC HÀNH .............................................................238
BÀI THỰC HÀNH SỐ 1 .............................................................238
BÀI THỰC HÀNH SỐ 2 .............................................................239
BÀI THỰC HÀNH SỐ 3 .............................................................240
BÀI THỰC HÀNH SỐ 4 .............................................................240
BÀI THỰC HÀNH SỐ 5 .............................................................242
BÀI THỰC HÀNH SỐ 6 .............................................................243
TÀI LIỆU THAM KHẢO THÊM .............................................246
----
Đặc biệt, trong phiên bản mới:
- Bổ sung thêm nhiều ví dụ minh họa.
- Hướng dẫn cách lập trình game và các ứng trên AIR dùng cho Android smartphone, Android Tablet, Iphone, Ipad...
- Hướng dẫn lập trình trên AS3 chi tiết và đầy đủ hơn.

Download 
(Bạn hãy để lại một lời comment giúp tôi điều chỉnh giáo trình hoàn thiện hơn)
+ Tải sách PDF (15 MB).
+ Tải CD ((677MB, bao gồm dự án mẫu, file tài nguyên...) 
-------- Phần 1 
-------- Phần 2 
-------- Phần 3 
-------- Phần 4 
+ Link CD phụ: http://sdrv.ms/U6csbq
+ Tài nguyên bổ sung (một số bài hướng dẫn nâng cao theo giáo trình): http://sdrv.ms/SI0C8m




Hiệu ứng Plasma

Bước 1. Tạo một khối cầu hình tròn có màu bất kì. Convert nó sang movieClip. Nhấp đôi chuột vào movieClip này (hoặc chọn Edit từ menu chuột phải của đối tượng trong Library). Sử dụng Motion Tween để tạo sự biến đổi cho đối tượng: biến đổi về độ blur của Filter, biến đổi về kích thước và biến đổi độ alpha. Ở cuối của Motion này cần phải bổ sung lệnh stop để không cho movieClip lặp lại.

Bước 2. Kích chuột phải vào movieClip trong Library, chọn Edit Class và sửa nội dung lại như sau:

package  {

import flash.display.MovieClip;
import flash.events.Event;

public class Light extends MovieClip {

public function Light() {
addEventListener(Event.ENTER_FRAME, fl_remove);
}

function fl_remove(e:Event)
{
if(this.currentFrame==40)
{
removeEventListener(Event.ENTER_FRAME, fl_remove);
delete this;
parent.removeChild(this);
}
}
}

}
Chú ý: Motion Tween của movieClip này chỉ diễn ra trong 40 frame. Do đó, Frame 40 là frame cuối cùng của nó.
Bước 3. Lưu tập tin lại dưới tên Light.as.
Bước 4. Xóa toàn bộ đối tượng trên stage, đổi màu cho stage sang màu đen. Kích chuột phải vào frame đầu tiên, chọn Actions để bổ sung Actionscript như sau:

import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import flash.display.MovieClip;
import flash.events.MouseEvent;

var xc:int = 0, scale:int = 1;

addEventListener(Event.ENTER_FRAME, fl_light);
function fl_light(e:Event)
{
var lightR:Light = new Light();
lightR.scaleX = .6;
lightR.scaleY = .6;
xc+=1;
if(xc>=int.MAX_VALUE)
xc = 0;
lightR.x = 300+scale*16*Math.pow(Math.sin(xc),3);
lightR.y = 300+scale*(13*Math.cos(xc)-5*Math.cos(2*xc)-2*Math.cos(2*xc)-Math.cos(4*xc));
lightR.rotation+.1;
var colorR:ColorTransform = new ColorTransform();
colorR.color = Math.random()*uint.MAX_VALUE;
lightR.transform.colorTransform = colorR;
addChild(lightR);
}

var timer:Timer = new Timer(2000);
timer.addEventListener(TimerEvent.TIMER, tick);
timer.start();
function tick(e:TimerEvent)
{
scale+=1;
if(scale>17)
scale=1;
}
Bước 5. Nhấn Ctrl+Enter để kiểm tra kết quả.

Source

Friday, August 24, 2012

Easier object setup in ActionScript

I recently thought of something that will make it easier when I'm creating instances with different values in ActionScript and thought I'd share it. It's sort of a mix of default parameter values and optional parameters and it makes it much more convenient to setup instances of things that are slightly different.

Let's suppose I have a Weapon class with some basic stats:

class Weapon
{
public var name:String;
public var attack:int = 10;
public var defense:int = 10;
public var speed:Number = 1.0;
public var heavy:Boolean = false;
public var tags:Array = ["weapon"];

/* skipping constructor and a "describe" function that prints the values */
}

And assume I have some other code that creates a bunch of instances. They're mostly the same but ideally I could just specify what's different than the default. Something like this:

var weapons:Array = [
new Weapon("stick"),
new Weapon("sword", { attack: +2, defense: +2 } ),
new Weapon("club", { speed: -0.25, heavy: true } ),
new Weapon("knife", { attack: -2, tags: ["sharp"] } )
];

for each (var weapon:Weapon in weapons)
trace(weapon.describe());

It would be really cool if I could get something like this as the output:

stick = { attack=10, defense=10, speed=1, heavy=false, tags=weapon}
sword = { attack=12, defense=12, speed=1, heavy=false, tags=weapon}
club = { attack=10, defense=10, speed=0.75, heavy=true, tags=weapon}
knife = { attack=8, defense=10, speed=1, heavy=false, tags=weapon,sharp}

Well, wish no more because it's possible. Here's the function that makes it happen. It takes two things and expands the first by the second. It could be improved to handle other types, but this is enough to get started with.

public function expand(receiver:Object, expansions:Object):Object
{
if (receiver == null || expansions == null)
return receiver;

for (var property:String in expansions)
{
if (receiver[property] == null)
continue;

var value:Object = expansions[property];

if (value is Number || value is int)
{
receiver[property] += value;
}
else if (value is Array)
{
for each (var element:Object in value)
receiver[property].push(element);
}
else
{
receiver[property] = value;
}
}

return receiver;
}

Just use it in the constructor or some section external to the object like a Factory.

public function Weapon(name:String, values:Object = null)
{
this.name = name;
Util.expand(this, values);
}

I'm sure I'm not the first to do something like this but I think it's a more convenient way to create things. If I ever find myself working on a 7 day long project and need a quick way to add content, this could be useful....

Wednesday, August 22, 2012

Tạo hiệu ứng bong bóng rơi theo trỏ chuột


Bước 1. Tạo một hình tròn rỗng ruột, có kích thước là 8x8px, viền 0.1 và có màu viền là màu đỏ.
 Bước 2. Bấm chọn hình tròn và nhấn phím F8 (để chuyển hình tròn này thành symbol khác). Trong hộp thoại convert symbol hiện ra, ta chọn MovieClip và nhập tên cho nó, ví dụ buble.
Bước 3. Nhấp chọn movieClip có tên là buble trong Library, kích chuột phải và chọn Edit. Trong cửa sổ thiết kế bên phải, ta chọn Frame 1, kích chuột phải và chọn Create Motion Tween.
Một vùng Tween mới được tạo ra, ta cố định độ dài cho vùng Tween này là 40 frame. Trong thao tác này, Flash sẽ tự động sinh ra một movieClip mới có tên mặc định là Symbol 1; ta đổi tên nó thành static_buble như trên.
- Chọn Frame đầu tiên, ta hiệu chỉnh đối tượng trên frame này có tọa độ (x,y)=(0, 0); ở frame cuối cùng, ta hiệu chỉnh tọa độ cho đối tượng trên frame này là (x, y)=(0, 310).
- Tiếp tục chọn Frame đầu tiên, ta chọn đối tượng trên frame này và chọn filters (trong hộp thoại properties) và bổ sung Adjust color cho nó với tham số Hue=117. Ở frame cuối cùng, ta chọn đối tượng trên frame này và chọn filters và bổ sung Adjust color cho nó với tham số Hue=-19.
- Tương tự hai bước trên, ta hiệu chỉnh Color Effect với style là alpha=1 cho đối tượng ở frame đầu; và alpha=0 cho đối tượng ở frame cuối.
Bước 4. Bổ sung một Layer mới có tên là Action. Bấm chọn Frame 40, nhấn phím F6 để chèn mới một Keyframe tại vị trí này. Kích chuột phải vào frame 40 này của Layer Action, chọn Action để chèn actionScript. Trong khung soạn thảo actionscript, nhập vào lệnh:
stop();
Bước 5. Trong library, kích chọn movieClip có tên là buble, kích chuột phải và chọn Edit Class, sau đó bổ sung mã lệnh vào ta thu được lớp buble hoàn chỉnh như bên dưới:
package  {
            import flash.display.MovieClip;
            import flash.events.Event;
           
           
            public class buble extends MovieClip {
                       
                       
                        public function buble() {
                                    addEventListener(Event.ENTER_FRAME, removeMe);
                        }
                       
                        function removeMe(e:Event)
                        {
                                    if(alpha<=0)
                                    {
                                                removeEventListener(Event.ENTER_FRAME, removeMe);
                                                parent.removeChild(this);
                                    }
                        }
            }
           
}
Bước 6. Quay trở lại với khung thiết kế chính. Xóa tất cả các đối tượng trên stage. Chọn màu nền cho stage là màu đen. Chọn Frame 1 của Layer 1, kích phải và chọn action để soạn thảo actionscript. Nhập đoạn mã sau:
import flash.events.Event;

addEventListener(Event.ENTER_FRAME, fl_add);
function fl_add(e:Event)
{
            var b:buble = new buble();
            b.x = mouseX;
            b.y = mouseY;
            b.play();
            addChild(b);
}

Bước 7. Nhấn Ctrl+Enter để kiểm tra kết quả.

Sources:

Tuesday, August 21, 2012

Vipshock templates - Tin tức news

Giao diện 2 cột dành cho site tin tức, thủ thuật.
Cấu trúc đơn giản gọn gàng.
load nhãn mặc định để tối ưu seo cho site.
Tóm lại là giao diện để làm site tin tức, thủ thuật ... :!^^

XEM DEMO DOWNLOAD


XEM DEMO DOWNLOAD


Cài đặt cũng như các theme share trước . mở bằng notepad++ tìm các đoạn js và thay tên nhãn cho phù hợp với nhãn blog bạn

<script>document.write("<script src=\"/feeds/posts/default/-/Tiêu điểm?max-results="+10+"&orderby=published&alt=json-in-script&callback=hotnewl\"><\/script>");</script>

Ai yêu thì để cho xin cái liên kết tới blog mình nha

<a href='http://www.bay68.com' target='_blank' title='Tham gia Hội chém gió VN'>Tham gia Hội chém gió VN</a>

Thông cảm adf buy domain nha các bạn. mới đc có 1$ còn thiếu nhiều quá!
Ai hảo tâm donate nhé :
Paypal.com: helloximo@gmail.com
Baokim.vn: nguagovt@gmail.com
Thank kiu!

Wednesday, August 8, 2012

Share temp maphim.net phiên bản v3.0 [skin Phim47] . Xml của Blogger.

Share temp maphim.net phiên bản v3.0 [skin Phim47] . Xml của Blogger.

Phim,Xem phim online HD nhanh mien phi chat luong cao khong giat 2013,2012

Tuy là cũ nhưng có vẻ rất nhiều bạn kết Temp này. Vì đó mình quyết định edit lại temp và share cho các bạn.

Player phiên bản mới nhất, hỗ trợ thumb cho Youtube và change Server.

Phim,Xem phim online HD nhanh mien phi chat luong cao khong giat 2013,2012


Download : http://v3maphim.googlecode.com/files/maphimblogs.zip

Demo : http://blog-mphim.blogspot.com/2012/08/test-temp.html

Hướng dẫn sử dụng :

= > tìm đoạn code sau : anc.home = "maphim.net"; thay bằng anc.home = "domain của bạn";

Nếu không có Sub thì chỉ cần ghi "domain.com" như trên, có sub thì điền là : xxx.domain.com

Ctrl + F : đoạn code sau ..

<script src='http://anhnc.googlecode.com/svn/trunk/beg/search.js'/>

<script src='http://anhnc.googlecode.com/svn/trunk/beg/ft.js'/>

= > Tải 2 file này về và sửa tất cả www.maphim.net thành domain của bạn, hoặc sub domain.

== > Cách post phim các bạn có thể xem tại đây.

Sunday, July 29, 2012

Notes for the next Game Jam I go to

I'm rarely a fan of posts that are in list form (e.g. "Top 10 tips for writing top 10 lists") but I seem to be in "list making mode" right now so expect some lists in this post.



I recently went to a local Game Jam. What's a game jam? I'd describe it as an event where people meet and come together to attempt to prototype an innovative game idea, fiting a common theme, and then share their results, no matter how embarrassingly incomplete, with others. All within a few hours.

Here's what I wanted to get out of it, from most important to least important:
  1. Meet cool people. I program at home and with coworkers all the time; this is a chance to meet others.
  2. Work together. I can work by myself any day.
  3. Fit a theme. I can follow my own ideas any day.
  4. Prototype a mechanic or idea. Because doing something boring is boring.
  5. See something cool. It can be really inspiring to see something created in such a short time.
  6. Show something cool. I need to share what I come up with more often.
  7. Make a game. Another thing I can do on my own time.
  8. Network/connect. If it happens, it happens; if not, I'm fine without it.

I'm sure everyone has their own criteria and there's probably someone with the exact opposite list writing a blog post right now about how they went to a game jam and ran into someone who spent all his time socializing and coding and didn't even bring business cards to hand out.

I certainly met some cool people, saw some really neat games, and even got a few business cards from other local developers and artists. The other things? Well... maybe next time. I was looking at the team I was on and the other teams and it seems like there's three things you need to do to accomplish the things on my list:
  • Pick an acceptable team
  • Pick an acceptable idea
  • Contribute

Notice I said "acceptable" team and idea. Not even "great", not even "good", just acceptable. You only have a few hours and everyone there will be quite impressed if your game is a slight variation of "avoid the red squares and collide with the green squares."

If those three things can make a gam jam experience good, then I suppose the opposite would probably lead to a less fun time:
  • Actively break up the team
  • Push or accept an idea that totaly misses the point of a game jam
  • Contribute nothing but your dumb idea

Yup, those were the three things I ran into. I suppose I should have stepped up and tried to keep the team together, make sure we we're doing something worth doing, and make sure everyone had something to do. So, if you're the proactive type of person, the three things you really need to do to prevent someone from sabotaging your efforts to accomplish the things on my list are:
  • Pick (and maintain) an acceptable team
  • Pick (and maintain) an acceptable idea
  • Contribute (and help others)

Here's another list of random observations:
  • UnityScript sucks. Not thoroughly statically typed, not thoroughly dynamically typed. If you have to explicitly cast every time you get something from an array then your language has the worst of both worlds. And that's the easy way. I had to sum an array of floats and since floats are primitive, I couldn't cast them. I looked online for about 15 minutes and in the end, I had to convert the object to a string then parse it as a float.
  • Pick a team you can quickly get started with. When you only have 6 hours you don't want to spend the first 2.5 hours downloading and setting up Unity and Dropbox.
  • Teams that stick to the spirit of game jam do better than people sitting near each other half-working toward a dumb idea.
  • Dropbox sharing made integration easy but also more painful: you constantly get updates in the background but when someone is stuck on a compiler error or obvious bug, everyone knows within thirty seconds. Ultimately, instant feedback, and help from others, was a better way of maintaining progress on such a short iteration.
  • Control-z is good enough version control if you're only programming for one session.
  • Unity may be better for weeklong or monthlong jams, but not good at all for 6 hour jams. The best games used Flixel.
  • Working in teams would be better without all the other people. I really hate to say it but I've never been a fan of teamwork and it rarely works out. Sometimes it does, but the end results are mostly beyond my influence and usually disappointing. It always reminds me of high school group projects.
  • Whatever you create is going to be buggy and incomplete and almost certainly not even fun. That's ok. Everyone there is in the same situation and we're all there to have a good time. There was definitely an air of cooperation and support. It was fun and strangely adventurous to see what so many small groups of people could come up with under such constraints.


I still plan on going to the next game jam in my area - I'm just going to do it differently.

Popular Posts