Esempio n. 1
0
def ml_loop(side: str):
	init_pygame()

	print("Invisible joystick is used. " \
		"Press Enter to start the {} ml process.".format(side))
	while wait_enter_key():
		pass

	comm.ml_ready()

	while True:
		scene_info = comm.get_scene_info()

		if scene_info.status == GameStatus.GAME_1P_WIN or \
		   scene_info.status == GameStatus.GAME_2P_WIN:
			comm.ml_ready()
			continue

		key_pressed_list = pygame.key.get_pressed()
		if key_pressed_list[pygame.K_LEFT]:
			comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)
		elif key_pressed_list[pygame.K_RIGHT]:
			comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)
		else:
			comm.send_instruction(scene_info.frame, PlatformAction.NONE)

		pygame.event.pump()
Esempio n. 2
0
def ml_loop(side: str):

    filename = "forestTrained2P.sav"
    load_model = pickle.load(open(filename, 'rb'))
    comm.ml_ready()
    while True:
        scene_info = comm.get_scene_info()
        if scene_info.frame == 0:
            LastBallPos = scene_info.ball
    
        if scene_info.status == GameStatus.GAME_1P_WIN or \
            scene_info.status == GameStatus.GAME_2P_WIN:
            comm.ml_ready()
            continue
        Direction = (scene_info.ball[1] - LastBallPos[1]) / scene_info.ball_speed


        input_temp = np.array([scene_info.ball[0], scene_info.ball[1], scene_info.platform_2P[0], Direction])
        input = input_temp[np.newaxis, :]
        a = load_model.predict(input)
        #print(a)
        LastBallPos = scene_info.ball
        if a > 0:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)
        elif a < 0:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)
        else:
            comm.send_instruction(scene_info.frame, PlatformAction.NONE)
def ml_loop(side: str):
	"""
	The main loop for the machine learning process

	The `side` parameter can be used for switch the code for either of both sides,
	so you can write the code for both sides in the same script. Such as:
	```python
	if side == "1P":
		ml_loop_for_1P()
	else:
		ml_loop_for_2P()
	```

	@param side The side which this script is executed for. Either "1P" or "2P".
	"""

	# === Here is the execution order of the loop === #
	# 1. Put the initialization code here

	# 2. Inform the game process that ml process is ready
	comm.ml_ready()

	# 3. Start an endless loop
	while True:
		# 3.1. Receive the scene information sent from the game process
		scene_info = comm.get_scene_info()

		# 3.2. If either of two sides wins the game, do the updating or
		#      reseting stuff and inform the game process when the ml process
		#      is ready.
		if scene_info.status == GameStatus.GAME_1P_WIN or \
		   scene_info.status == GameStatus.GAME_2P_WIN:
			# Do something updating or reseting stuff

			# 3.2.1 Inform the game process that
			#       the ml process is ready for the next round
			comm.ml_ready()
			continue

		# 3.3 Put the code here to handle the scene information

		# 3.4 Send the instruction for this frame to the game process
		comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)
def ml_loop(side: str):
    """
	The main loop for the machine learning process

	The `side` parameter can be used for switch the code for either of both sides,
	so you can write the code for both sides in the same script. Such as:
	```python
	if side == "1P":
		ml_loop_for_1P()
	else:
		ml_loop_for_2P()
	```

	@param side The side which this script is executed for. Either "1P" or "2P".
	"""

    # === Here is the execution order of the loop === #
    # 1. Put the initialization code here
    c = 100
    d = 250
    LL2 = 0  #global variable
    # 2. Inform the game process that ml process is ready
    # filename1="pingpong_model_p1.sav"
    # load_model_p1=pickle.load(open(filename1, 'rb'))
    # filename2="pingpong_model_p2.sav"
    # load_model_p2=pickle.load(open(filename2, 'rb'))
    # comm.ml_ready()

    # 3. Start an endless loop
    if side == '1P':
        # filename="F74066365_p1_svm_ver3.sav"
        # load_model_p1=pickle.load(open(filename, 'rb'))
        filename = "F74066365_p1_svm_ver3.sav"
        filepath = os.path.join(os.path.dirname(__file__), filename)
        load_model_p1 = pickle.load(open(filepath, 'rb'))

        comm.ml_ready()

        while True:
            # 3.1. Receive the scene information sent from the game process
            scene_info = comm.get_scene_info()

            # 3.2. If either of two sides wins the game, do the updating or
            #      reseting stuff and inform the game process when the ml process
            #      is ready.
            if scene_info.status == GameStatus.GAME_1P_WIN or \
             scene_info.status == GameStatus.GAME_2P_WIN:
                # Do something updating or reseting stuff

                # 3.2.1 Inform the game process that
                #       the ml process is ready for the next round
                comm.ml_ready()
                continue

        # 3.3 Put the code here to handle the scene information
            a = c
            b = d
            c = scene_info.ball[0]
            d = scene_info.ball[1]

            # 3.4 Send the instruction for this frame to the game process
            inp_temp = np.array([c, d, (c - a), (d - b)])
            input = inp_temp[np.newaxis, :]
            L = load_model_p1.predict(input)

            if scene_info.platform_1P[0] + 20 > L + 3:  #+4  +2.5
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_LEFT)
            elif scene_info.platform_1P[0] + 20 < L + 2:  #+1  +2.5
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_RIGHT)
            else:
                comm.send_instruction(scene_info.frame, PlatformAction.NONE)

    else:
        # filename="F74066365_p2_svm_ver3.sav"
        # load_model_p2=pickle.load(open(filename, 'rb'))
        filename = "F74066365_p2_svm_ver3.sav"
        filepath = os.path.join(os.path.dirname(__file__), filename)
        load_model_p2 = pickle.load(open(filepath, 'rb'))

        comm.ml_ready()

        while True:
            # 3.1. Receive the scene information sent from the game process
            scene_info = comm.get_scene_info()

            # 3.2. If either of two sides wins the game, do the updating or
            #      reseting stuff and inform the game process when the ml process
            #      is ready.
            if scene_info.status == GameStatus.GAME_1P_WIN or \
             scene_info.status == GameStatus.GAME_2P_WIN:
                # Do something updating or reseting stuff

                # 3.2.1 Inform the game process that
                #       the ml process is ready for the next round
                comm.ml_ready()
                continue

        # 3.3 Put the code here to handle the scene information
            a = c
            b = d
            c = scene_info.ball[0]
            d = scene_info.ball[1]

            # 3.4 Send the instruction for this frame to the game process
            inp_temp = np.array([c, d, (c - a), (d - b)])
            input = inp_temp[np.newaxis, :]
            L = load_model_p2.predict(input)

            if scene_info.platform_2P[0] + 20 > L + 3:  #+4
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_LEFT)
            elif scene_info.platform_2P[0] + 20 < L + 2:  #+1
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_RIGHT)
            else:
                comm.send_instruction(scene_info.frame, PlatformAction.NONE)
def ml_loop(side: str):
    """
	The main loop for the machine learning process

	The `side` parameter can be used for switch the code for either of both sides,
	so you can write the code for both sides in the same script. Such as:
	```python
	if side == "1P":
		ml_loop_for_1P()
	else:
		ml_loop_for_2P()
	```

	@param side The side which this script is executed for. Either "1P" or "2P".
	"""

    # === Here is the execution order of the loop === #
    # 1. Put the initialization code here
    c = 100
    d = 250
    LL2 = 0  #global variable
    # 2. Inform the game process that ml process is ready
    comm.ml_ready()

    # 3. Start an endless loop
    if side == '1P':
        while True:
            # 3.1. Receive the scene information sent from the game process
            scene_info = comm.get_scene_info()

            # 3.2. If either of two sides wins the game, do the updating or
            #      reseting stuff and inform the game process when the ml process
            #      is ready.
            if scene_info.status == GameStatus.GAME_1P_WIN or \
             scene_info.status == GameStatus.GAME_2P_WIN:
                # Do something updating or reseting stuff

                # 3.2.1 Inform the game process that
                #       the ml process is ready for the next round
                comm.ml_ready()
                continue

        # 3.3 Put the code here to handle the scene information
            a = c
            b = d
            c = scene_info.ball[0]
            d = scene_info.ball[1]
            if c - a == 0:
                m = ((d - b) / 1)
            else:
                m = ((d - b) / (c - a))

        # 3.4 Send the instruction for this frame to the game process
            if d - b < 0:
                L = (80 - d + c * m) / m

                if L >= 0 and L <= 200:
                    L = L
                elif L < 0:
                    L = -L
                    num = L // 200
                    rr = L % 200
                    if num % 2 == 1:
                        L = 200 - rr
                    else:
                        L = rr
                elif L > 200:
                    L = L - 200
                    num = L // 200
                    rr = L % 200
                    if num % 2 == 1:
                        L = rr
                    else:
                        L = 200 - rr

                if scene_info.platform_1P[0] + 20 > L + 3:  #+4  +2.5
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.MOVE_LEFT)
                elif scene_info.platform_1P[0] + 20 < L + 2:  #+1  +2.5
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.MOVE_RIGHT)
                else:
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.NONE)
            else:
                if d < 215:
                    L = (215 - d + c * m) / m

                    if L >= 0 and L <= 200:
                        L = L
                    elif L < 0:
                        L = -L
                        num = L // 200
                        rr = L % 200
                        if num % 2 == 1:
                            L = 200 - rr
                        else:
                            L = rr
                    elif L > 200:
                        L = L - 200
                        num = L // 200
                        rr = L % 200
                        if num % 2 == 1:
                            L = rr
                        else:
                            L = 200 - rr

                    m2 = (-1 / m)
                    L2 = (80 - 215 + L * m2) / m2

                    if L2 >= 0 and L2 <= 200:
                        L2 = L2
                    elif L2 < 0:
                        L2 = -L2
                        num = L2 // 200
                        rr = L2 % 200
                        if num % 2 == 1:
                            L2 = 200 - rr
                        else:
                            L2 = rr
                    elif L2 > 200:
                        L2 = L2 - 200
                        num = L2 // 200
                        rr = L2 % 200
                        if num % 2 == 1:
                            L2 = rr
                        else:
                            L2 = 200 - rr

                    LL2 = L2

                    if scene_info.platform_1P[0] + 20 > L2 + 3:  #+4  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_LEFT)
                    elif scene_info.platform_1P[0] + 20 < L2 + 2:  #+1  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_RIGHT)
                    else:
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.NONE)
                else:
                    if scene_info.platform_1P[0] + 20 > LL2 + 3:  #+4  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_LEFT)
                    elif scene_info.platform_1P[0] + 20 < LL2 + 2:  #+1  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_RIGHT)
                    else:
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.NONE)

    else:
        while True:
            # 3.1. Receive the scene information sent from the game process
            scene_info = comm.get_scene_info()

            # 3.2. If either of two sides wins the game, do the updating or
            #      reseting stuff and inform the game process when the ml process
            #      is ready.
            if scene_info.status == GameStatus.GAME_1P_WIN or \
             scene_info.status == GameStatus.GAME_2P_WIN:
                # Do something updating or reseting stuff

                # 3.2.1 Inform the game process that
                #       the ml process is ready for the next round
                comm.ml_ready()
                continue

        # 3.3 Put the code here to handle the scene information
            a = c
            b = d
            c = scene_info.ball[0]
            d = scene_info.ball[1]
            if c - a == 0:
                m = ((d - b) / 1)
            else:
                m = ((d - b) / (c - a))

        # 3.4 Send the instruction for this frame to the game process
            if d - b > 0:
                L = (415 - d + c * m) / m

                if L >= 0 and L <= 200:
                    L = L
                elif L < 0:
                    L = -L
                    num = L // 200
                    rr = L % 200
                    if num % 2 == 1:
                        L = 200 - rr
                    else:
                        L = rr
                elif L > 200:
                    L = L - 200
                    num = L // 200
                    rr = L % 200
                    if num % 2 == 1:
                        L = rr
                    else:
                        L = 200 - rr

                if scene_info.platform_2P[0] + 20 > L + 3:  #+4
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.MOVE_LEFT)
                elif scene_info.platform_2P[0] + 20 < L + 2:  #+1
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.MOVE_RIGHT)
                else:
                    comm.send_instruction(scene_info.frame,
                                          PlatformAction.NONE)
            else:
                if d > 280:
                    L = (280 - d + c * m) / m

                    if L >= 0 and L <= 200:
                        L = L
                    elif L < 0:
                        L = -L
                        num = L // 200
                        rr = L % 200
                        if num % 2 == 1:
                            L = 200 - rr
                        else:
                            L = rr
                    elif L > 200:
                        L = L - 200
                        num = L // 200
                        rr = L % 200
                        if num % 2 == 1:
                            L = rr
                        else:
                            L = 200 - rr

                    m2 = (-1 / m)
                    #L2=(416-280+L*m2)/m2
                    L2 = (415 - 280 + L * m2) / m2

                    if L2 >= 0 and L2 <= 200:
                        L2 = L2
                    elif L2 < 0:
                        L2 = -L2
                        num = L2 // 200
                        rr = L2 % 200
                        if num % 2 == 1:
                            L2 = 200 - rr
                        else:
                            L2 = rr
                    elif L2 > 200:
                        L2 = L2 - 200
                        num = L2 // 200
                        rr = L2 % 200
                        if num % 2 == 1:
                            L2 = rr
                        else:
                            L2 = 200 - rr

                    LL2 = L2

                    if scene_info.platform_2P[0] + 20 > L2 + 3:  #+4  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_LEFT)
                    elif scene_info.platform_2P[0] + 20 < L2 + 2:  #+1  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_RIGHT)
                    else:
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.NONE)
                else:
                    if scene_info.platform_2P[0] + 20 > LL2 + 3:  #+4  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_LEFT)
                    elif scene_info.platform_2P[0] + 20 < LL2 + 2:  #+1  +2.5
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.MOVE_RIGHT)
                    else:
                        comm.send_instruction(scene_info.frame,
                                              PlatformAction.NONE)
Esempio n. 6
0
def ml_loop(side: str):

    err = 0
    all_infor = []
    ball_pos = (82, 107)
    #plateform_pos = (70, 400)

    #zipname='v1.zip'
    #filepath=os.path.join(os.path.dirname(__file__),zipname)
    #z = zipfile.ZipFile(filepath,'r')
    #m1_path = z.extract('newrf.sav')
    #s1_path = z.extract('newsc.sav')
    #z.close()

    m = pickle.load(open('p2rf_betta2.sav', 'rb'))
    s = pickle.load(open('p2sc_betta2.sav', 'rb'))
    comm.ml_ready()

    # 3. Start an endless loop.
    while True:

        # 3.1. Receive the scene information sent from the game process.
        scene_info = comm.get_scene_info()
        all_infor.append(scene_info)

        a1 = scene_info.ball[0]
        a2 = scene_info.ball[1]
        a3 = a1 - ball_pos[0]
        a4 = a2 - ball_pos[1]
        a5 = scene_info.platform_2P[0]
        input = [(a1, a2, a3, a4)]

        std_input = s.transform(input)
        pre_pos = m.predict(std_input) - 20

        #print("2P: ",scene_info.ball[0] - pre_pos[0]-20,input)
        if (scene_info.ball[1] == 415):
            if (scene_info.ball[0] != pre_pos[0] + 20):
                print("2P: ", scene_info.ball[0] - pre_pos[0] - 20)
                err += abs(scene_info.ball[0] - pre_pos[0] - 20)


        if scene_info.status == GameStatus.GAME_1P_WIN or \
        scene_info.status == GameStatus.GAME_2P_WIN:

            path = "C:/Users/User/Desktop/ping pong/MLGame-master/"
            with open(path + "P2_betta2.pickle", "rb") as f:
                model = pickle.load(f)
            model.read_file(all_infor, "P2", 1, 0)
            model.RandomForest()
            model.write_file(path + "p2rf_betta2.sav",
                             path + "p2sc_betta2.sav")
            pickle.dump(model, open(path + "P2_betta2.pickle", 'wb'))
            m = pickle.load(open('p2rf_betta2.sav', 'rb'))
            s = pickle.load(open('p2sc_betta2.sav', 'rb'))
            print("2p error: ", err)
            all_infor = []
            err = 0
            comm.ml_ready()
            continue

        if (pre_pos == a5):
            pass
            #comm.send_instruction(scene_info.frame, GameInstruction.CMD_NONE)

        elif (pre_pos < a5):
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)

        else:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)

        ball_pos = scene_info.ball
Esempio n. 7
0
def ml_loop(side: str):
	"""
	The main loop for the machine learning process

	The `side` parameter can be used for switch the code for either of both sides,
	so you can write the code for both sides in the same script. Such as:
	```python
	if side == "1P":
		ml_loop_for_1P()
	else:
		ml_loop_for_2P()
	```

	@param side The side which this script is executed for. Either "1P" or "2P".
	"""

	# === Here is the execution order of the loop === #
	# 1. Put the initialization code here
	x = 90
	y = 50
	flag = 2
	lastx = 75
	lasty = 100
	speed = 7
	# 2. Inform the game process that ml process is ready
	comm.ml_ready()
	
	# 3. Start an endless loop
	while True:
		# 3.1. Receive the scene information sent from the game process
		scene_info = comm.get_scene_info()

		# 3.2. If either of two sides wins the game, do the updating or
		#      reseting stuff and inform the game process when the ml process
		#      is ready.
		
		if scene_info.status == GameStatus.GAME_1P_WIN or \
		   scene_info.status == GameStatus.GAME_2P_WIN:
			# Do something updating or reseting stuff

			# 3.2.1 Inform the game process that
			#       the ml process is ready for the next round
			comm.ml_ready()
			continue

		# 3.3 Put the code here to handle the scene information
		
		x = scene_info.ball[0]
		y = scene_info.ball[1]	
		
		if lastx <= scene_info.ball[0] and lasty <= scene_info.ball[1]:
			flag = 1;
		elif lastx <= scene_info.ball[0] and lasty >= scene_info.ball[1]:
			flag = 2;
		elif lastx >= scene_info.ball[0] and lasty >= scene_info.ball[1]:
			flag = 3;
		elif lastx >= scene_info.ball[0] and lasty <= scene_info.ball[1]:
			flag = 4;
		speed = scene_info.ball_speed
		
		if flag==2 or flag==3:
			while y > 80:
				if x==0:
					if y-80<=195: 
						x = (y-80)//speed*speed
						y = y-(y-80)//speed*speed
						x = (x+speed) if (y>80) else x
						y = 80
					else:
						x = 195//speed*speed
						y = y-195//speed*speed
						y = (y-speed) if (x<195) else y
						x = 195
				elif x==195:
					if 195-(y-80)>=0:
						x = 195-(y-80)//speed*speed
						y = y-(y-80)//speed*speed
						x = (x-speed) if (y>80) else x
						y = 80
					else: 
						x = 195-195//speed*speed
						y = y-195//speed*speed
						y = (y-speed) if (x>0) else y
						x = 0
				elif flag == 2:
					if x+(y-80)<=195:
						x = x+(y-80)//speed*speed
						y = y-(y-80)//speed*speed
						x = (x+speed) if (y>80) else x
						y = 80
					else: 
						y = y-(195-x)//speed*speed
						x = x+(195-x)//speed*speed
						y = (y-speed) if (x<195) else y
						x = 195
				elif flag == 3:
					if y-80<=x:
						x = x-(y-80)//speed*speed
						y = y-(y-80)//speed*speed
						x = (x-speed) if (y>80) else x
						y = 80
					else: 
						y = y-x//speed*speed
						x = x-x//speed*speed
						y = (y-speed) if (x>0) else y
						x = 0
			x = x-(x%5)

		# 3.4 Send the instruction for this frame to the game process
		if scene_info.platform_1P[0]<x:
			comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)
		elif scene_info.platform_1P[0]>x:
			comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)
		elif scene_info.platform_1P[0]==x:
			comm.send_instruction(scene_info.frame, PlatformAction.NONE)
		#print(scene_info.ball[0], scene_info.ball[1], x, flag, speed, scene_info.platform_1P[0])
		lastx = scene_info.ball[0]
		lasty = scene_info.ball[1]
Esempio n. 8
0
def ml_loop(side: str):
    all_infor = []
    game = []
    ans = []
    pre = []
    e = []
    err = 0
    ball_pos = (82, 107)
    platform_pos2P = (80, 420)

    #zipname='v1.zip'
    #filepath=os.path.join(os.path.dirname(__file__),zipname)
    #z = zipfile.ZipFile(filepath,'r')
    #m1_path = z.extract('newrf.sav')
    #s1_path = z.extract('newsc.sav')
    #z.close()

    #p12 = train_model()
    m = pickle.load(open('p1rf_betta2.sav', 'rb'))
    s = pickle.load(open('p1sc_betta2.sav', 'rb'))
    comm.ml_ready()

    # 3. Start an endless loop.
    while True:

        # 3.1. Receive the scene information sent from the game process.
        scene_info = comm.get_scene_info()
        all_infor.append(scene_info)

        a1 = scene_info.ball[0]
        a2 = scene_info.ball[1]
        a3 = a1 - ball_pos[0]
        a4 = a2 - ball_pos[1]
        a5 = scene_info.platform_1P[0]
        #a6 = scene_info.platform_2P[0]
        #a7 = a6 - platform_pos2P[0]
        #input = [(a1, a2, a3, a4,a6,a7,scene_info.frame)]
        input = [(a1, a2, a3, a4)]

        #print(input)
        #std_input=m.scaler.transform(input)
        std_input = s.transform(input)
        pre_pos = m.predict(std_input) - 20
        #print(pre_pos)
        #print("1P: ",scene_info.ball[0] - pre_pos[0]-20,input)
        if (scene_info.ball[1] == 80):
            e.append(scene_info.ball[0] - pre_pos[0] - 20)
            ans.append(scene_info.ball[0])
            pre.append(pre_pos[0] + 20)
            if (scene_info.ball[0] != pre_pos[0] + 20):
                print("1P: ", scene_info.ball[0] - pre_pos[0] - 20)
                err += abs(scene_info.ball[0] - pre_pos[0] - 20)
            #print("1P: ",scene_info.ball[0],'vs',pre_pos[0]+20)
            #act.append(scene_info.ball[0])
            #pre.append(pre_pos+20)
            #minus.append(scene_info.ball[0]-int(pre_pos[0])-20)

        if scene_info.status == GameStatus.GAME_1P_WIN or \
        scene_info.status == GameStatus.GAME_2P_WIN:
            # Do something updating or reseting stuff

            # 3.2.1 Inform the game process that
            #       the ml process is ready for the next round# save game data

            path = "C:/Users/User/Desktop/ping pong/MLGame-master/"
            with open(path + "game_result.pickle", "rb") as d:
                game = pickle.load(d)
            with open(path + "P1_betta2.pickle", "rb") as f:
                model = pickle.load(f)

            model.read_file(all_infor, "P1", 1, 0)
            model.RandomForest()
            model.write_file(path + "p1rf_betta2.sav",
                             path + "p1sc_betta2.sav")
            pickle.dump(model, open(path + "P1_betta2.pickle", 'wb'))

            m = pickle.load(open('p1rf_betta2.sav', 'rb'))
            s = pickle.load(open('p1sc_betta2.sav', 'rb'))

            game.append((scene_info.frame, scene_info.ball_speed,
                         scene_info.status, err))
            pickle.dump(game, open(path + "game_result.pickle", 'wb'))

            pre = []
            e = []
            ans = []
            all_infor = []
            err = 0
            comm.ml_ready()
            continue

        if (pre_pos == a5):
            pass
            #comm.send_instruction(scene_info.frame, GameInstruction.CMD_NONE)

        elif (pre_pos < a5):
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)

        else:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)

        ball_pos = scene_info.ball
Esempio n. 9
0
def ml_loop(side: str):
    comm.ml_ready()
    if side == '1P':  # Upper
        while True:
            scene_info = comm.get_scene_info()
            ball = scene_info.ball
            speed = scene_info.ball_speed
            if scene_info.status == GameStatus.GAME_1P_WIN or \
                scene_info.status == GameStatus.GAME_2P_WIN:
                comm.ml_ready()
                continue
            if scene_info.frame == 0:
                last_scene_info = scene_info
                continue
            ## To caculate drop point
            if ball[1] > last_scene_info.ball[1]:  # ball leaving board(down)
                tickLeft = (680 - (ball[1] - 80)) / scene_info.ball_speed
                if (ball[0] - last_scene_info.ball[0] > 0):  # Going right
                    XDest = ball[0] + scene_info.ball_speed * tickLeft
                else:
                    XDest = ball[0] - scene_info.ball_speed * tickLeft
            else:  # ball going toward board
                tickLeft = (ball[1] - 80) / scene_info.ball_speed
                if (ball[0] - last_scene_info.ball[0] > 0):  # Going right
                    XDest = ball[0] + scene_info.ball_speed * tickLeft
                else:
                    XDest = ball[0] - scene_info.ball_speed * tickLeft
            if (math.floor(XDest / 200) % 2 == 1):
                XDest = 200 - (XDest % 200)
            else:
                XDest %= 200

            if scene_info.platform_1P[0] + 20 < XDest and abs(
                    scene_info.platform_1P[0] + 20 - XDest) >= 13:
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_RIGHT)
            elif scene_info.platform_1P[0] + 20 > XDest and abs(
                    scene_info.platform_1P[0] + 20 - XDest) >= 13:
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_LEFT)
            else:
                comm.send_instruction(scene_info.frame, PlatformAction.NONE)
            last_scene_info = scene_info

    else:  # Lower
        while True:
            scene_info = comm.get_scene_info()
            ball = scene_info.ball
            speed = scene_info.ball_speed
            if scene_info.status == GameStatus.GAME_1P_WIN or \
                scene_info.status == GameStatus.GAME_2P_WIN:
                comm.ml_ready()
                continue
            if scene_info.frame == 0:
                last_scene_info = scene_info
                continue
            ## To caculate drop point
            if ball[1] < last_scene_info.ball[1]:  # ball leaving board(up)
                tickLeft = (340 + (ball[1] - 80)) / scene_info.ball_speed
                if (ball[0] - last_scene_info.ball[0] > 0):  # Going right
                    XDest = ball[0] + scene_info.ball_speed * tickLeft
                else:
                    XDest = ball[0] - scene_info.ball_speed * tickLeft
            else:  # ball going toward board
                tickLeft = (420 - ball[1]) / scene_info.ball_speed
                if (ball[0] - last_scene_info.ball[0] > 0):  # Going right
                    XDest = ball[0] + scene_info.ball_speed * tickLeft
                else:
                    XDest = ball[0] - scene_info.ball_speed * tickLeft
            if (math.floor(XDest / 200) % 2 == 1):
                XDest = 200 - (XDest % 200)
            else:
                XDest %= 200
            if scene_info.platform_2P[0] + 20 < XDest and abs(
                    scene_info.platform_2P[0] + 20 - XDest) >= 13:
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_RIGHT)
            elif scene_info.platform_2P[0] + 20 > XDest and abs(
                    scene_info.platform_2P[0] + 20 - XDest) >= 13:
                comm.send_instruction(scene_info.frame,
                                      PlatformAction.MOVE_LEFT)
            else:
                comm.send_instruction(scene_info.frame, PlatformAction.NONE)
            last_scene_info = scene_info
Esempio n. 10
0
def ml_loop(side: str):
    """The main loop of the machine learning process

	This loop is run in a seperate process, and communicates with the game process.

	Note that the game process won't wait for the ml process to generate the
	GameInstrcution. It is possible that the frame of the GameInstruction
	is behind of the current frame in the game process. Try to decrease the fps
	to avoid this situation.
	"""

    # === Here is the execution order of the loop === #
    # 1. Put the initialization code here.
    lastx = 120
    lasty = 395
    flag = 1
    speed = 7
    # 2. Inform the game process that ml process is ready before start the loop.
    filename = "model_2.sav"
    load_model = pickle.load(open(filename, 'rb'))
    comm.ml_ready()
    # 3. Start an endless loop.
    while True:
        # 3.1. Receive the scene information sent from the game process.
        scene_info = comm.get_scene_info()

        # 3.2. If the game is over or passed, the game process will reset
        #      the scene immediately and send the scene information again.
        #      Therefore, receive the reset scene information.
        #      You can do proper actions, when the game is over or passed.
        if scene_info.status == GameStatus.GAME_1P_WIN or \
           scene_info.status == GameStatus.GAME_2P_WIN:
            # Do something updating or reseting stuff

            # 3.2.1 Inform the game process that
            #       the ml process is ready for the next round
            comm.ml_ready()
            continue

        # 3.3. Put the code here to handle the scene information
        if lastx <= scene_info.ball[0] and lasty <= scene_info.ball[1]:
            flag = 1
        elif lastx <= scene_info.ball[0] and lasty >= scene_info.ball[1]:
            flag = 2
        elif lastx >= scene_info.ball[0] and lasty >= scene_info.ball[1]:
            flag = 3
        elif lastx >= scene_info.ball[0] and lasty <= scene_info.ball[1]:
            flag = 4
        speed = scene_info.ball_speed
        inp_temp = np.array([
            lastx, lasty, scene_info.ball[0], scene_info.ball[1], flag, speed
        ])
        input = inp_temp[np.newaxis, :]
        instr = load_model.predict(input)
        instr = instr - (instr % 5)
        # 3.4. Send the instruction for this frame to the game process
        if scene_info.platform_2P[0] < instr:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_RIGHT)
        elif scene_info.platform_2P[0] > instr:
            comm.send_instruction(scene_info.frame, PlatformAction.MOVE_LEFT)
        elif scene_info.platform_2P[0] == instr:
            comm.send_instruction(scene_info.frame, PlatformAction.NONE)
        #print(instr, scene_info.ball[0], scene_info.ball[1], scene_info.platform_2P[0])
        lastx = scene_info.ball[0]
        lasty = scene_info.ball[1]