-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.py
162 lines (128 loc) · 6.12 KB
/
player.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import random
import numpy as np
import pygame
from variables import global_variables
from nn import NeuralNetwork
class Player(pygame.sprite.Sprite):
def __init__(self, game_mode):
super().__init__()
# loading images
player_walk1 = pygame.image.load('Graphics/Player/player_walk_1.png').convert_alpha()
player_walk2 = pygame.image.load('Graphics/Player/player_walk_2.png').convert_alpha()
# rotating -90 degree and scaling by factor of 0.5
player_walk1 = pygame.transform.rotozoom(player_walk1, -90, 0.5)
player_walk2 = pygame.transform.rotozoom(player_walk2, -90, 0.5)
# flipping vertically
player_walk1 = pygame.transform.flip(player_walk1, flip_x=False, flip_y=True)
player_walk2 = pygame.transform.flip(player_walk2, flip_x=False, flip_y=True)
self.player_walk = [player_walk1, player_walk2]
self.player_index = 0
self.image = self.player_walk[self.player_index]
self.rect = self.image.get_rect(midleft=(177, 656))
self.player_gravity = 'left'
self.gravity = 10
self.game_mode = game_mode
# choosing game mode
if self.game_mode == "Neuroevolution":
self.fitness = 0 # Initial fitness
# default layer size
layer_sizes = [6, 14, 2]
self.nn = NeuralNetwork(layer_sizes=layer_sizes)
def think(self, screen_width, screen_height, obstacles, player_x, player_y):
"""
Creates input vector of the neural network and determines the gravity according to neural network's output.
:param screen_width: Game's screen width which is 604.
:param screen_height: Game's screen height which is 800.
:param obstacles: List of obstacles that are above the player. Each entry is a dictionary having 'x' and 'y' of
the obstacle as the key. The list is sorted based on the obstacle's 'y' point on the screen. Hence, obstacles[0]
is the nearest obstacle to our player. It is also worthwhile noting that 'y' range is in [-100, 656], such that
-100 means it is offscreen (Topmost point) and 656 means in parallel to our player's 'y' point.
:param player_x: 'x' position of the player
:param player_y: 'y' position of the player
"""
# using the generate input layer function
# to create the inputs.
inp = self.generate_input_layer(screen_width, screen_height, obstacles, player_x, player_y)
output = self.nn.forward(inp)
if output[0] >= output[1]:
self.change_gravity('left')
else:
self.change_gravity('right')
def change_gravity(self, new_gravity):
"""
Changes the self.player_gravity based on the input parameter.
:param new_gravity: Either "left" or "right"
"""
new_gravity = new_gravity.lower()
if new_gravity != self.player_gravity:
self.player_gravity = new_gravity
self.flip_player_horizontally()
def player_input(self):
"""
In manual mode: After pressing space from the keyboard toggles player's gravity.
"""
if global_variables['events']:
for pygame_event in global_variables['events']:
if pygame_event.type == pygame.KEYDOWN:
if pygame_event.key == pygame.K_SPACE:
self.player_gravity = "left" if self.player_gravity == 'right' else 'right'
self.flip_player_horizontally()
def apply_gravity(self):
if self.player_gravity == 'left':
self.rect.x -= self.gravity
if self.rect.left <= 177:
self.rect.left = 177
else:
self.rect.x += self.gravity
if self.rect.right >= 430:
self.rect.right = 430
def animation_state(self):
"""
Animates the player.
After each execution, it increases player_index by 0.1. Therefore, after ten execution, it changes the
player_index and player's frame correspondingly.
"""
self.player_index += 0.1
if self.player_index >= len(self.player_walk):
self.player_index = 0
self.image = self.player_walk[int(self.player_index)]
def update(self):
"""
Updates the player according to the game_mode. If it is "Manual", it listens to the keyboard. Otherwise the
player changes its location based on `think` method.
"""
if self.game_mode == "Manual":
self.player_input()
if self.game_mode == "Neuroevolution":
obstacles = []
for obstacle in global_variables['obstacle_groups']:
if obstacle.rect.y <= 656:
obstacles.append({'x': obstacle.rect.x, 'y': obstacle.rect.y})
self.think(global_variables['screen_width'],
global_variables['screen_height'],
obstacles, self.rect.x, self.rect.y)
self.apply_gravity()
self.animation_state()
def flip_player_horizontally(self):
"""
Flips horizontally to have a better graphic after each jump.
"""
for i, player_surface in enumerate(self.player_walk):
self.player_walk[i] = pygame.transform.flip(player_surface, flip_x=True, flip_y=False)
"""
this mehtod is used to create input layer.
"""
def generate_input_layer(self, screen_width, screen_height, obstacles, player_x, player_y):
param = np.zeros((self.nn.layer_sizes[0], 1))
for i in range(min(len(obstacles), self.nn.layer_sizes[0] // 2)):
param[i * 2] = np.exp(self.nn.layer_sizes[0] - i) * (abs(obstacles[i]['x'] - player_x)) / screen_width
param[i * 2 + 1] = (player_y - obstacles[i]['y']) * np.exp(self.nn.layer_sizes[0] - i) / screen_height
param = self.normalize(param)
return param
@staticmethod
def normalize(param):
var = np.var(param)
mean = np.mean(param)
sqrt_var = np.sqrt(var)
param = (param - mean) / sqrt_var if sqrt_var != 0 else np.zeros((len(param), 1))
return param