Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fs;
- struct CRT {
- // Devices
- cpu: CPU,
- gpu: GPU,
- // Registrars
- clock: f64,
- signal_strenght: f64,
- checkpoints: Vec<f64>,
- }
- struct CPU {
- current_instruction: usize,
- instruction_active: bool,
- register: f64,
- instructions: Vec<String>,
- shutdown: bool
- }
- struct GPU {
- width: i32,
- display: Vec<String>
- }
- impl CRT {
- fn new(instruction_set: Vec<String>, width: i32) -> CRT {
- CRT {
- cpu: CPU::new(instruction_set),
- gpu: GPU::new(width),
- clock: 1.0,
- signal_strenght: 0.0,
- checkpoints: vec![ 20.0, 60.0, 100.0, 140.0, 180.0, 220.0 ]
- }
- }
- fn start(&mut self) {
- while !self.cpu.shutdown {
- self.tick();
- }
- self.gpu.draw();
- println!("Signal Strenght: {}", self.signal_strenght);
- }
- fn tick(&mut self) {
- if self.checkpoints.contains(&self.clock) {
- self.signal_strenght += self.cpu.register * self.clock;
- }
- self.gpu.tick(self.clock, &self.cpu);
- self.cpu.tick(self.clock);
- self.clock += 1.0;
- }
- }
- impl CPU {
- fn new(instruction_set: Vec<String>) -> CPU {
- CPU { current_instruction: 0, instruction_active: false, register: 1.0, instructions: instruction_set, shutdown: false }
- }
- fn tick(&mut self, clock: f64) {
- if self.instructions.len() - 1 <= self.current_instruction {
- self.shutdown = true;
- }
- let instruction: Vec<&str> = self.instructions[self.current_instruction].split(" ").collect();
- if instruction[0] == "addx" {
- let value = instruction[1].parse::<f64>().expect(&format!("I{} - addx - FATAL: Unparseable Value", clock));
- if self.instruction_active {
- self.addx(value);
- self.instruction_active = false;
- self.current_instruction += 1;
- } else {
- self.instruction_active = true;
- }
- } else {
- self.noop();
- self.current_instruction += 1;
- }
- }
- fn addx(&mut self, value: f64) {
- self.register += value;
- }
- fn noop(&mut self) { }
- }
- impl GPU {
- fn new(width: i32) -> GPU {
- GPU { display: vec![], width: width }
- }
- fn tick(&mut self, clock: f64, cpu: &CPU) {
- let mut normalized_clock = clock - 1.0;
- while normalized_clock > 39.0 {
- normalized_clock -= 40.0;
- }
- let mut cur_pixel = String::from(".");
- let sprite = (cpu.register-1.1)..(cpu.register+1.1);
- if sprite.contains(&normalized_clock) {
- cur_pixel = String::from("#");
- }
- self.display.push(cur_pixel);
- }
- fn draw(&self) {
- let display_buffer = self.display.chunks(self.width as usize);
- for line in display_buffer {
- println!("{}", line.join(""));
- }
- }
- }
- fn main() {
- let raw_instructions = fs::read_to_string("source.txt").expect("Unable to read file");
- let instructions: Vec<String> = raw_instructions.lines().map(String::from).collect();
- let mut crt = CRT::new(instructions, 40 );
- crt.start();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement