1

I am trying to make a game where two scripts are running at the same time.

For example, one script takes in the user's inputs and other variables and the other script updates the screen,controls objects, and runs any needed tasks.

I need to be able to pass variables back and forth between the scripts while they are running.

Here is an example of my code:

main.py

#main
Num = 0
while True:
  if (#/up key is pressed/#):
    Num=1

control.py

#control script
while True:
  if main.Num==1:
     main.Num=0
     Move_object()

I have tried saving the data to a file then reading the data from another script but problems occur because, sometimes the scripts try to read the file at the same time and it causes my code to crash.

By having two or more scripts running simultaneously it splits the tasks and helps increase frame-rate because instead of one script processing all functions it shares the processes out between scripts.

Edit:

My only goal is to pass variables back and forth between the scripts while they are running.

Does anyone know how I could accomplish my goal?

Yolo Gamer
  • 35
  • 1
  • 1
  • 5

2 Answers2

0

This requires threading as it is two processes. The simplest way you can do this by having shared variables between the two threads Shared Values-Stack Overflow

If you want you can checkout about MUTEX, SEMAPHORE in multithreading which will help you handle multiple process accessing the same resource

Ajay Tom George
  • 1,031
  • 8
  • 19
  • i have thought of this but it seems like the functions need to be within the same file/script and what i'm trying to do is the same thing but from two different files/scripts – Yolo Gamer Mar 16 '20 at 11:18
  • You can use global variables and use them across https://stackoverflow.com/questions/13034496/using-global-variables-between-files. If program is breaking down, implement MUTEX. This is as far as I know about threads – Ajay Tom George Mar 16 '20 at 11:27
0

i found a rough solution the matches my criteria from a friend using mmap

main.py

import mmap

while True:
    a=mmap.mmap(0, 100, 'GlobalSharedMemory')    #get data/file
    inp=bytes(input(": "),"utf-8")    #gets input and changes to bytes
    a.write(inp)    # write inp to data/file

control.py

import mmap
while True:
  a=mmap.mmap(0, 100, 'GlobalSharedMemory')    #get data/file
  val=a.read().replace(b"\x00",b"")    #remove empty bytes
  if val != b"":    # if val is not empty
    print(val)    #print val
    a=mmap.mmap(0, 100, 'GlobalSharedMemory')    #get data/file
    a.write(b"\x00"*100)    #re-write data

the only problem with this solution is you can't directly edit variables from other scripts

Yolo Gamer
  • 35
  • 1
  • 1
  • 5