chapter four

4 Maths, loops, conditions, and bits

 

This chapter covers

  • Let’s do some Maths.
  • 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, at making decisions (conditions), jumping to other places in your code, and then finally looking at 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 Maths

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 Add with carry.
clc    #A 
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.

Figure 4.1 Adding an 8-bit value to the A register.
A picture containing text, screenshot, font, rectangle Description automatically generated

4.1.2 Subtraction

4.1.3 Increasing and Decreasing

4.2 Conditions

4.3 Jumps, Branches, and Calls

4.3.1 Jumps

4.3.2 Branches

4.3.3 Calling a Subroutine

4.3.4 Labels

4.4 Bytes, Bits, and Nibbles

4.4.1 Bit Test

4.4.2 Logical Operations

4.4.3 Shift and Rotate Operations

4.5 Using the Stack

4.6 Summary