Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ops.go 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package intcode
  2. // ArgFunc provides the value of an argument for an opcode
  3. type ArgFunc = func(pos int) int
  4. // OpcodeFunc is a function that describes an opcode implemented in the VM.
  5. type OpcodeFunc = func(vm *VirtualMachine, param ArgFunc)
  6. // AddOpcode takes the values specified by args 1 and 2, adds them together, and stores at the memory address given
  7. // by arg 3.
  8. func AddOpcode(vm *VirtualMachine, arg ArgFunc) {
  9. vm.Memory[vm.Memory[vm.ip+3]] = arg(0) + arg(1)
  10. vm.ip += 4
  11. }
  12. // MulOpcode takes the values specified by args 1 and 2, multiplies them together, and stores at the memory address
  13. // given by arg 3.
  14. func MulOpcode(vm *VirtualMachine, arg ArgFunc) {
  15. vm.Memory[vm.Memory[vm.ip+3]] = arg(0) * arg(1)
  16. vm.ip += 4
  17. }
  18. // ReadOpCode reads a value from the input stream and stores it at the memory address given by arg 1.
  19. func ReadOpCode(vm *VirtualMachine, arg ArgFunc) {
  20. vm.Memory[vm.Memory[vm.ip+1]] = <-vm.Input
  21. vm.ip += 2
  22. }
  23. // WriteOpCode writes the value specified by the first argument to the output stream.
  24. func WriteOpCode(vm *VirtualMachine, arg ArgFunc) {
  25. vm.Output <- arg(0)
  26. vm.ip += 2
  27. }
  28. // JumpIfTrueOpCode checks if the first argument is not zero, and if so jumps to the second argument.
  29. func JumpIfTrueOpCode(vm *VirtualMachine, arg ArgFunc) {
  30. if arg(0) != 0 {
  31. vm.ip = arg(1)
  32. } else {
  33. vm.ip += 3
  34. }
  35. }
  36. // JumpIfFalseOpCode checks if the first argument is zero, and if so jumps to the second argument.
  37. func JumpIfFalseOpCode(vm *VirtualMachine, arg ArgFunc) {
  38. if arg(0) == 0 {
  39. vm.ip = arg(1)
  40. } else {
  41. vm.ip += 3
  42. }
  43. }
  44. // LessThanOpCode checks if the first argument is less than the second, and stores the result at the address given
  45. // by the third argument.
  46. func LessThanOpCode(vm *VirtualMachine, arg ArgFunc) {
  47. if arg(0) < arg(1) {
  48. vm.Memory[vm.Memory[vm.ip+3]] = 1
  49. } else {
  50. vm.Memory[vm.Memory[vm.ip+3]] = 0
  51. }
  52. vm.ip += 4
  53. }
  54. // EqualsOpCode checks if the first argument is equal to the second, and stores the result at the address given
  55. // by the third argument.
  56. func EqualsOpCode(vm *VirtualMachine, arg ArgFunc) {
  57. if arg(0) == arg(1) {
  58. vm.Memory[vm.Memory[vm.ip+3]] = 1
  59. } else {
  60. vm.Memory[vm.Memory[vm.ip+3]] = 0
  61. }
  62. vm.ip += 4
  63. }
  64. // HaltOpcode halts the VM and takes no arguments.
  65. func HaltOpcode(vm *VirtualMachine, arg ArgFunc) {
  66. vm.Halted = true
  67. }