text:
User talk:Zleitzen~enwikibooks

Hello and welcome to Wikibooks!

Here are some tips to help you get started:
 * You should sign your name on Talk and vote pages using four tildes, like this: ~~~~.
 * Remember to conduct any editing experiments in the sandbox.
 * If you're a Wikipedian, see Wikibooks for Wikipedians for a primer on how things work here (it's a little different).
 * If you want to base your work here on materials from Wikipedia, please use WB:RFI to bring the material over in compliance with the GFDL.
 * If you're an instructor and plan on using wikibooks for a class project, see Guidelines for class projects
 * Please say hello at the Staff Lounge with any questions or ideas.
 * Eventually, you might want to read the Manual of Style and Policies and Guidelines.
 * Please take a look at Naming policy before starting a new book.
 * Remember to maintain a Neutral point of view.
 * Explore, be bold in editing pages, and have fun!

You will find more resources in Community Portal. If you want to ask a question, visit the Study help desk, the Staff lounge, IRC channel or ask me personally on my talk page. For site news, see the Bulletin board. It might be an idea if you add this page to your "watchlist" so that you can see when any new information is posted there.

Good luck! Mattb112885 03:22, 20 February 2007 (UTC)

Your account will be renamed
Hello,

The developer team at Wikimedia is making some changes to how accounts work, as part of our on-going efforts to provide new and better tools for our users like cross-wiki notifications. These changes will mean you have the same account name everywhere. This will let us give you new features that will help you edit and discuss better, and allow more flexible user permissions for tools. One of the side-effects of this is that user accounts will now have to be unique across all 900 Wikimedia wikis. See the announcement for more information.

Unfortunately, your account clashes with another account also called Zleitzen. To make sure that both of you can use all Wikimedia projects in future, we have reserved the name Zleitzen~enwikibooks that only you will have. If you like it, you don't have to do anything. If you do not like it, you can pick out a different name.

Your account will still work as before, and you will be credited for all your edits made so far, but you will have to use the new account name when you log in.

Sorry for the inconvenience.

Yours, Keegan Peterzell Community Liaison, Wikimedia Foundation 23:56, 17 March 2015 (UTC)

Renamed
 This account has been renamed as part of single-user login finalisation. If you own this account you can |log in using your previous username and password for more information. If you do not like this account's new name, you can choose your own using this form after logging in: . -- Keegan (WMF) (talk) 05:40, 19 April 2015 (UTC)

title: User talk:Zleitzen~enwikibooks


text:
Analogue Electronics/BJTs

BJTs are very versatile and very simple devices. They can be used for amplification and switching in a variety of configuratons, each with uses and drawbacks.

Structure
BJTs are so named because they consist of junctions between the two kinds of semiconductor (n and p type) and have one pn junction and one np junction (i.e. the other way around). Compare this to a unipolar junction transistor,which has only one junction. The construction of a BJT is very simple - it is three alternating layers of semiconductor. The diagram below show the basic construction, but they are not to scale.

NPN Transistors
The NPN transistor is made of layers in that order:

It is equivalent to two back-to-back diodes, but connecting two diodes like this will not work, as the thicknesses and geometry of each layer is important, as are effects from the interaction of the two outer layers.

The symbol for this kind of transistor is shown to the right. It can be drawn with or without the circle. With is technically more correct, but it is not necessary. A useful mnemonic for remembering which way the arrow points on an NPN transistor is:

 * "Not Pointing iN".

The arrow is always drawn on the emitter - it actually means which way (conventional) current flows in the emitter.

PNP Transistors
The PNP transistor is the same, except the order of the layers is reversed:

It is equivalent to two nose-to-nose diodes, but as before, just connecting two diodes will not work. Generally, a PNP transistor is identical to an NPN transistor, but with all currents reversed.

The symbol is the same, but with the arrow reversed. Note that the emitter of PNP transistors often face upwards.

We will not really consider the PNP transistor at first - it is essentially the same as the more common NPN transistor, but reversed. We will look at applications for it later.

Operating Modes
How the BJT works depends on the bias of each junction. Each junction is like a diode, and in some ways behaves accordingly. Since there are two junctions, each of which can be biased in two ways (forward or reverse), there are four possible modes for the BJT. The following table lists them. The modes are the same for NPN and PNP.

The Active mode is generally used for amplification, and the Cut-Off and Saturation modes are used for switching and binary logic (when you just want 1 or 0).

The working of a BJT will be explained on the next page, BJTs in Active Mode.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Analogue Electronics/BJTs


text:
Prolog/Lists

Lists
Any language needs a way to handle collections of objects and prolog is no exception. A list in prolog can look like this:

[a, b, c, d, e]

The brackets are the beginning and the end of the list, and the commas separate the various elements. Here all the elements are atoms, but a list can contain all sorts of elements, and different types of element can occur in the same list. The following are examples of valid lists:

[a, A, B, C, D] [p(A,V), p(a, V)] a1,a2,a3],[b1,b2,b3],[c1,c2,c3 [[A,B], [B,C], quu([a,b,c],[a,b,d,e,f],_), c, m, D]

Most prolog code will not define a list explicitly, like these examples, but rather handle lists of any length, with many possible elements. To handle lists without knowing what's inside them or how long they are, you use the bar notation:

[Head|Tail]

In this notation the variable Head represents the leftmost element of the list and the variable Tail represents the rest of the list represented as another list. A head can be anything, from a predicate to another list, but the tail is always another list.

Some default library rules are provided, e.g., length, reverse, append (also, these can be defined easily, as shown at the bottom of this page). To see how these work, try the following codes: ?- length([1, 3, 6], What). Prolog will answer 3.

?- append([a], b, Z).

?- append([a], [b], Z). Observe the difference here.

?- append(X, [1, 2], [1, 1, 2]).

?- reverse([1,2], What).

The following program shows how to use this.

listsplit([H|T], H, T).

Here, [H|T] is a list, H is the head, and T is the tail. For the query ?- listsplit([a,b,c,d,e], a, [b,c,d,e]).

Prolog will answer yes. For the query

?- listsplit([a,b,c,d,e], A, B). Prolog will answer:

A = a B = [b, c, d, e] ;

The program can even be used to 'create' a list: ?- listsplit(List, a, [b,c,d,e]). List = [a, b, c, d, e] ; here are some examples of lists, and what heads and tails they result in:

Note that the empty list [ ] cannot be split up and therefore will not unify with [H|T].

Splitting up lists can be done with more than two heads:

[H1, H2, H3|Tail]

This will split a list up into the first three elements, and the rest of the list. Note, however that this will fail if the list has fewer than three elements.

Now consider the following program:

last([Elem], Elem). last([_|Tail], Elem) :- last(Tail, Elem).

This relation defines the last element of a list. It can be used as a program to find a list's last element:

?- last([a,b,c,d,e],X). X = e

First, there is the stop predicate, that says that the last element of a list with one element, is that element. The second line says that the last element (Elem) of a list [_|Tail] is the last element of its tail (Tail). Since we don't care about the head, we use the anonymous variable, _, for it.

The member predicate
Normally, you would use built in predicates for these list operations, instead of writing them yourself. Built in predicates are defined by your prolog implementation, but can be used in any program. These implementations are shown here to illustrate how to modify lists.

Member is a standard prolog built-in predicate. You use it like this:

member(Element, List).

Where List is any prolog list, and Element is any element in that list. The following, for instance, succeeds (returns 'Yes'): ?- member(a, [a, b, c]). ?- member(b, [a, b, c]). ?- member(c, [a, b, c]). This query: ?- member(Element, [a, b, c]). Will return the following values for Element: Element = a; Element = b; Element = c; The member predicate is defined like this: member(X, [X|_]). % member(X, [Head|Tail]) is true if X = Head % that is, if X is the head of the list member(X, [_|Tail]) :-  % or if X is a member of Tail, member(X, Tail). % ie. if member(X, Tail) is true.

The append predicate
The built-in predicate append/3 attaches a list to the back of another, in other words, it concatenates two lists. It's used like this: append(Xs, Ys, Zs) Where Zs is Ys appended to Xs. The following succeed: append([a, b, c], [1, 2, 3], [a, b, c, 1, 2, 3]). append([], [a, b, c], [a, b, c]). append([A, B, C], [1, 2, 3], [A, B, C, 1, 2, 3]). You can use it to append two lists: ?- append([a, b, c], [d, e, f], Result).

Result = [a, b, c, d, e, f] Or to split a list into left and right parts, ?- append(ListLeft, ListRight, [a, b, c]). ListLeft = [] ListRight = [a, b, c] ; ListLeft = [a] ListRight = [b, c] ; ListLeft = [a, b] ListRight = [c] ; ListLeft = [a, b, c] ListRight = [] ; No You can even use it with three variables. (Try this for yourself to see what the result looks like).

The append predicate can be defined like this:

append([], Ys, Ys). append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).

The first line simply unifies the last two lists, it succeeds for queries like: append([], [a,b,c], [a,b,c]). or append([], X, [e]). in which case it would bind X = [e]. The second line (the recursive clause) declares that, given append(A,B,C) the head of A is equal to the head of C, and appending the tail of A, with B, gives the tail of C.

Due to the nondeterminism of Prolog, append/3 has many uses. It can be used as another way to implement last/2 which was defined earlier.

last(List, Last) :- append(_, [Last], List).

Many more definitions are possible,

split(List, Pivot, Left, Right) :- append(Left, [Pivot|Right], List).

?- split([o,o,x,e,e,e], x, L, R). L = [o, o], R = [e, e, e] ;

?- split(A, -, [o,o], [u,u,u]). A = [o, o, -, u, u, u].

Reversing a list
We will look at two ways to reverse a list, first of all the naive way is to simply keep taking the head off and appending it onto the end,

reverse([],[]). reverse([X|Xs],YsX) :- reverse(Xs,Ys), append(Ys,[X],YsX).

Executing it means that you traverse the list over and over again appending each time, A more efficient version can be created by taking the definition of append:

append([], Ys, Ys). append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).

and changing it slightly,

revappend([], Ys, Ys). revappend([X|Xs], Ys, Zs) :- revappend(Xs, [X|Ys], Zs).

then,

reverse(Xs,Ys) :- revappend(Xs,[],Ys).

The strategy used in revappend is called an accumulating parameter.

Exercises
(1) The built in predicate length can be used to find the length of a list. For example: ?- length([a,b,95,[1,1,1,1]],X). X = 4. ?- length([a,XYZ,59,1,1,1,1],X). X = 7. How might this predicate be defined?

Answers to Exercises
(1) As you probably guessed, we will use recursion. len([], 0). len([_ | Tail], Length) :- len(Tail, Length1), Length is Length1 + 1,!. Another solution which uses tail recursion optimisation and Prolog's arithmetic (And therefore uses less stack space): % 0 - Calling Rule cl(List, Out) :- call(List, 0, Out).

% 1 - Terminating condition call([], Count, Count).

% 2 - Recursive rule call([H|T], Count, Out) :- Count1 is Count + 1, call(T, Count1, Out).

prev:Variables next:Math, Functions and Equality

title: Prolog/Lists


text:
Muggles' Guide to Harry Potter/Magic/Waddiwasi

Overview
The Waddiwasi charm apparently causes violent removal of chewing gum (possibly among other things) from the place that it is currently stuck.

Extended Description
Professor Lupin uses this spell when he encounters Peeves stuffing chewing gum into a lock. He says that this is a very useful little spell, before he uses it; and it is interesting, because the effect is to fire the chewing gum up Peeves' nostril and send him away, something that many teachers had been unable to do. As to its usefulness, though, it does not seem to be used anywhere else in the books.

The incantation, the verbal part of the spell, contains the word "wad", that is to say, a small amorphous mass of material - such as chewing gum.

Analysis
As noted, despite Professor Lupin saying it is a useful little spell, it is used nowhere else in the series. This does rather call its usefulness into question, though it certainly does serve the dual purpose of clearing out the lock and getting rid of Peeves. We suspect that the author's purpose in introducing this spell is more one of enlightening us regarding the character and magical ability of Professor Lupin. The spell is clearly relatively obscure, as it serves a primary purpose (eliminating gum) that is not often needed, yet Lupin is fluent in its use, which speaks highly of his ability and memory. Additionally, he immediately sees this as a teaching opportunity, a place where he can teach the class a possibly useful spell. Many other professors at Hogwarts, we believe, would simply perform the spell, whereas Lupin makes a point of demonstrating it.


text: Template:Adobe screenshot

title: Template:Adobe screenshot


text:
Analogue Electronics/BJTs/Active Mode

In the Emitter
Recall from the previous page that a BJT in active mode has its emitter-base junction in forward bias and its collector-base junction (CBJ) in reverse. This means, for an NPN device, that the emitter is at a lower potential than the base, which is lower than the collector. Generally, the voltage between the collector and base is larger than the voltage between the emitter and base.

The EBJ is forward biased, so electrons will be injected from the emitter into the base. Also, some holes will be injected into the emitter from the base, but the emitter is much more heavily doped than the base, so this current is small (this is the preferable situation, so transistors are designed and made like this).

The electrons flowing out of the emitter and the holes flowing in together constitute the emitter current, iE, which is defined to be "out of" the emitter lead. As we said before, this current is dominated by the electron flow.

We might expect the electrons to be either "stuck" in the base, or to be removed via the base, as the CBJ is reverse biased, and therefore we do not expect it to be conducting. However, recall that when a pn junction is reverse biased like this, all that it means is that holes cannot travel from left to right, and electrons cannot go from right to left. Normally, this results in no current, as there are no electrons present in p-type material.

In the Base

Let us now look at what happens to the electrons injected into the base. Because the base is made of p-type silicon, the electrons are minority carriers. The base is very thin (the diagram above is not to scale), so the electron concentration, np, will have a linear characteristic. This is explained in Semiconductors, and we will not try to prove it here. The electron concentration will be highest at the emitter side of the base, and will be zero at the collector side. It is zero here because the CBJ is in reverse bias, causing all minority carriers to be attracted to and swept across to the collector (by the same token, majority carriers, holes, are repelled from the junction). We will term the electron concentration at the EBJ np(0).

The EBJ is in forward bias, so the concentration at the emitter side of the base np(0) will be proportional to evBE/vT:

 * $$n_p \left( 0 \right) = n_{p0} \exp \left( {\frac

} \right)$$

where
 * np0 is the thermal equilibrium concentration of electrons in the base
 * vBE is the forward voltage across the EBJ
 * VT is the thermal voltage (about 25 mV at room temperature - 300K)

The decreasing concentration of electrons in the base as we move toward the collector causes a diffusion current in this direction (electrons try to diffuse to lower concentrations). This diffusion current, In is proportional to the gradient of the electron concentration:

 * $$I_n = A_E qD_n \frac$$
 * $$I_n = A_E qD_n \left( { - \frac{W}} \right)$$

where
 * x is the distance of a point from the EBJ
 * AE is the cross sectional area of the EBJ
 * q is the magnitude charge on an electron (a positive quantity)
 * Dn is the electron diffusivity in the base
 * W is the effective width of the base (taking into account reduction due to depletion zones)

For more information on exactly why this is, see Semiconductors.

Due to the negative slope of the electron concentration, we get a negative current (with respect to x), which means that it flows right-left. This is not surprising, as electrons are negatively charged, so a diffusion form left to right leads to a current from right to left.

Because the electrons here are in a p-type material populated with holes, some will recombine with the holes in the base. Due to the base being very thin, this is a small proportion of the total number of electrons. This effect causes the electron concentration in the base to be slightly non linear (dashed line in the above diagram). Because the concentration is higher near the EBJ, we expect a larger number of electrons to recombine per unit length than we do at the CBJ, so the line is steeper at the EBJ, leading the "dished" shape shown in the diagram.

In summary so far, we are injecting electrons into the base from the emitter, and these are readily swept up by the electric field across the CBJ. The base is made very thin to allow just this to occur. A small number of electrons will recombine with the holes (which are the majority carriers) in the base layer. However, the base is very thin, so the electrons are usually swept up before they can recombine. This means that a large current will flow through the transistor from emitter to base. A smaller current, made up of the holes flowing into the emitter and the recombining holes makes up the base current.

This is why the emitter and collector are so named - the emitter emits electrons into the base, and the collector collects them from the base.

Collector Current
In the sections above, we saw that the majority of the electrons diffusing across the base make it to the CBJ, whereupon they are swept up by the electric field across the CBJ, which is in reverse bias. These "swept-up" electrons constitute the collector current, iC Therefore, we can say that:

 * $$i_C=I_n \,$$.

Since In is negative, this implies that the collector current is negative too, with respect to our direction of increasing x. This means a current from right to left, so flowing into the collector lead. In the equations below, we will remove the negative sign, and work with the magnitude of the current.

Thus:

 * $$i_C = A_E qD_n \left( {\frac{W}} \right)$$

Substituting for np(0) from above, we get:

 * $$I_n = A_E qD_n \frac{W}$$

We now define a quantity called the saturation current as follows:

 * $$I_S = \frac{W}$$,

leading to:

 * $$i_C = I_S \exp \left( \frac{v_{BE}} {V_T } \right)$$.

We can also substitute np0=ni2/NA into our expression for IS:

 * $$I_S = \frac

$$

Note here that the collector current does not depend on the voltage across the CBJ, vCB. So long as the CBJ is in reverse bias, the electrons that reach the CBJ will be removed into the collector.

Our newly defined saturation current, 'IS is inversely proportional to the width of the base, W, and directly proportional to the area of the EBJ. The saturation current can generally be expected to lie in the range of 10−18 to 10−12 A. It is very much affected by temperature as it proportional to the square intrinsic electron concentration. Therefore, it is also proportional to the cube of the absolute temperature. This is explained in Semiconductors. For an actual transistor, the saturation current will be given by the manufacturer on the datasheet.

As the saturation current is related to the ratio of the EBJ area and the width of the base, it is also known as the scale current. This is a frequently-used principle in the field of IC design, as two transistors that are identical except for EBJ area will have, for the same vBE, collector currents differing by a factor equal to the ratio of the EBJ areas.

Base Current
We have already seen that there are two components to the base current: the holes injected into the emitter (iB1) and the holes that are supplied (via diffusion) to replace those lost by recombination with electrons in transit from emitter to collector. This is ''iB2.

iB1 is given by the equation for a forward-biased pn-junction, similar to that used earlier:

$$i_{B1} = \frac\exp \left( {\frac } \right)$$

where:
 * AE is the cross sectional area of the EBJ
 * Lp is the hole diffusion length
 * Dp is the hole diffusivity in the base
 * ND is the doping concentration of the emitter

Note that because the emitter is very long (as opposed to the very short base), we do not use the emitter length, but rather Lp, the diffusion length of the holes.

iB2 can be evaluated by looking at the average time that it takes for an electron in the base to recombine. This time, called the minority-carrier lifetime, is denoted by τb. In this case, in this time, all the electrons in the base (constituting a charge Qn) will have recombined.

In a steady state, this charge will be constantly replenished by the electrons flowing in from the emitter. in order for the electrons to be replenished to maintain a steady state, the injected current must supply the base with a (positive) charge of:

 * $$i_{B2}=\frac{Q_n}{\tau_b}$$

The minority carrier charge stored in the base in steady-state is related to the area under the triangle formed by the electron-concentration curve (which is a straight line), which can be seen in the diagram above. Multiplying by the volume of the base, electronic charge and the maximum concentration, np(0), we get the total charge to be:

 * $$Q_n = A_EWq \times \frac{1}{2} n_p\left( 0 \right).$$

Substituting for np(0) and then for np0 gives:

 * $$Q_n = \frac{1}{2}\frac\exp \left( {\frac} \right)$$

Substituting from the equation relating iB2 to τb, we get:

 * $$i_{B2} = \frac{1}{2}\frac\exp \left( {\frac} \right)$$

Now, the total base current is given by:

 * $$i_B = i_{B1}  + i_{B2}$$
 * $$i_B = \frac

\exp \left( {\frac } \right) + \frac{1} {2}\frac \exp \left( {\frac } \right)$$

This unwieldy form can be simplified somewhat by applying the expression for the saturation current and factoring out the exponential part:

 * $$i_B = I_S \left( {\frac

+ \frac{1} {2}\frac } \right)\exp \left( {\frac } \right)$$

As an aside here, notice that the part given by iB1 is related to the following ratios:
 * Hole to electron diffusivity
 * Acceptor to donor doping concentration
 * Base width the hole diffusion length in the emitter

We now define a quantity called β as follows:

 * $$\beta = 1 \bigg/\left( {\frac

+ \frac{1} {2}\frac } \right)$$

β is a scalar quantity (see here for confirmation) that is defined entirely by the physical properties of the transistor. We can see that it relates the base and collector current:

 * $$i_B=\frac{i_C}{\beta}$$.

β generally takes a value of between 50 and 300 for "normal" transistors, but for more expensive devices (especially those sold in IC form such as the SSM2210), it can reach 1000. β is often called the common-emitter current gain. It is also often called hFE. This is due to convention in circuit theory. To see why, see this page. We can see that β is influence by some parameter related to the production process rather than the physical properties of the semiconductor. In order to obtain high β, we can make the base width, W, very small and dope the emitter very heavily compared to the base. Also, note that so far, we have assumed that β is constant for a given transistor. We shall see soon that this is not necessarily the case, but it is frequently a useful approximation.

Emitter Current
From Kirchhoff's Current Law, we know that all current entering the transistor must also leave the transistor. Given the "default" current direction for each of the terminals of the device, we see that:

 * $$i_E=i_B+i_C$$

Using the relationship between iB and iC, we have

 * $$i_E = i_C + \frac{i_C}{\beta}=\frac{\beta+1}{\beta}i_C $$
 * $$i_E = I_S \frac{\beta }

\exp \left( {\frac } \right)$$

We can also define α such that:

 * $$i_C=\alpha i_E$$.

α is therefore:

 * $$\alpha=\frac{\beta}{\beta+1}$$

We can easily see from this that α is less than, but close to, unity. Substituting with α in the expression for ''iE, gives

 * $$i_E = \left( {\frac

{\alpha }} \right)\exp \left( {\frac } \right)$$

Rearranging the expression for α, we also have:

 * $$\beta = \frac{\alpha}{\alpha-1}$$

α is termed the common-base current gain. α and β describe the transistor in forward-active mode only (reverse active operation is different). Sometimes it may be necessary to explicitly show this, by writing αF and βF. These can be used interchangeably with α and β.

It is also possible to consider the action of a BJT in active mode using energy band diagrams. This explanation can be found on this page.

Large Signal Models
In the previous section, we saw how the NPN BJT behaves in the forward-active mode. That is, the base is at a higher potential than the emitter and the collector is at a higher potential than the base. We can use the properties to "convert" a BJT to simpler components for analysis. The models will work for all signals, and so are called large-signal equivalent models, or LSEMs.

The Common-Base LSEM
The forward biased EBJ causes a current to flow in the collector that is exponential with base-emitter voltage, vBE. This current is not related to the voltage of the collector, as long as it is greater than that of the base (so the CBJ is in reverse bias). The BJT thus behaves like a (non-linear) voltage-controlled current source, controlled by vBE.

The base current is a fraction, given by the emitter current divided by β, and the emitter current is the sum of the collector and base currents. Generally, β is large, so the base current is small, and emitter current is approximately equal to the collector current.

From the above description of an NPN BJT, we can derive an equivalent circuit model that describes the BJT in terms of simpler components:

Diode DE has a current of iE in it. From above, we have:

 * $$i_E = \left( {\frac

{\alpha }} \right)\exp \left( {\frac } \right)$$

We can call $$I_S/\alpha$$ the saturation current for the diode, I_{SE}. The current in the collector was previously established to be given by:

 * $$i_C = i_S \exp \left( {\frac

} \right)$$

Therefore, we can see that iC is related to iE by dividing by α. We also saw this previously in the section where α was derived.

We now have a BJT model that describes all the currents in terms of vBE, and is reference to the base voltage. Let us now consider this model as a two-port network, with the input port being between the emitter and the base, and the output port between the collector and the base. The base is therefore common. As we can see, the current gain is equal to α, hence the naming of α the common-base current gain:

The Common-Emitter LSEM
We can also have a BJT model referenced to a common emitter:

The collector current is given, just as for the common-base configuration, by:

 * $$i_C = I_S \exp \left( \frac{v_{be}}{V_T} \right) $$

We know that the base current is given by the collector current divided by β:

 * $$i_B = \frac{I_S}{\beta} \exp \left( \frac{v_{be}}{V_T} \right) $$

We can therefore easily see that the collector current is related to the base current by:

 * $$i_C=\beta i_B$$.

As before, we consider the current from base to emitter to flow through an internal diode. This time, we call it DB, but now its saturation current is given by:

 * $$I_{SB}=I_S / \beta$$

title: Analogue Electronics/BJTs/Active Mode


text:
Civ/Civilization IV/Modding

 * /Utilities/
 * /Tutorials/

title: Civ/Civilization IV/Modding


text:
Civ/Civilization IV/Modding/Utilities

General
Utilities are for accessing or modifying data in Civilization IV or for other purposes like creating maps, debugging python code, editing XML.

XML

 * XML Marker is a free, user-friendly XML editor
 * Altova XMLSpy 2006 Home Edition is the free version of the utility used by Firaxis itself!

Python

 * The HAP Python Debugger is a python remote debugger which can be used to monitor python scripts running in Civilization IV from the outside.

Graphics

 * The Gimp is an open source software package for creating and modifying pixel based graphical content.
 * GIMP DDS plugin is a plugin for GIMP 2.x that allows you to load and save images in DDS format, which Civilization IV uses.
 * Blender is an open source 3D modeler package which in the future might be useful together with Niftools to create and modify 3d-models for Civilization IV. (some reading materials about civ in the niftools forums can be found here and here)

Maps

 * BMP to WBS Converter is a utility written by Jon Shafer, Rhye, Jesse Smith, Locutus and Door, that allows you make maps by drawing bitmaps and converting them to worldbuilder saves

title: Civ/Civilization IV/Modding/Utilities


text:
Civ/Civilization IV/Modding/Tutorials

Python

 * Getting Started
 * Python Console
 * Tips and Tricks
 * TGA's Python Tutorial
 * Python in Civ 4
 * Civ 4 Python Class Reference (by Locutus)

World Builder

 * Dale's "Modding Guide for Civilization IV Volume 1" covers designing scenarios, using the world builder and editing world builder saves in text format is no longer available. A replacement would be nice …

 * Actually, it's still available: at CivFanatics. This thread contains both the World Builder manual and manually editing a WBS file that I wrote.  -- Dale

Graphics
There are no graphics tutorials at present

Scenarios
There are no scenario creation tutorials at present

Mods

 * Adding a Civilization
 * Minimum City Range

title: Civ/Civilization IV/Modding/Tutorials


text:
Civ/Civilization IV/Modding/Tutorials/Getting Started

Getting Started
This page will become a helpful place to get started in modding Civilization IV. It is layed out in a semi-logical format (as much as possible in wiki), starting from the basics of tweaking things (using XML) up to the more advanced modding using Python to create scenarios and rework the GUI.

Getting Started With XML
A large part of the configuration of Civ4 is done through XML. All of the text (in different languages), unit stats, building costs and more are encoded in XML and are saved in plain text files, with the extension .xml.

That's all great, but what does XML look like, and how does it work? If you are comfortable with HTML, or even the VB code used in your posts, then learning XML should be no problem. It consists of tags like ... that wrap around pieces of information to describe them. To see a good example of XML in use, look no further than your PMs! You can download PMs in XML format- there is an option in the menu where you delete them.

As an example, here is a PM that I sent to myself:

  2005-10-25 09:31        XML in Civ4 Weasel Op        Hey, did you know that Civ4 uses XML? :D Now that probably looks awfully complicated, especially if you have never seen HTML, but don't worry. I'll explain how it works.

 That part just tells the program reading the file, and you the coder, what this is. The first tag informs the program that this is an XML file, written in version 1.0, and that it uses the Western European character set. The next 2 lines are comments- notice the. Everything between those is a comment, and is ignored by the program. It's just there for you, so you know what this is.

Next comes the good stuff:  The first tag that really does something is the tag. This tag tells the computer that everything from this tag through the closing tag (a tag with a / before the name, in this case ) is an element. An element is a piece of information. It can contain other elements, text, or both. In this case, begins an element that contains all of the private messages in the file. (There is only 1 here, but if I had saved my entire Inbox they would all be in there.)

Next is the tag. Notice that this tag does not only have a name, but a description. This description is called an attribute. An attribute is a little piece of information included in an element tag. It gives the element a characteristic, in this case the name "Inbox." This is an example of the flexibility of XML. "Inbox" could have been a separate element within "folder" like this:  Here, "Inbox" is an element within "folder." However, "Inbox" is better as an attribute because logically, "Inbox" is a specific folder, not a part of a folder.

Are you getting the hang of it yet? Let's move on. This is where things start getting interesting: 2005-10-25 09:31    XML in Civ4 Weasel Op    Hey, did you know that Civ4 uses XML? :D That's a big chunk of code, but if you look closely it folloes the same pattern. This is the PM itself, the actual information that I sent myself. Notice the tag. This is NOT the same as. That tag defined everything in it to be a group of private messages, but this tag defines itself to be a single PM. Look at the bottom line. See that closing tag? It has the same name, but a slash before it:. This is the closing tag for indicating the end of that element. Everything in between, including the tags themselves, are part of the element.

The second line gives us the date and time the message was sent. The tags wrap around it, indicating that it is also an element. Similarly, the next line is the title of the PM, and the line after that indicates who the message is from. Keep in mind that each of these elements are part of the element, which is part of the element, which is in turn part of the element.

The next line looks a little different. This tag combines the opening and closing tags into one. Since the line is blank, there is no need for two separate tags. Adding the slash to the end after the slash is like xml shorthand- it opens and closes the element with the same tag. The "touser" element is blank because this is my own PM. If it were addressed to someone else, it wouldn't be in my inbox!

The next element is the heart of it all. This is the actual text of the PM, enclosed in the tags. Depending on the PM, this element could include several lines of text, VB code, etc. But the important thing to note is that it's all text. There is nothing magic about XML. There is no compiler, no functions, no special characters. Everything is saved, sent, and edited in text format only.

As I mentioned, the last line indicates the end of the element.

Now let's look at the last piece of code: By now you can probably guess what these do. closes the "folder" element. Notice that the attribute "Inbox" is not included here. The attribute is a part of the element, not an element itself. In fact it can't be closed because it was never opened. It's just a characteristic of the "folder" element. If there's no more "folder", it can't be an "Inbox". The final line closes the element.

Now you may be wondering, why are there 3 elements inside of each other like that? If you look back at the entire piece of code, you will see that the 3 major elements open and close together:  . . . Why couldn't those all be one element? Actually, the only reason they appear that way is because I only saved 1 PM. If I had downloaded all of my PMs in one file, it would be different. would still contain everything, because that is the root element. That just means that is the primary, basic element of the file. The whole file is essentially one element,. Inside would be two elements:  and . After the first tag, the second folder would then begin:  The same would apply to. Each PM would be a separate element, and after each closed the next would begin, until the end of the folder.

Now that wasn't too hard was it? Once you understand the basic concepts of how XML works, it's a simple process.

Now I know you're probably wondering, how does that help me mod Civ4? PMs have nothing to do with it. That's right, but you will be surprised at how similar it will be.

Getting Started with Python
The great thing about Civilization IV using Python for most of its GUI and event system is that you don't need to do anything other than open up .py files in a text editor (such as notepad), edit them and save it. No compiling necessary.

Python files are located in Assets\Python. The base of this directory varies, as it can be the Civilization 4 root game directory, or a mod directory, but the layout of directories under Assets\Python shouldn't change.

Here's a look at the directories: \...\Civilization 4\Assets\Python . `-- pyWB
 * -- EntryPoints
 * -- PitBoss
 * -- Screens
 * -- System
 * |-- email
 * |-- encodings
 * `-- wx
 * |-- build
 * |-- lib
 * |  |-- colourchooser
 * |  |-- editor
 * |  |-- floatcanvas
 * |  |-- masked
 * |  |-- mixins
 * |  `-- ogl
 * |-- py
 * |  `-- tests
 * `-- tools
 * `-- XRCed
 * -- _DebugTools
 * -- pyHelper
 * -- pyUnit


text:
Civ/Civilization IV/Modding/Tutorials/Python Console

Overview
A really helpful feature of Civilization IV is the in-game Python console. This is similar to the interactive mode when you start python without specifying a .py file to run.

From the console you can interactively inspect, modify and debug all the python internals while the game is running. This will be invaluable for python programmers and modders.

Enabling the console
Warning: This section contains a cheat code.

 * 1) Edit the main CivilizationIV.ini file.
 * 2) * Change the "CheatCode = 0" line to "CheatCode = chipotle"

>>
 * 1) Start Civilization IV as per normal.
 * 2) Start a new game, or load an existing game.
 * 3) While in the main view of the game, press Shift-~ to enable the Python console (that is "shift + ö" on German keyboards).
 * 4) * You will be presented with a short version string and a prompt like this:

Useful commands
The Python console is very similar to the standard interactive Python mode. One notable exception is that you need to explicitly print out statements to see their return value.

You can use the arrow keys to go to the next/previous command you typed and to move the cursor left and right along the current line. Pressing return on the end of a logical Python statement executes that statement. Statements that define a block (such as the if statement) will expect more lines to be entered before the command is executed. Indentation is required in Python code blocks.

Here are some useful commands to try out:

>> print 'Hello World'

Prints out the standard 'Hello World' bit.

>> print dir

Prints out an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. In other words, this will list all the classes, modules and variables that are in use at the moment in the current Civilization IV game.

Handy.

>> print dir(gc)

gc is the current game context and contains almost all the information about the current game, such as player info, city info, how many units are in the game, etc. This will list all the attributes of the game context.


text:
Civ/Civilization IV/Modding/Tutorials/Tips and Tricks

Getting Python to Generate Documentation
If you're looking for a quick and easy way to get documentation about the Python modules in Civilization IV then here's what you can do:

import pydoc pydoc.writedoc(<module name>) So if you want to show all Dll-exported classes do: import pydoc pydoc.writedoc(sys.modules['CvPythonExtensions'])
 * Open up a .py file.
 * Add these lines to the __init__ function:
 * Run Civ4.

This (should) write out an .html file in the Civilization 4 root directory all the information that pydoc can find about the module. While this depends heavily on the programmers leaving lots of descriptive __doc__ strings, you can at least get the function and parameter names out of it.

Making Changes Quickly
Since Python is an interpreted language, you should be able to modify a python file, and then see the results in Civ4 immediately. I've found that this is true in at least one case, but false in certain other cases.

For example, if you modify the Civilopedia pages, and then access this page from Civ4 main menu (when you load up the game), then any changes to the Civilopedia wont be seen until you either restart the game, or actually start a game.

However, if you are in a game, and you alt-tab back to the desktop, make changes to the Python files, then alt-tab back to Civ4, the Python files are reloaded and you see the changes immediately, and more importantly, Civ4 tells you at this point whether there's a problem loading any files.

As always, your mileage may vary, but in most cases development in Python should be fairly quick. No more restarting the whole game to see changes...


text:
Civ/Civilization IV/Modding/Tutorials/Python Tutorial

Contents

 * Page 1: Introduction
 * Page 2: The basics
 * Page 3: Using the API
 * Page 4: Event scripting & Interface mods
 * Page 5: Debugging
 * Page 6: Misc

Introduction
Python can be used to achieve a surprising amount of things in Civ 4, but only if you know how. Now, while I'm probably not the best person to be writing this tutorial, I feel I am quite familiar with the sort of things you can do to the game with it. Please feel free to edit anything I've got here, as the tutorial is far from complete. The tutorial is also on CFC here. Any updates on the wiki I will attempt to update there, though obviously the format is a bit stricter there.

If you want to know a little bit about python, I'd check out the wikipedia entry and the python website

Just a brief rundown on what python is capable of in Civ 4 terms:

Python can:
 * be used to make complex scripts causing events to happen on a trigger. For example, you can make it so that if you take the holy city of a religion, all Civs following that religion will declare war on you.
 * be used to edit the interface. Pretty much all of the game interface is generated dynamically by python, and can be edited in python. You can make new buttons, alter the layout of the Civelopedia, change the way the tech tree is generated... and even, if you so desire make a small dancing pig in the corner of your screen - with music (though I don't believe anybody has tried this, I'm pretty sure it's doable). There are limitation to this - mouseover texts, for example, are far better suited to the SDK.
 * be used to generate new map types. I haven't tried this myself, so it might not be covered too well in this tutorial.
 * be used to edit the AI... I'd do it with the SDK though, as it'll probably save a lot of time!

Python can't:
 * be used exactly how you might want to use it. While the amount of things you can do in it is really quite large, there are several things you just can't do. This is really quite annoying, but it's something you've got to learn to live with. The amount of things you can do is staggering, so don't complain. Hopefully with the release of the SDK more experienced coders will enhance the ability of python to change the way the game works.

Still reading? Good!

Now my suggestion for first steps would be to browse through GBM's python tutorial, which gives a brief outline of how to program in python. Also, if you have not done so, check out the python website which has lots of information about python (unsuprisingly). Finally, I'd check out this python tutorial by Jon (Trip) Shafer, Firaxis, who's tutorial you may find better than mine, after all, he is the guy who coded a lot of it in the first place.

The basics
As you should know by now, there are several different types of "thing" you can get in python: ints, floats, strings, and bools. You also might be aware of "pointers". I wasn't when I first came to python, so I'll give you a little heads-up about them.

Basically a pointer is a game entity. It can take the form of a unit, a plot (square), or a player. In the default python code, and in many modder's code, a variable is shown to be a pointer by prefacing it with "p". So pUnit will define a single unit in the game, pPlayer a single player.

Likewise, if a variable is prefaced with an "i" it is likely to be an integer (int) variable, and "b" a Boolean (bool) variable. iPlayer, for example, will probably be a player's individual ID number, rather then the pointer for the player.

It does sometimes get confusing, as most pointers have integers which are closely related to them. This method of naming things helps to avoid confusion in a language like python where variables need not be declared, however it is only a guideline, and just because a variable is named as if it were a certain type of variable, it won't necessarily be one.

I also would like to put a note here about "Types". In most xml entries you will need to enter something into a type field. This field is a very important link to python, though must be converted to an int for it to work properly. There is one function that you'll be finding yourself using over and over again, so I thought I'd put it here. This function will find the int corresponding to the type - and as most functions in the API (soon to come) will want the int value of the type it's very useful. For example: gc.getInfoTypeForString("TECH_MYSTICISM") will return the int corresponding to the tech Mysticism, which, as it is the first entry in the relevant xml file will be zero by default. gc.getInfoTypeForString("RELIGION_TAOISM") will return the int 6 by default, as it is the 7th religion listed.

If you don't get that last bit right now, don't worry - hopefully it'll come clear when you read the next section.

The API
The Civ 4 API is a list of all the functions specific to Civ 4 which interface with the actual game. There are two copies of the API. The first, by Locutus can be found here, and the second, by GBM can be found here. Locutus' API is up to date with the patch 1.60, so I suggest you use that one.

Now, in the past month or so answering questions on the forums about python I have noticed that quite a few people have had trouble reading the APIs. Interpreting what the functions do can be quite difficult, however the APIs do give you lots of hints, if you care to read them.

I'll use Locutus' API as an example, as I feel the interface is better, so open it up!

Classes
Firstly, we have the classes. These list all the functions that can be done to a specific entity, or pointer. For example, CyUnit lists all the functions that will work on a unit entity (a unit in the game). The classes are listed in the top-left hand frame. You will notice that there are several classes with a little "+" symbol by them. These classes are used for getting specific information directly from the xml files on an object.

Types
Now we have the types. These are the different types which can be extracted from the xml files. The int values shown are the default values, and while you could use them, and your code would most likely work, I would recommend against it, as if the order of the xml is changed in a future patch, your code will break. Instead I recommend using gc.getInfoTypeForString("") as shown above, as this is much more patch-compatible.

Functions
Finally we have the functions. Each class has its own set of functions which must be done to that class and that class only. If you try to take a function from a class, and use it on a different class it won't work. The functions are the main bit of the API, the stuff you want to know.

Now, there are lots of different functions. Most of the functions don't "do" anything in the game, instead they get a value from your pointer which you can use in an equation. If you look on the left hand side of the function, it will show you what this function returns. For example, if you used: BOOL CyPlayer.canChangeReligion it would not set the player able to change religion, instead it would return a BOOL, a true or false value depending on weather the player can or can't. See what I mean about it not "doing" anything?

Things a function can return are:
 * Bool - true or false, 1 or 0
 * Int - an integer value (can be negative) (256 for example)
 * Float - a floating point number (1.3423 for example)
 * String - a string ("The cat sat on the mat")
 * Turple - a list ([1, 4, 2, 8, 2])
 * Void - see below

The functions that do "do" things return a "VOID" - meaning that they setting rather than getting data. These functions are the most important ones really, as you can't do much without them, and unfortunately there aren't really enough of them to do everything you would want. Sorry, but that's just the way it is.

So, you know what a function returns, but that's not all you need to know. You also need to know what information to give it to return this data. Some functions don't require any inputs. CyUnit.canMove for example doesn't need to know anything apart from which unit it's checking to see if can move (the unit pointer should be in the place of the CyUnit). However, most functions aren't this simple, and require an input to create an output.

Let's take, for example: CyUnit.setHasPromotion(PromotionType eIndex, BOOL bNewValue) This function takes two arguments (inputs), the promotion type you want to give to the unit, and a bool value of weather to take, or remove the promotion. To give an example: pUnit.setHasPromotion(gc.getInfoTypeForString("PROMOTION_COMBAT1"), 1) would give the pointer, pUnit the promotion combat 1. Note that it is important to give the int value of the promotion in this case, as when the function asks for a type, it really wants an int... don't ask! As luck would have it, if you put the wrong arguments into a function python will tell you when trying to run the function. More about this in the debugging section!

CyGlobalContext
Commonly abbreviated to gc in files this is probably the most useful class, as it contains all the general Civ 4 related functions. GlobalContext is unique in that it doesn't have to be called with a pointer, but is a standalone class for getting information.

It has a number of useful purposes: gc.getInfoTypeForString("TECH_MYSTICISM") would get the int value for Mysticism.
 * As I have said before you can use it to get integers from types. For example:

gc.getPlayer(0) would return the pPlayer pointer for the the player with an ID of zero.
 * You can use it to get from an integer ID to a pointer. For example:

gc.getPromotionInfo("PROMOTION_COMBAT1") would return the pointer for the combat 1 promotion, which could then be used with CvPromotionInfo to get information about that specific promotion.
 * You can use it to get info from xml files. For example

gc.getActivePlayer
 * A common usage is to get the active player pointer, which returns the pointer of the player whose turn it is:

gc.getNumPromotionInfos would return the number of promotions which are available in the game. This is very useful for if you want to cycle through the promotions and check if a unit has them, activating a new function if it does.
 * The final major use is to get the number of instances of a certain thing. For example:

While there are other uses for CyGlobalContext, they are a bit to numerous to list here. I've tried to list what I think are the major ones.

Events
Events are things which occur due to certain triggers. There is only certain amount of fixed triggers, and this ties down modders slightly, however the triggers will accommodate most scripts. If you open up CvEventManager.py, the event triggers run from line 193 down to line 747 (patch 1.52). There are nearly 60 different triggers that can be used, ranging from onUpdate which runs every frame (probably about 30 times a second), to onGameStart which runs only once, at the start of the game.

Most triggers have arguments associated with them. These arguments are stored in the argsList. Under most event headers these arguments are defined. It's usually pretty obvious what they do.

Perhaps the simplest method of adding events on triggers is to just to add the event into the events manager. This will work for small mods, although it raises certain compatibility issues. A better way of doing it is to create your own CvCustomEventManager file. I recommend Dr Elmer Jiggle's event manager (found here). It's a bit tricky to understand at first, but well worth it if you can get it working. For examples of it in action I'd check out any of TheLopez's ModComps (look in this forum).

Things to note
 * The onEndPlayerTurn tigger does not occur at the end of a player's turn, instead it occurs at the end of the start of a player's turn, after all the cities have built, etc. If you want to do an event on the end of a player's turn you'll probably have to bodge up some code to do it at the start of the next player's turn. It would appear something similar goes on with onBeginGameTurn, and onEndGameTurn, although both occur at the END of the game turn rather than at the beginning like the player ones. Thanks to Kael for spotting this.

Example
 * If, for instance, you wanted a message to come up on every player's screen at the start of every game turn (in other words, at the start of the first player's turn), you could replace this code in the event manager:

def onBeginGameTurn(self, argsList): 'Called at the beginning of the end of each turn' iGameTurn = argsList[0] CvTopCivs.CvTopCivs.turnChecker(iGameTurn)

with the following code:

def onBeginGameTurn(self, argsList): 'Called at the beginning of the end of each turn' iGameTurn = argsList[0] CyInterface.addImmediateMessage("You have just started a new turn", "") # Adds the message "You have just started a new turn" with no sound attached. CvTopCivs.CvTopCivs.turnChecker(iGameTurn)

''NOTE: When making a formal mod you shouldn't simply add stuff to the event manager like this as it can cause compatibility issues. Check out the custom event manager linked to above.''

Interface
As I mentioned in the introduction almost all of the GUI is created dynamically either when you enter the relevant screen, or at the start of the game. Just about all of it is moddable. The files for modding the interface are in .../Assets/Python/Screens.

Things to note
 * When placing items in the interface that the x and y co-ords that you enter will correspond to the top left hand corner of the item.

CyGInterfaceScreen.getXResolution or CyGInterfaceScreen.getYResolution
 * Remember that the resolution can change. It may often be a good idea to change how your interface displays depending on the resolution. To find the X and Y resolutions you can use the code:

 * If an item needs a name, that name must be unique to that item, or strange things start to happen.

 * The way the techchooser script is written can make it quite hard to mod. Instead of being generated everytime you load up the screen, the techchooser is instead generated at the start of the game, and then only the colour changes are done in-game. To stop this happening in game, and to ensure that the techchooser shows the mods you make to it while you're game is running I suggest you comment out line 72 (screen.setPersistent(True)). This will make the techchooser be constantly regenerated while open, and although this may cause your computer to slow slightly, it should work better. Sometimes though, due to the way it is generated for techchooser mods you will have to restart the game to see any changes.

Debugging
I would appreciate it if somebody could check over this section as I'm not certain as to all of it's accuracy, and cannot test it as I will be away from my computer for the next few months

Everybody has to do debugging when their scripts don't work, as it is so easy to make one little mistake, causing the whole code to make no sence. The first step in debugging is to switch the in-game debugging options on. To do this, open up Civilization4.ini (make sure to back it up), and change the following entries to the following values: HidePythonExceptions = 0 ShowPythonDebugMsgs = 1 LoggingEnabled = 1 MessageLog = 1 This should enable in-game python popups, and cause all errors and messages to be printed in your My Documents/My Games/Civilization 4/Logs directory. The three important logs to look for when debugging are PythonDbg, PythonErr and PythonErr2.

Common error messages and their causes:
In the logs usually the errors will have a traceback on them. This traceback lists all the files that are effected by the error, and the lines the error occur on. The lase line is usually the one you are interested in, as this is the one where the error occurs. Sometimes you'll have to go back a few steps as the error won't be on the last line, but usually it is!

Syntax errors:
These are mainly typing errors - missed ":"s, incorrect whitespace, or bad bracketing. The game usually picks up on these when you load it up. The error logs should show you exactly where the error is in the syntax with a little ^ symbol underneath it.

Argument errors:
If you try to use a function designed for a pointer on an integer value, you will get a type error. Go to the line specified and check that the function you're are using is valid. Usually it will say what type of function it is expecting, and what you've given it. NOTE: Some classes need after them in functions, some don't. If you are getting a Type Error this may be the cause.

Type Errors:
These either occur when you are passing a function too many, or too few arguments. You have to make sure the amount of arguments you are passing a function matches the amount of arguments it takes, or the function will throw up an error when you try to run it.

Name Errors:
This means that you've tried to use something that the game doesn't know what is. For example, if you were to type a = b without first saying what b was, there is no way the computer could set a vale to a. Remember a=b does not do the same as b=a. Also, make sure you haven't any "==" where you want "=", or vice versa.

Sometimes you'll get "Argument referenced before assignment". I don't know if this goes alongside the Name Error, if it needs it's own category, but basically it's like a name error, but you define "a" later on in your code.

"List index out of range"
This happens when you try and reference a index in a list, turple, or dictionary which doesn't exist. This one can be tough, and you might have to use methods described in the next part of this section to see exactly what is going wrong.

That's all the error messages I can think of right now. I'm pretty sure there are one or two I've forgotten - if you find any please feel free to ask and I'll include them here. As I said at the start I'm not 100% certain on the accuracy of these, but they should be ok.

Code not behaving
So you've written your code. It all functions with no errors... but it doesn't actually produce the results you expect it to in the game. There can be several causes of this:

Firstly, if you think a piece of code should be having an effect in the game, make sure that it is by checking the API to see if it is a VOID function. It's quite a common mistake when first starting out to use other functions thinking that they will do something, when in fact they just retrieve information.

Secondly, if everything seems right you need to start putting debug messages in. This section brings you back right to the very start of python coding, when you were telling your computer to print "hello world". What you will need to do is to get the computer to print a message telling you what a certain value is at a certain point in the code, and compare it to what you think it should be. For example, the following code will print "a=b" in the debugging log if a=b, and print the values of a and b otherwise: if a == b: 	print "a=b" else: print a 	print b This can be quite hard to decypher in the debug log (often you will have many many numbers), so you can do more advanced messages if a == b: 	print "a = b, a and b are %d, and %d"%(a,b)) else: 	print("a = %d"%(a)) 	print("b = %d"%(b)) Where %d will reference the number outside the "" after the %. If you want to place a string there you have to use %s. This can give you detailed information as to exactly what is going on inside your code, and hopefully from that you should be able to see what is going wrong with it.

Misc
This page contains other stuff about Civ 4 python that isn't really covered in the other posts, and is not obvious at first glance. Some of it is fan-made - creating shortcuts to do some quite complicated things.

PyHelpers.py:
Most python files import this file. Basically it adds a few shortcuts to some more complicated functions. If you can't find exactly what you want in the API there is a chance that this file might be able to help you - though it only really creates shortcuts, and still follows the API.

CvGameUtils.py:
This file is used when deciding certain things, like what can/cannot be built. It can be used to interrupt some basic game functions. Normally each function returns "False", but if you were to make it return "True" under some certain conditions on those conditions the unit, for example, could be removed from the list of units available. You could use this to make having the slavery civic make a slave unit be buildable, for example. I'd check it out yourself to see exactly how much power you have in there.

Scriptdata:
If you want to add additional information about certain parts of the game world you need scriptdata. For example, if you want a unit to use up "ammo" everytime it fought, and then have to return to a city with an armoury to resupply, or maybe you want plots to become muddy if too many units travel on them without roads, you need scriptdata.

If you want to play around with scriptdata, I recommend getting Stone-D's excellent SD-Toolkit. This toolkit allows you to attach pieces of data to parts of the game. Each part must be identified with a unique mod-name (for compatibility).

NOTE: There is an improved version of the toolkit posted on this post on CFC by Teg_Navanis. This version is faster than the default version, and fixes several minor issues the default had.

Action Buttons:
talchas has released an | Action Button's Utility Mod which is a template for adding buttons to the GUI to do custom functions when pressed. The AI will have no clue about it.

Square Selection:
Once again by talchas | this mod is a template. With suitable modification this could be used to make artilliary act exactly as Civ 3 artilliary, with no bodges. Once again, AI shortcomings come in.

.ini file modifications:
While I have not actually tried it myself, there is a mod by Dr Elmer Jiggle which allows you to add variables to a mod's .ini file. | Get it here


text:
Civ/Civilization IV/Modding/Tutorials/Python Tutorial/Introduction

Contents:

 * Page 1: Introduction
 * Page 2: The basics
 * Page 3: Using the API
 * Page 4: Event scripting & Interface mods
 * Page 5: Debugging
 * Page 6: Misc

Introduction
Python can be used to achieve a surprising amount of things in Civ 4, but only if you know how. Now, while I'm probably not the best person to be writing this tutorial, I feel I am quite familiar with the sort of things you can do to the game with it. Please feel free to edit anything I've got here, as the tutorial is far from complete. The tutorial is also on CFC here. Any updates on the wiki I will attempt to update there, though obviously the format is a bit stricter there.

If you want to know a little bit about python, I'd check out the wikipedia entry and the python website

Just a brief rundown on what python is capable of in Civ 4 terms:

Python can:
 * be used to make complex scripts causing events to happen on a trigger. For example, you can make it so that if you take the holy city of a religion, all Civs following that religion will declare war on you.
 * be used to edit the interface. Pretty much all of the game interface is generated dynamically by python, and can be edited in python. You can make new buttons, alter the layout of the Civelopedia, change the way the tech tree is generated... and even, if you so desire make a small dancing pig in the corner of your screen - with music (though I don't believe anybody has tried this, I'm pretty sure it's doable). There are limitation to this - mouseover texts, for example, are far better suited to the SDK.
 * be used to generate new map types. I haven't tried this myself, so it might not be covered too well in this tutorial.
 * be used to edit the AI... I'd do it with the SDK though, as it'll probably save a lot of time!

Python can't:
 * be used exactly how you might want to use it. While the amount of things you can do in it is really quite large, there are several things you just can't do. This is really quite annoying, but it's something you've got to learn to live with. The amount of things you can do is staggering, so don't complain. Hopefully with the release of the SDK more experienced coders will enhance the ability of python to change the way the game works.

Still reading? Good!

Now my suggestion for first steps would be to browse through GBM's python tutorial, which gives a brief outline of how to program in python. Also, if you have not done so, check out the python website which has lots of information about python (unsurprisingly). Finally, I'd check out this python tutorial by Jon (Trip) Shafer, Firaxis, who's tutorial you may find better than mine, after all, he is the guy who coded alot of it in the first place.

The basics
As you should know by now, there are several different types of "thing" you can get in python: ints, floats, strings, and bools. You also might be aware of "pointers". I wasn't when I first came to python, so I'll give you a little heads-up about them.

Basically a pointer is a game entity. It can take the form of a unit, a plot (square), or a player. In the default python code, and in many modder's code, a variable is shown to be a pointer by prefacing it with "p". So pUnit will define a single unit in the game, pPlayer a single player.

Likewise, if a variable is prefaced with an "i" it is likely to be an integer (int) variable, and "b" a Boolean (bool) variable. iPlayer, for example, will probably be a player's individual ID number, rather then the pointer for the player.

It does sometimes get confusing, as most pointers have integers which are closely related to them. This method of naming things helps to avoid confusion in a language like python where variables need not be declared, however it is only a guideline, and just because a variable is named as if it were a certain type of variable, it won't necessarily be one.

I also would like to put a note here about "Types". In most xml entries you will need to enter something into a type field. This field is a very important link to python, though must be converted to an int for it to work properly. There is one function that you'll be finding yourself using over and over again, so I thought I'd put it here. This function will find the int corresponding to the type - and as most functions in the API (soon to come) will want the int value of the type it's very useful. For example: gc.getInfoTypeForString("TECH_MYSTICISM") will return the int corresponding to the tech Mysticism, which, as it is the first entry in the relevant xml file will be zero by default. gc.getInfoTypeForString("RELIGION_TAOISM") will return the int 6 by default, as it is the 7th religion listed.

If you don't get that last bit right now, don't worry - hopefully it'll come clear when you read the next section.

The API
The Civ 4 API is a list of all the functions specific to Civ 4 which interface with the actual game. There are two copies of the API. The first, by Locutus can be found here, and the second, by GBM can be found here. Locutus' API is up to date with the patch 1.60, so I suggest you use that one.

Now, in the past month or so answering questions on the forums about python I have noticed that quite a few people have had trouble reading the APIs. Interpreting what the functions do can be quite difficult, however the APIs do give you lots of hints, if you care to read them.

I'll use Locutus' API as an example, as I feel the interface is better, so open it up!

Classes
Firstly, we have the classes. These list all the functions that can be done to a specific entity, or pointer. For example, CyUnit lists all the functions that will work on a unit entity (a unit in the game). The classes are listed in the top-left hand frame. You will notice that there are several classes with a little "+" symbol by them. These classes are used for getting specific information directly from the xml files on an object.

Types
Now we have the types. These are the different types which can be extracted from the xml files. The int values shown are the default values, and while you could use them, and your code would most likely work, I would recommend against it, as if the order of the xml is changed in a future patch, your code will break. Instead I recommend using gc.getInfoTypeForString("") as shown above, as this is much more patch-compatible.

Functions
Finally we have the functions. Each class has its own set of functions which must be done to that class and that class only. If you try to take a function from a class, and use it on a different class it won't work. The functions are the main bit of the API, the stuff you want to know.

Now, there are lots of different functions. Most of the functions don't "do" anything in the game, instead they get a value from your pointer which you can use in an equation. If you look on the left hand side of the function, it will show you what this function returns. For example, if you used: BOOL CyPlayer.canChangeReligion it would not set the player able to change religion, instead it would return a BOOL, a true or false value depending on weather the player can or can't. See what I mean about it not "doing" anything?

Things a function can return are:
 * Bool - true or false, 1 or 0
 * Int - an integer value (can be negative) (256 for example)
 * Float - a floating point number (1.3423 for example)
 * String - a string ("The cat sat on the mat")
 * Turple - a list ([1, 4, 2, 8, 2])
 * Void - see below

The functions that do "do" things return a "VOID" - meaning that they setting rather than getting data. These functions are the most important ones really, as you can't do much without them, and unfortunately there aren't really enough of them to do everything you would want. Sorry, but that's just the way it is.

So, you know what a function returns, but that's not all you need to know. You also need to know what information to give it to return this data. Some functions don't require any inputs. CyUnit.canMove for example doesn't need to know anything apart from which unit it's checking to see if can move (the unit pointer should be in the place of the CyUnit). However, most functions aren't this simple, and require an input to create an output.

Let's take, for example: CyUnit.setHasPromotion(PromotionType eIndex, BOOL bNewValue) This function takes two arguments (inputs), the promotion type you want to give to the unit, and a bool value of weather to take, or remove the promotion. To give an example: pUnit.setHasPromotion(gc.getInfoTypeForString("PROMOTION_COMBAT1"), 1) would give the pointer, pUnit the promotion combat 1. Note that it is important to give the int value of the promotion in this case, as when the function asks for a type, it really wants an int... don't ask! As luck would have it, if you put the wrong arguments into a function python will tell you when trying to run the function. More about this in the debugging section!

CyGlobalContext
Commonly abbreviated to gc in files this is probably the most useful class, as it contains all the general Civ 4 related functions. GlobalContext is unique in that it doesn't have to be called with a pointer, but is a standalone class for getting information.

It has a number of useful purposes: gc.getInfoTypeForString("TECH_MYSTICISM") would get the int value for Mysticism.
 * As I have said before you can use it to get integers from types. For example:

 * You can use it to get from an integer ID to a pointer. For example:[code]gc.getPlayer(0)[/code] would return the pPlayer pointer for the the player with an ID of zero.

gc.getPromotionInfo("PROMOTION_COMBAT1") would return the pointer for the combat 1 promotion, which could then be used with CvPromotionInfo to get information about that specific promotion.
 * You can use it to get info from xml files. For example

gc.getActivePlayer
 * A common usage is to get the active player pointer, which returns the pointer of the player whose turn it is:

gc.getNumPromotionInfos would return the number of promotions which are available in the game. This is very useful for if you want to cycle through the promotions and check if a unit has them, activating a new function if it does.
 * The final major use is to get the number of instances of a certain thing. For example:

While there are other uses for CyGlobalContext, they are a bit to numerous to list here. I've tried to list what I think are the major ones.

Events
Events are things which occur due to certain triggers. There is only certain amount of fixed triggers, and this ties down modders slightly, however the triggers will accommodate most scripts. If you open up CvEventManager.py, the event triggers run from line 193 down to line 747 (patch 1.52). There are nearly 60 different triggers that can be used, ranging from onUpdate which runs every frame (probably about 30 times a second), to onGameStart which runs only once, at the start of the game.

Most triggers have arguments associated with them. These arguments are stored in the argsList. Under most event headers these arguments are defined. It's usually pretty obvious what they do.

Perhaps the simplest method of adding events on triggers is to just to add the event into the events manager. This will work for small mods, although it raises certain compatibility issues. A better way of doing it is to create your own CvCustomEventManager file. I recommend Dr Elmer Jiggle's event manager (found here). It's a bit tricky to understand at first, but well worth it if you can get it working. For examples of it in action I'd check out any of TheLopez's ModComps (look in this forum).

Things to note
 * The onEndPlayerTurn trigger does not occur at the end of a player's turn, instead it occurs at the end of the start of a player's turn, after all the cities have built, etc. If you want to do an event on the end of a player's turn you'll probably have to bodge up some code to do it at the start of the next player's turn. It would appear something similar goes on with onBeginGameTurn, and onEndGameTurn, although both occur at the END of the game turn rather than at the beginning like the player ones. Thanks to Kael for spotting this.

Example
 * If, for instance, you wanted a message to come up on every player's screen at the start of every game turn (in other words, at the start of the first player's turn), you could replace this code in the event manager:

def onBeginGameTurn(self, argsList): 'Called at the beginning of the end of each turn' iGameTurn = argsList[0] CvTopCivs.CvTopCivs.turnChecker(iGameTurn)

with the following code:

def onBeginGameTurn(self, argsList): 'Called at the beginning of the end of each turn' iGameTurn = argsList[0] CyInterface.addImmediateMessage("You have just started a new turn", "") # Adds the message "You have just started a new turn" with no sound attached. CvTopCivs.CvTopCivs.turnChecker(iGameTurn)

''NOTE: When making a formal mod you shouldn't simply add stuff to the event manager like this as it can cause compatibility issues. Check out the custom event manager linked to above.''

Interface
As I mentioned in the introduction almost all of the GUI is created dynamically either when you enter the relevant screen, or at the start of the game. Just about all of it is moddable. The files for modding the interface are in .../Assets/Python/Screens.

Things to note
 * When placing items in the interface that the x and y co-ords that you enter will correspond to the top left hand corner of the item.

CyGInterfaceScreen.getXResolution or CyGInterfaceScreen.getYResolution
 * Remember that the resolution can change. It may often be a good idea to change how your interface displays depending on the resolution. To find the X and Y resolutions you can use the code:

 * If an item needs a name, that name must be unique to that item, or strange things start to happen.

 * The way the techchooser script is written can make it quite hard to mod. Instead of being generated every time you load up the screen, the techchooser is instead generated at the start of the game, and then only the colour changes are done in-game. To stop this happening in game, and to ensure that the techchooser shows the mods you make to it while you're game is running I suggest you comment out line 72 (screen.setPersistent(True)). This will make the techchooser be constantly regenerated while open, and although this may cause your computer to slow slightly, it should work better. Sometimes though, due to the way it is generated for techchooser mods you will have to restart the game to see any changes.

Debugging
I would appreciate it if somebody could check over this section as I'm not certain as to all of it's accuracy, and cannot test it as I will be away from my computer for the next few months

Everybody has to do debugging when their scripts don't work, as it is so easy to make one little mistake, causing the whole code to make no sense. The first step in debugging is to switch the in-game debugging options on. To do this, open up Civilization4.ini (make sure to back it up), and change the following entries to the following values: HidePythonExceptions = 0 ShowPythonDebugMsgs = 1 LoggingEnabled = 1 MessageLog = 1 This should enable in-game python popups, and cause all errors and messages to be printed in your My Documents/My Games/Civilization 4/Logs directory. The three important logs to look for when debugging are PythonDbg, PythonErr and PythonErr2.

Common error messages and their causes:
In the logs usually the errors will have a traceback on them. This traceback lists all the files that are effected by the error, and the lines the error occur on. The lase line is usually the one you are interested in, as this is the one where the error occurs. Sometimes you'll have to go back a few steps as the error won't be on the last line, but usually it is!

Syntax errors:
These are mainly typing errors - missed ":"s, incorrect whitespace, or bad bracketing. The game usually picks up on these when you load it up. The error logs should show you exactly where the error is in the syntax with a little ^ symbol underneath it.

Argument errors:
If you try to use a function designed for a pointer on an integer value, you will get a type error. Go to the line specified and check that the function you're are using is valid. Usually it will say what type of function it is expecting, and what you've given it. NOTE: Some classes need after them in functions, some don't. If you are getting a Type Error this may be the cause.

Type Errors:
These either occur when you are passing a function too many, or too few arguments. You have to make sure the amount of arguments you are passing a function matches the amount of arguments it takes, or the function will throw up an error when you try to run it.

Name Errors:
This means that you've tried to use something that the game doesn't know what is. For example, if you were to type a = b without first saying what b was, there is no way the computer could set a vale to a. Remember a=b does not do the same as b=a. Also, make sure you haven't any "==" where you want "=", or vice versa.

Sometimes you'll get "Argument referenced before assignment". I don't know if this goes alongside the Name Error, if it needs it's own category, but basically it's like a name error, but you define "a" later on in your code.

"List index out of range"
This happens when you try and reference a index in a list, turple, or dictionary which doesn't exist. This one can be tough, and you might have to use methods described in the next part of this section to see exactly what is going wrong.

That's all the error messages I can think of right now. I'm pretty sure there are one or two I've forgotten - if you find any please feel free to ask and I'll include them here. As I said at the start I'm not 100% certain on the accuracy of these, but they should be ok.

Code not behaving
So you've written your code. It all functions with no errors... but it doesn't actually produce the results you expect it to in the game. There can be several causes of this:

Firstly, if you think a piece of code should be having an effect in the game, make sure that it is by checking the API to see if it is a VOID function. It's quite a common mistake when first starting out to use other functions thinking that they will do something, when in fact they just retrieve information.

Secondly, if everything seems right you need to start putting debug messages in. This section brings you back right to the very start of python coding, when you were telling your computer to print "hello world". What you will need to do is to get the computer to print a message telling you what a certain value is at a certain point in the code, and compare it to what you think it should be. For example, the following code will print "a=b" in the debugging log if a=b, and print the values of a and b otherwise: if a == b: 	print "a=b" else: print a 	print b This can be quite hard to decipher in the debug log (often you will have many many numbers), so you can do more advanced messages if a == b: 	print "a = b, a and b are %d, and %d"%(a,b)) else: 	print("a = %d"%(a)) 	print("b = %d"%(b)) Where %d will reference the number outside the "" after the %. If you want to place a string there you have to use %s. This can give you detailed information as to exactly what is going on inside your code, and hopefully from that you should be able to see what is going wrong with it.

Misc
This page contains other stuff about Civ 4 python that isn't really covered in the other posts, and is not obvious at first glance. Some of it is fan-made - creating shortcuts to do some quite complicated things.

PyHelpers.py:
Most python files import this file. Basically it adds a few shortcuts to some more complicated functions. If you can't find exactly what you want in the API there is a chance that this file might be able to help you - though it only really creates shortcuts, and still follows the API.

CvGameUtils.py:
This file is used when deciding certain things, like what can/cannot be built. It can be used to interrupt some basic game functions. Normally each function returns "False", but if you were to make it return "True" under some certain conditions on those conditions the unit, for example, could be removed from the list of units available. You could use this to make having the slavery civic make a slave unit be buildable, for example. I'd check it out yourself to see exactly how much power you have in there.

Scriptdata:
If you want to add additional information about certain parts of the game world you need scriptdata. For example, if you want a unit to use up "ammo" everytime it fought, and then have to return to a city with an armoury to resupply, or maybe you want plots to become muddy if too many units travel on them without roads, you need scriptdata.

If you want to play around with scriptdata, I recommend getting Stone-D's excellent SD-Toolkit. This toolkit allows you to attach pieces of data to parts of the game. Each part must be identified with a unique mod-name (for compatibility).

NOTE: There is an improved version of the toolkit posted on this post on CFC by Teg_Navanis. This version is faster than the default version, and fixes several minor issues the default had.

Action Buttons:
talchas has released an Action Button's Utility Mod which is a template for adding buttons to the GUI to do custom functions when pressed. The AI will have no clue about it.

Square Selection:
Once again by talchas this mod is a template. With suitable modification this could be used to make artillery act exactly as Civ 3 artillery, with no bodges. Once again, AI shortcomings come in.

.ini file modifications:
While I have not actually tried it myself, there is a mod by Dr Elmer Jiggle which allows you to add variables to a mod's .ini file. Get it here

Next page -->


text:
Civ/Civilization IV/Modding/Tutorials/Python Tutorial/Using the API

Contents

 * Page 1: Introduction
 * Page 2: The basics
 * Page 3: Using the API
 * Page 4: Event scripting & Interface mods
 * Page 5: Debugging
 * Page 6: Misc

The API
The Civ 4 API is a list of all the functions specific to Civ 4 which interface with the actual game. There are two copies of the API. The first, by Locutus can be found here, and the second, by GBM can be found here. Locutus' API is up to date with the latest patch, so I suggest you use that one.

Now, in the past month or so answering questions on the forums about python I have noticed that quite a few people have had trouble reading the APIs. Interpreting what the functions do can be quite difficult, however the APIs do give you lots of hints, if you care to read them.

Now, in the past month or so answering questions on the forums about python I have noticed that quite a few people have had trouble reading the APIs. Interpreting what the functions do can be quite difficult, however the APIs do give you lots of hints, if you care to read them.

I'll use Locutus' API as an example, as I feel the interface is better, so open it up!

Firstly, we have the classes. These list all the functions that can be done to a specific entity, or pointer. For example, CyUnit lists all the functions that will work on a unit entity (a unit in the game). The classes are listed in the top-left hand frame. You will notice that there are several classes with a little "+" symbol by them. These classes are used for getting specific information directly from the xml files on an object.

Now we have the types. These the different types which can be extracted from the xml files. The int values shown are the default values, and while you could use them, and your code would most likely work, I would recommend against it, as if the order of the xml is changed in a future patch, your code will break. Instead I recommend using gc.getInfoTypeForString("") as shown above, as this is much more patch-compatible.

Finally we have the functions. Each class has its own set of functions which must be done to that class and that class only. If you try to take a function from a class, and use it on a different class it won't work. The functions are the main bit of the API, the stuff you want to know.

Functions

Now, there are lots of different functions. Most of the functions don't "do" anything in the game, instead they get a value from your pointer which you can use in an equation. If you look on the left hand side of the function, it will show you what this function returns. For example, if you used: BOOL CyPlayer.canChangeReligion it would not set the player able to change religion, instead it would return a BOOL, a true or false value depending on whether the player can or can't. See what I mean about it not "doing" anything?

Things a function can return are:
 * Bool – true or false, 1 or 0
 * Int – an integer value (can be negative) (256 for example)
 * Float – a floating point number (1.3423 for example)
 * String – a string ("The cat sat on the mat")
 * Turple – a list ([1, 4, 2, 8, 2])
 * Void – see below

The functions that do "do" things return a "VOID" – meaning that they setting rather than getting data. These functions are the most important ones really, as you can't do much without them, and unfortunately there aren't really enough of them to do everything you would want. Sorry, but that's just the way it is.

So, you know what a function returns, but that's not all you need to know. You also need to know what information to give it to return this data. Some functions don't require any inputs. CyUnit.canMove for example doesn't need to know anything apart from which unit it's checking to see if can move (the unit pointer should be in the place of the CyUnit). However, most functions aren't this simple, and require an input to create an output.

Let's take, for example: CyUnit.setHasPromotion(PromotionType eIndex, BOOL bNewValue) This function takes two arguments (inputs), the promotion type you want to give to the unit, and a bool value of whether to take, or remove the promotion. To give an example: pUnit.setHasPromotion(gc.getInfoTypeForString("PROMOTION_COMBAT1"), 1) would give the pointer, pUnit the promotion combat 1. Note that it is important to give the int value of the promotion in this case, as when the function asks for a type, it really wants an int... don't ask! As luck would have it, if you put the wrong arguments into a function python will tell you when trying to run the function. More about this in the debugging section!

CyGlobalContext

Commonly abbreviated to gc in files this is probably the most useful class, as it contains all the general Civ 4 related functions. GlobalContext is unique in that it doesn't have to be called with a pointer, but is a standalone class for getting information.

It has a number of useful purposes: gc.getInfoTypeForString("TECH_MYSTICISM") would get the int value for Mysticism.
 * As I have said before you can use it to get integers from types. For example:

 * You can use it to get from an integer ID to a pointer. For example:[code]gc.getPlayer(0)[/code] would return the pPlayer pointer for the the player with an ID of zero.

gc.getPromotionInfo("PROMOTION_COMBAT1") would return the pointer for the combat 1 promotion, which could then be used with CvPromotionInfo to get information about that specific promotion.
 * You can use it to get info from xml files. For example

gc.getActivePlayer
 * A common usage is to get the active player pointer, which returns the pointer of the player whose turn it is:

gc.getNumPromotionInfos would return the number of promotions which are available in the game. This is very useful for if you want to cycle through the promotions and check if a unit has them, activating a new function if it does.
 * The final major use is to get the number of instances of a certain thing. For example:

While there are other uses for CyGlobalContext, they are a bit to numerous to list here. I've tried to list what I think are the major ones.

<--Previous Page Next page -->


text:
User talk:212.219.83.101

Welcome to Wikibooks. We invite everyone to contribute constructively to our collection. Take a look at the welcome page if you would like to learn more about contributing. However, unconstructive edits are considered vandalism, and if you continue in this manner you may be blocked from editing without further warning. Please stop, and consider improving rather than damaging the hard work of others. Thanks. -- Herby talk thyme 09:56, 20 February 2007 (UTC)

Block
This is a school shared ip with hundreds of users, it would be a good idea to block editing.

thanks RD12D

title: User talk:212.219.83.101


text:
Template:Haskell/Speaker 2

" "

title: Template:Haskell/Speaker 2


text:
Category:Book:Haskell/Templates

Note that we also use the following generic templates:
 * Template:Body note
 * Template:Exercises
 * Template:Auto category

title: Category:Book:Haskell/Templates


text:
Haskell/Solutions/Variables and functions

One approach for the Giza problem is starting from the pyramid volume and the estimated stone volume. Using general functions for the task, that might look like this in GHCi:

Prelude> let volumeBox w h d = w * h * d -- Just as above. Prelude> let volumeSquarePyramid b h = b * b * h / 3 Prelude> volumeSquarePyramid 230.4 146.5 / volumeBox 1 1 1 2592276.48


text:
Category:Book:Haskell/Solutions

Solutions to exercises. If you have found an answer that isn't in these articles, but you're sure is correct (by testing in the GHCi for example), please add it!

title: Category:Book:Haskell/Solutions


text:
Haskell/Solutions/Lists and tuples

Building lists

 * 1) This won't work. [True, False] is a list of booleans, 3 is an integer.
 * ,  and   are all valid functions.
 * 1)   returns
 * 2)   returns
 * 3)   gives a type error. This is the same mistake as in exercise 1.
 * 4)   gives no output message, but foo is  . Try it!
 * 5)   (assuming you did 2.4) returns
 * 6) As recognized   does not work, cause 8 is not a list, but   will work since (++) concatenates 2 lists
 * ,  are both valid functions.

Lists within lists

 * 1) 1 and 2 aren't valid Haskell, 3 is valid:
 * 2)  . ,   and   are integers, while   is a list.
 * 3)  . Again,   and   are integers, and   is a list of integers.
 * 4)  . This is valid Haskell, as   is a list of integers, and   is an empty list (of any type).
 * 5) The first four are valid Haskell. The fifth is not.
 * 6)  . Both   and   are lists of integers. The whole list is a list of lists of integers. We can cons an empty list (of any type) in front of it.
 * 7)  . Not the empty list!. This is a list containing an empty list. The list itself is not empty, because it has one element!
 * 8)  . This is a list containing two empty lists.
 * 9)  . This is the same list as the previous, but with a   as the first element instead of  . Since the list was a lists of lists, it now has become a list of list of integers.
 * 10)  . ["hi"] is a list of Chars while [1] is a list of integers.
 * 11) Yes, this is possible. For example:  . Why? You can make a list of anything! If you already have a list of some type, then you can make a list of lists of that type. The example list would be written as:
 * 12) The list   is not valid because it is equivalent to , where we try to cons elements that have different types (i.e. list and numeric). Lists in Haskell must be type-homogeneous. A valid list would be  , equivalent to.

A different notion of many

 * 1) They all are! Tuples aren't restricted to types.
 * 2) A tuple of two integers.
 * 3) A tuple of an integer and a string.
 * 4) A tuple of a boolean and two strings.
 * 5) The empty tuple   is pronounced "unit"
 * 6) Maybe the creators of Haskell wanted to limit the functionality of tuples to discourage their overuse. The practice of feeding functions cons-able tuples, instead of lists and tuples, may have made functions more complex, therefore harder to read, write and maintain.
 * 7) Unlike lists, we would obtain a tuple with a different type, because the tuple size would be bigger.
 * 1) Maybe the creators of Haskell wanted to limit the functionality of tuples to discourage their overuse. The practice of feeding functions cons-able tuples, instead of lists and tuples, may have made functions more complex, therefore harder to read, write and maintain.
 * 2) Unlike lists, we would obtain a tuple with a different type, because the tuple size would be bigger.

Tuples within lists and other combinations

 * 1) * Not valid.  is a tuple, and cons, , only works with lists.
 * 2) * Not valid.  is a tuple, and cons, , only works with lists.
 * 3) * Valid. You'll get a list of tuples of an integer and an integer:
 * 4) * Not valid. All elements of a list must be of the same type.  and   are tuples of an integer and an integer, but   is a tuple of a character and a character.
 * 5) * Valid. This is a tuple of a list of integers and a list of integers.
 * 1) * Valid. This is a tuple of a list of integers and a list of integers.

Retrieving values

 * 1)   returns.
 * 2) Yes, we can! The difference between a tuple and a list is that all elements of a list must be of the same type (integers, booleans, etc.), but you can add elements to the list. The elements of a tuple can be of any type you want, like a tuple of an integer and a character in , but you can't change its size.
 * 3)   Inconveniences of this implementation include the clunkiness of the definition, its lack of generality (what if we wanted to get the fourth or the sixth or the nineteenth element?), and the fact it will cause the program to crash whenever it is passed a list with less than five elements.
 * 1)   Inconveniences of this implementation include the clunkiness of the definition, its lack of generality (what if we wanted to get the fourth or the sixth or the nineteenth element?), and the fact it will cause the program to crash whenever it is passed a list with less than five elements.

title: Haskell/Solutions/Lists and tuples


text:
A-level Mathematics/OCR/FP2/Polar Coordinates

We have usually used cartesian co-ordinates(x,y).Polar coordinates are an alternative system which can describe position of a point.In polar co-ordinates any point can be described in terms of its distance and direction from a fixed point O.

Each point P in the plane is assigned polar coordinationates according to the following rules: r is the directed distance from O to P. θ is the directed angle between the polar axis (usually a ray from point O to the east) to the line OP.