the code system of a new 'MO lock' is a regular $n$-gon,each vertex labelled a number $0$ or $1$ and coloured red or blue.it is known that for any two adjacent vertices,either their numbers or colours coincide.
find the number of all possible codes(in terms of $n$).
1. **Define the problem in terms of graph theory:**
   We need to find the number of possible codes for an $n$-gon where each vertex is labeled with a number (0 or 1) and colored (red or blue). The condition is that for any two adjacent vertices, either their numbers or colors coincide.

2. **Construct the adjacency matrix:**
   The adjacency matrix $M$ for the graph of four vertices (representing the combinations of number and color) is given by:
   \[
   M = \begin{pmatrix}
   1 & 1 & 1 & 0 \\
   1 & 1 & 0 & 1 \\
   1 & 0 & 1 & 1 \\
   0 & 1 & 1 & 1
   \end{pmatrix}
   \]
   This matrix represents the allowed transitions between the states (vertices).

3. **Decompose the matrix $M$:**
   We decompose $M$ as $M = U - J$, where:
   \[
   U = \begin{pmatrix}
   1 & 1 & 1 & 1 \\
   1 & 1 & 1 & 1 \\
   1 & 1 & 1 & 1 \\
   1 & 1 & 1 & 1
   \end{pmatrix}
   \]
   and
   \[
   J = \begin{pmatrix}
   0 & 0 & 0 & 1 \\
   0 & 0 & 1 & 0 \\
   0 & 1 & 0 & 0 \\
   1 & 0 & 0 & 0
   \end{pmatrix}
   \]

4. **Properties of $U$ and $J$:**
   - $U$ is a matrix where all entries are 1.
   - $J$ is a permutation matrix representing a cyclic shift.
   - $J^2 = I$ (the identity matrix), so $J$ is an involution.
   - $U^2 = 4U$ because each row of $U$ sums to 4.
   - $UJ = JU = U$ because $U$ is invariant under permutation.

5. **Trace of powers of $U$ and $J$:**
   - The trace of $U^k$ is $4^k$ because $U^k = 4^{k-1}U$ and the trace of $U$ is 4.
   - The trace of $J^k$ is $2 + (-1)^k \cdot 2$ because $J$ has eigenvalues 1 and -1.

6. **Calculate the trace of $M^n$:**
   Using the binomial theorem for matrices, we have:
   \[
   M^n = (U - J)^n = \sum_{k=0}^{n} \binom{n}{k} U^{n-k} (-J)^k
   \]
   Taking the trace, we get:
   \[
   \text{tr}(M^n) = \sum_{k=0}^{n} \binom{n}{k} \text{tr}(U^{n-k} (-J)^k)
   \]
   Since $\text{tr}(U^{n-k} (-J)^k) = 4^{n-k} \cdot (-1)^k \cdot \text{tr}(J^k)$, we have:
   \[
   \text{tr}(M^n) = \sum_{k=0}^{n} \binom{n}{k} 4^{n-k} (-1)^k (2 + (-1)^k \cdot 2)
   \]

7. **Simplify the expression:**
   - For even $k$, $\text{tr}(J^k) = 4$.
   - For odd $k$, $\text{tr}(J^k) = 0$.
   Therefore, the sum simplifies to:
   \[
   \text{tr}(M^n) = \sum_{k=0, \text{even}}^{n} \binom{n}{k} 4^{n-k} (-1)^k \cdot 4
   \]
   This can be further simplified using the binomial theorem.

8. **Final result:**
   After simplification, we find:
   \[
   \text{tr}(M^n) = 3^n + 3 \quad \text{if } n \text{ is even}
   \]
   \[
   \text{tr}(M^n) = 3^n + 1 \quad \text{if } n \text{ is odd}
   \]

The final answer is $\boxed{3^n + 3 \text{ if } n \text{ is even, and } 3^n + 1 \text{ if } n \text{ is odd}}$.