Advertisement
Dugongue

Untitled

Nov 10th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. function new_node()
  2. return { state = nil, actions = nil, parent = nil, children = {}, value = 0, visits = 0 };
  3. end
  4.  
  5. function roulette(node)
  6. return (node.actions)[math.random(#(node.actions))]
  7. end
  8.  
  9. state_counter = 0;
  10.  
  11. function MonteCarlo(game, iterations)
  12.  
  13. tree = { root = new_node() };
  14. tree.root.state = state_counter;
  15. state_counter = state_counter + 1;
  16. savestate.save(tostring(0))
  17.  
  18. for i=1,iterations,1
  19. do
  20. curNode = tree.root;
  21. while (curNode.actions ~= nil) do
  22. nextAct = roulette(curNode);
  23. nextNode = curNode.children[nextAct];
  24. if (nextNode.visits == 0) then
  25. savestate.load(tostring(curNode.state))
  26. game.perform(nextAct);
  27. nextNode.state = state_counter;
  28. savestate.save(tostring(state_counter));
  29. state_counter = state_counter + 1;
  30. end
  31. nextNode.visits = nextNode.visits + 1;
  32. nextNode.parent = curNode;
  33. curNode = nextNode;
  34. end
  35. curNode.actions = game.expand(curNode)
  36. curNode.actions = {"R", "A"}
  37. score = game.rollout();
  38. while (curNode ~= nil) do
  39. curNode.value = curNode.value + score;
  40. curNode = curNode.parent;
  41. end
  42. end
  43. end
  44.  
  45. SuperMarioBros = {
  46. name = "Super Mario Bros.",
  47.  
  48. expand = function(node)
  49. acts = {"R", "A"}
  50. for i, act in ipairs(acts) do
  51. node.children[act] = new_node()
  52. end
  53. node.actions = {"R", "A"}
  54. end,
  55.  
  56. perform = function(act)
  57. if (act == "R") then
  58. --print("R")
  59. joypad.set({B = true, Right = true}, 1)
  60. emu.frameadvance()
  61. joypad.set({B = true, Right = true}, 1)
  62. emu.frameadvance()
  63. joypad.set({B = true, Right = true}, 1)
  64. emu.frameadvance()
  65. joypad.set({B = true, Right = true}, 1)
  66. emu.frameadvance()
  67. joypad.set({B = true, Right = true}, 1)
  68. emu.frameadvance()
  69. elseif (act == "A") then
  70. --print("A")
  71. joypad.set({B = true, Right = true, A = true}, 1)
  72. emu.frameadvance()
  73. joypad.set({B = true, Right = true, A = true}, 1)
  74. emu.frameadvance()
  75. joypad.set({B = true, Right = true, A = true}, 1)
  76. emu.frameadvance()
  77. joypad.set({B = true, Right = true, A = true}, 1)
  78. emu.frameadvance()
  79. joypad.set({B = true, Right = true, A = true}, 1)
  80. emu.frameadvance()
  81. end
  82.  
  83. end,
  84.  
  85. rollout = function()
  86. score = 0
  87. for i = 0,4,1 do
  88. score = score + math.pow(10,i) * mainmemory.readbyte(0x7DC - i)
  89. end
  90. return score;
  91. end,
  92. }
  93.  
  94. MonteCarlo(SuperMarioBros, 10000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement