-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.py
173 lines (140 loc) · 6.57 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
163
164
165
166
167
168
169
170
171
172
173
import random
import pygame
import numpy as np
from variables import global_variables
from nn import NeuralNetwork
class Player(pygame.sprite.Sprite):
def __init__(self, game_mode):
super().__init__()
self.layer_sizes = []
# 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
if self.game_mode == "Neuroevolution":
self.fitness = 0 # Initial fitness
# input layer
# self.layer_sizes[0] must be even
self.layer_sizes.append(6)
# hidden layer
self.layer_sizes.append(20)
# output layer
self.layer_sizes.append(2)
# [8, 32, 2] # TODO (Design your architecture here by changing the values)
self.nn = NeuralNetwork(self.layer_sizes)
def create_input(self, screen_width, screen_height, obstacles, player_x, player_y):
"""
Creates input vector of the neural network based on the location of obstacles.
The size of input vector is 8.
:return: created vector
"""
created_input = [player_x / screen_width, player_y / screen_height]
for i in range(self.layer_sizes[0] // 2 - 1):
try:
y = obstacles[i]['y']
x = obstacles[i]['x']
if y - 2 < player_y:
created_input.append((screen_height - y) / screen_height)
created_input.append(x / screen_width)
else:
created_input.append(1)
created_input.append(1)
except:
created_input.append(1)
created_input.append(1)
return created_input
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 first obstacle on the scene. It is also worthwhile noting that 'y' range is in [-100, 656], such that
-100 means it is off screen (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
"""
# TODO (change player's gravity here by calling self.change_gravity)
input = self.create_input(screen_width, screen_height, obstacles, player_x, player_y)
output = self.nn.forward(np.array(input).reshape(len(input), 1))
# Update gravity based of output of NN
if output[0] > 0.5:
self.change_gravity('left')
elif output[1] > 0.5:
self.change_gravity('right')
else:
self.change_gravity(self.player_gravity)
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)