4 Math, loops, conditions, and bits

 

This chapter covers

  • Doing some math
  • Conditions
  • Jumps, branches, and calls
  • Bytes, bits, and nibbles
  • Using the stack

In the last chapter, we covered loading and storing values between the registers in the CPU and memory. In this chapter, we will look at performing some simple math, making decisions (conditions), jumping to other places in your code, and then finally instructions that help us look at and change individual bits and use the special area of memory used for the stack.

4.1 Let’s do some math

Let’s do something with some numbers and some basic math operations. Math operations with computer processors are based on addition, subtraction, and manipulation of bits. Adding, subtracting, and changing bits are vital in game development, from changing object positions to working out what color or shape to make an enemy next. For this quick look, we will do some simple addition and subtraction to get you started.

4.1.1 Addition

To add two 8-bit numbers together, we must use the A register and the command ADC (ADd with Carry) as follows.

Listing 4.1 Adding with carry
clc              #1
adc <source>

This takes the current value of register A, adds the value from the source plus the value of the carry flag, and stores the result in A (see figure 4.1).

Figure 4.1 Adding an 8-bit value to the A register

4.1.2 Subtraction

4.2 Increasing and decreasing

4.3 Conditions

4.4 Jumps, branches, and calls

4.4.1 Jumps

4.4.2 Branches

4.4.3 Calling a subroutine

4.4.4 Labels

4.5 Bytes, bits, and nibbles

4.5.1 Bit test

4.5.2 Logical operations

4.6 Using the stack