Skip to content
This repository was archived by the owner on Oct 28, 2021. It is now read-only.

Commit 72d7e32

Browse files
author
Bill Lord
committed
cpu: switch to c++ rng and fix a bug in the rnd op
1 parent 1e70960 commit 72d7e32

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

src/Chip8.cpp

+2-4
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,8 @@
55
#include <sstream>
66
#include "Chip8.h"
77

8-
Chip8::Chip8() {
8+
Chip8::Chip8() : rng(device()), randomDistribution(0, 255) {
99
initState();
10-
// Seed RNG
11-
srand(static_cast<unsigned int>(time(nullptr)));
1210
}
1311

1412
void Chip8::initState() {
@@ -133,7 +131,7 @@ void Chip8::step() {
133131
state.pc = addr(opcode) + state.v[0];
134132
} else if (opidx(opcode) == 0xC) {
135133
// Random uint8 & Vx
136-
state.v[x(opcode)] &= rand() % 256; // C random is discouraged but should be fine for an insecure PRNG
134+
state.v[x(opcode)] = randomDistribution(rng) & lowByte(opcode);
137135
} else if (opidx(opcode) == 0xD) {
138136
// Read [nibble] bytes from RAM starting at $[register I] and XOR them into VRAM at (Vx, Vy), wrapping on OOB
139137
state.v[0xf] = 0; // set on sprite collision

src/Chip8.h

+4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include <array>
55
#include <cstdint>
6+
#include <random>
67
#include "Display.h"
78

89
constexpr int PROGRAM_OFFSET = 0x200;
@@ -67,6 +68,9 @@ class Chip8 {
6768
inline uint16_t x(uint16_t op) {return (op & 0x0F00) >> 8;} // 0X00
6869
inline uint16_t y(uint16_t op) {return (op & 0x00F0) >> 4;} // 00X0
6970
inline uint8_t lowByte(uint16_t op) {return uint8_t(op & 0x00FF);} // 00XX
71+
std::random_device device;
72+
std::mt19937 rng;
73+
std::uniform_int_distribution<int> randomDistribution;
7074
};
7175

7276
#endif //CHIP8_CHIP8_H

0 commit comments

Comments
 (0)