‘Ship in a Bottle‘ is a ‘Star Trek: The Next Generation’ episode (season six) where a sentient holodeck character, Professor James Moriarty, puts the Enterprise in jeopardy in his quest to be freed from confines of holographic environments.
Data and La Forge are enjoying a Sherlock Holmes holodeck program when the two notice that a character programmed to be left-handed was actually right-handed. They call Lt. Barclay to repair the holodeck, but as he checks the status of the Sherlock Holmes programs, he encounters an area of protected memory. He activates it to find the artificial sentient Professor James Moriarty character projected into the Holodeck, who appears to have memory since his creation (‘Elementary, Dear Data’ in season three: Geordi asks the holodeck to make a Sherlock Holmes villain that can defeat Data, creating a foe more powerful than originally planned).
Moriarty confuses the crew by seemingly willing himself to existence by walking off the holodeck. He creates a female companion for himself, and takes control of the Enterprise through the computer. Data observes that LaForge’s handedness is incorrect, just as they had experienced earlier, determining that he himself, Picard, and Barclay never left the holodeck, and everyone and everything that appears to be the Enterprise are part of a holodeck program Moriarty created. At that moment, Picard realizes that he has unwittingly provided Moriarty with the command codes for the Enterprise. With this information, Moriarty takes control of the real Enterprise from within his simulation.
Data finds a way to program the holodeck’s simulation of a holodeck to convince Moriarty that he and Regina can be beamed into the real world, though in fact they are only ‘beamed’ in the holodeck’s simulation. Moriarty, satisfied with the ruse, releases control of the ship back to Picard. He and the Countess use a shuttlecraft given to them by Picard to leave the Enterprise and explore the galaxy. Picard ends the simulation and returns to the real Enterprise. Barclay extracts the memory cube from the holodeck and sets it in an extended power device in order to provide Moriarty and the Countess a lifetime of exploration and adventure. Picard mentions the possibility that the crew’s reality may actually be a fabrication generated by ‘a little device sitting on someone’s table.’