def setUpSquares(self, width): num_rows = int(self.game_board.height / width) num_cols = int(self.game_board.width / width) # Generate squares self.squares.clear() for y in range(num_rows): row = [] for x in range(num_cols): # For every square, initialize it and tell it if it is a bomb square = Square( Rect((x * width) + self.game_board.left, (y * width) + self.game_board.top, width, width), (x, y)) square.draw(self.display, self.theme) row.append(square) self.squares.append(row)
class ShapeFacade: _circle = None _square = None _triangle = None def __init__(self): self._circle = Circle() self._square = Square() self._triangle = Triangle() # let's say the task is to create an easy interface to draw shapes def draw_circle(self): # TODO drawing circle complexity goes here # step 1 (ex. get pen) # step 2 (ex. go to whiteboard) # step 3 (ex. touch the whiteboard with the pen) # ... self._circle.draw() def draw_square(self): # TODO drawing square complexity goes here # step 1 # step 2 # step 3 # ... self._square.draw() def draw_triangle(self): # TODO drawing triangle complexity goes here # step 1 # step 2 # step 3 # ... self._triangle.draw()
"Bridge Pattern Concept Sample Code" from circle_implementer import CircleImplementer from square_implementer import SquareImplementer from circle import Circle from square import Square CIRCLE = Circle(CircleImplementer) CIRCLE.draw() SQUARE = Square(SquareImplementer) SQUARE.draw()
class Game: width = data.getConfig("width") rows = data.getConfig("rows") square_color = data.getConfig("squareColor") initial_snake_pos = data.getConfig("initialSnakePos") food_color = data.getConfig("foodColor") line_color = data.getConfig("lineColor") board_color = data.getConfig("boardColor") def __init__(self, ai_mode=False): '''snake game''' self.snake = Snake(self.initial_snake_pos, self.square_color) self.food = Square(self.random_food_pos(), self.food_color) self.ai_mode = ai_mode self.surface = pygame.display.set_mode((self.width, self.width)) self.clock = pygame.time.Clock() def get_game_map_rows(self): '''return rows config''' return self.rows def get_game_map_size(self): return (self.rows, self.rows) def get_snake_head_pos(self): '''return snake head pos [x, y]''' return self.snake.head.pos def get_snake_full_pos(self): '''return array for each of the snake body pos [x, y]''' return [body.pos for body in self.snake.body] def get_snake_dir(self): '''return snake dir [x, y]''' return self.snake.dir def get_food_pos(self): '''return food pos [x, y]''' return self.food.pos def get_score(self): '''return len of the snake body''' return len(self.snake.body) def is_snake_alive(self): '''return True if the snake is alive''' return self.snake.alive def kill_snake(self): '''set snake.alive to False''' self.snake.alive = False def move_snake_up(self): '''Move the snake up''' self.snake.move_snake_up() def move_snake_down(self): '''Move the snake down''' self.snake.move_snake_down() def move_snake_left(self): '''Move the snake left''' self.snake.move_snake_left() def move_snake_right(self): '''Move the snake right''' self.snake.move_snake_right() def draw_grid(self): '''draw visual of the game grid''' size_between = self.width // self.rows grid_x = 0 grid_y = 0 for l in range(self.rows): grid_x = grid_x + size_between grid_y = grid_y + size_between pygame.draw.line(self.surface, self.line_color, (grid_x, 0), (grid_x, self.width)) pygame.draw.line(self.surface, self.line_color, (0, grid_y), (self.width, grid_y)) def redraw_window(self): '''draw visual of the full game board''' self.surface.fill(self.board_color) self.snake.draw(self.surface) self.food.draw(self.surface) self.draw_grid() pygame.display.update() return pygame.surfarray.array3d(pygame.display.get_surface()) def random_food_pos(self): '''return a valid random food position''' positions = self.snake.body while True: pos = [random.randrange(self.rows), random.randrange(self.rows)] if len(list(filter(lambda z: z.pos == pos, positions))) > 0: continue break return pos def update(self): '''update the game state''' for event in pygame.event.get(): if event.type == QUIT: pygame.display.quit() pygame.quit() if self.snake.body[0].pos == self.food.pos: self.snake.add_cube() self.food = Square(self.random_food_pos(), self.food_color) if not self.is_snake_alive(): print('Score:', len(self.snake.body)) return self.redraw_window() def reset(self): '''reset the game''' self.snake.reset(data.getConfig("initialSnakePos")) self.food = Square(self.random_food_pos(), self.food_color) self.snake.alive = True def quit_game(self): pygame.display.quit() pygame.quit() def start(self): '''Main loop of the game''' while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() break if not self.ai_mode: pygame.time.delay(100) self.clock.tick(10) self.snake.move() if self.snake.body[0].pos == self.food.pos: self.snake.add_cube() self.food = Square(self.random_food_pos(), self.food_color) if not self.is_snake_alive(): print('Score:', len(self.snake.body)) self.snake.reset(data.getConfig("initialSnakePos")) self.snake.alive = True break self.redraw_window()
class Game: FOOD = 3 HEAD = 2 SNAKE = 1 SPACE = 0 width = data.getConfig("width") rows = data.getConfig("rows") square_color = data.getConfig("squareColor") initial_snake_pos = data.getConfig("initialSnakePos") food_color = data.getConfig("foodColor") line_color = data.getConfig("lineColor") board_color = data.getConfig("boardColor") def __init__(self): '''snake game''' self.snake = Snake(self.initial_snake_pos, self.square_color) self.food = Square(self.random_food_pos(), self.food_color) self.size = 0 def get_inputs(self): return [ self.get_snake_head_pos(), self.get_snake_dir(), self.get_food_pos() ] #return[self.get_snake_head_pos(), self.get_snake_full_pos(), self.get_snake_dir()] def get_game_map_rows(self): '''return rows config''' return self.rows def get_snake_head_pos(self): '''return snake head pos [x, y]''' return self.snake.head.pos def get_snake_full_pos(self): '''return array for each of the snake body pos [x, y]''' return [body.pos for body in self.snake.body] def get_snake_dir(self): '''return snake dir [x, y]''' return self.snake.dir def get_food_pos(self): '''return food pos [x, y]''' return self.food.pos def get_score(self): '''return len of the snake body''' return len(self.snake.body) def draw_grid(self, surface): '''draw visual of the game grid''' size_between = self.width // self.rows grid_x = 0 grid_y = 0 for l in range(self.rows): grid_x = grid_x + size_between grid_y = grid_y + size_between pygame.draw.line(surface, self.line_color, (grid_x, 0), (grid_x, self.width)) pygame.draw.line(surface, self.line_color, (0, grid_y), (self.width, grid_y)) def redraw_window(self, surface): '''draw visual of the full game board''' surface.fill(self.board_color) self.snake.draw(surface) self.food.draw(surface) self.draw_grid(surface) pygame.display.update() def random_food_pos(self): '''return a valid random food position''' positions = self.snake.body while True: pos = [random.randrange(self.rows), random.randrange(self.rows)] if len(list(filter(lambda z: z.pos == pos, positions))) > 0: continue break return pos def move_snake_up(self): '''Trigger one input K_UP to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_UP, mod=pygame.locals.KMOD_NONE, scancode=111, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_UP, mod=pygame.locals.KMOD_NONE, scancode=111, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_down(self): '''Trigger one input K_DOWN to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_DOWN, mod=pygame.locals.KMOD_NONE, scancode=116, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_DOWN, mod=pygame.locals.KMOD_NONE, scancode=116, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_left(self): '''Trigger one input K_LEFT to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_LEFT, mod=pygame.locals.KMOD_NONE, scancode=113, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_LEFT, mod=pygame.locals.KMOD_NONE, scancode=113, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_right(self): '''Trigger one input K_RIGHT to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_RIGHT, mod=pygame.locals.KMOD_NONE, scancode=114, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_RIGHT, mod=pygame.locals.KMOD_NONE, scancode=114, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def send_inputs(self, net): '''Envoie 200 input à notre reseau de neuronne On commence par faire une matrice de taille 10x10 remplies de 0 On insère la position courante de la tête du snake On refais la meme chose pour la position de la nourriture On transforme les deux matrices en liste unidimensionnels et on les appends ensemble On envoie nos 200 inputs à notre réseaux, on recois 4 ouput entre -1 et 1 Dépendemment des outputs, on donne un certains mouvement La partie commenté au millieu est une méthode vorace qui avais beaucoup plus de succès ''' matrixS = np.zeros((10, 10)) snakePos = self.get_snake_head_pos() print(snakePos) matrixS[snakePos[0], snakePos[1]] = 1 inputS = np.squeeze(np.asarray(matrixS)) matrixF = np.zeros((10, 10)) foodPos = self.get_food_pos() matrixF[foodPos[0], foodPos[1]] = 1 inputF = np.squeeze(np.asarray(matrixF)) input = np.append(inputS, inputF) output = net.activate(input) print(output) #méthode vorace # x = input[0]-input[4] # y = input[1]-input[5] # # if (x<0 and y<=0): # if (x<y): # self.move_snake_right() # else: # self.move_snake_down() # elif(x>=0 and y>=0): # if (x>y): # self.move_snake_left() # else: # self.move_snake_up() # # elif (x>=0 and y<=0): # if (x>abs(y)): # self.move_snake_left() # else: # self.move_snake_down() # elif (x<0 and y>0): # if (abs(x)>y): # self.move_snake_right() # # else: # self.move_snake_up() if (output[0] >= output[1] and output[0] >= output[2] and output[0] >= output[3]): self.move_snake_right() elif (output[1] >= output[0] and output[1] >= output[2] and output[1] >= output[3]): self.move_snake_left() elif (output[2] >= output[1] and output[2] >= output[0] and output[2] >= output[3]): self.move_snake_up() else: self.move_snake_down() def isCloser(self, snakeBefore, foodBefore): '''Regarde la position avant et après et retourne l'augmentation du fitness Retourne 10 si le snake a trouvé le food Retourne 1 si le snake a fait un mouvement vers le food Retourne -2 si le snake fait un mouvement plus loins du food''' snakeNow = self.get_snake_head_pos() foodNow = self.get_food_pos() distanceToFoodBefore = abs(snakeBefore[0] - foodBefore[0]) + abs(snakeBefore[1] - foodBefore[1]) distanceToFoodNow = abs(snakeNow[0] - foodNow[0]) + abs(snakeNow[1] - foodNow[1]) if (foodBefore[0] != foodNow[0] or foodBefore[1] != foodNow[1]): return 10 elif (distanceToFoodNow < distanceToFoodBefore): return 1 else: return -2 def start(self, net, genome): '''Main loop of the game''' self.size = 0 win = pygame.display.set_mode((self.width, self.width)) clock = pygame.time.Clock() flag = True counter = 0 while flag: counter += 1 #if statement pour limité le nombre de mouvement à 50 if counter > 50: self.snake.alive = False # pygame.time.delay(50) # clock.tick(10) #les données avant un mouvement snakeBefore = self.get_snake_head_pos()[:] food = self.get_food_pos() #appel send inputs qui va envoyer envoyer des inputs dans noter RN et ensuite faire un mouvement self.send_inputs(net) #fonction qui prend les events de deplacement et l'applique self.snake.move() #augmentation du fitness genome.fitness += self.isCloser(snakeBefore, food) #si le serpent a mangé une nourriture if self.snake.body[0].pos == self.food.pos: self.snake.add_cube() self.food = Square(self.random_food_pos(), self.food_color) #si le serpent meurt if self.snake.alive == False: genome.fitness -= 10 self.size = len(self.snake.body) print('Score:', self.size) self.snake.reset(data.getConfig("initialSnakePos")) self.snake.alive = True flag = False self.redraw_window(win)
pygame.init() screen = pygame.display.set_mode((700, 500)) pygame.display.set_caption("Studsaren") square = Square(screen, random.randint(0, screen.get_size()[0] - 50), random.randint(0, screen.get_size()[1] - 50), 50, 50) square.velocity = 200 * Vector(random.uniform(-10, 10), random.uniform(-10, 10)).normalized() clock = pygame.time.Clock() done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True t = clock.get_time() / 1000 width, height = screen.get_size() if square.pos.x <= 0 or square.pos.x >= width - square.w: square.velocity = Vector(-square.velocity.x, square.velocity.y) if square.pos.y <= 0 or square.pos.y >= height - square.h: square.velocity = Vector(square.velocity.x, -square.velocity.y) square.update(t) screen.fill((0, 0, 0)) square.draw() pygame.display.flip() clock.tick(60)
# モジュールインポート import tkinter as tk from square import Square from line import Line from point import Point # 初期化 def app_init(): root = tk.Tk() root.geometry("500x500") canvas = tk.Canvas(root, height=500, width=500) canvas.place(x=0, y=0) return root, canvas # メイン r, c = app_init() # 四角形オブジェクト生成 s1 = Square(c, Point(100, 100), Point(200, 200)) # draw()メソッド呼び出し s1.draw() # 直線オブジェクト生成 l1 = Line(c, Point(50, 50), Point(300, 300)) # draw()メソッド呼び出し l1.draw() # Tkinterメインループ r.mainloop()
class Game: FOOD = 3 HEAD = 2 SNAKE = 1 SPACE = 0 width = data.getConfig("width") rows = data.getConfig("rows") square_color = data.getConfig("squareColor") initial_snake_pos = data.getConfig("initialSnakePos") food_color = data.getConfig("foodColor") line_color = data.getConfig("lineColor") board_color = data.getConfig("boardColor") def __init__(self): '''snake game''' self.snake = Snake(self.initial_snake_pos, self.square_color) self.food = Square(self.random_food_pos(), self.food_color) def get_inputs(self): return [ self.get_snake_head_pos(), self.get_snake_dir(), self.get_food_pos() ] #return[self.get_snake_head_pos(), self.get_snake_full_pos(), self.get_snake_dir()] def get_game_map_rows(self): '''return rows config''' return self.rows def get_snake_head_pos(self): '''return snake head pos [x, y]''' return self.snake.head.pos def get_snake_full_pos(self): '''return array for each of the snake body pos [x, y]''' return [body.pos for body in self.snake.body] def get_snake_dir(self): '''return snake dir [x, y]''' return self.snake.dir def get_food_pos(self): '''return food pos [x, y]''' return self.food.pos def get_score(self): '''return len of the snake body''' return len(self.snake.body) def draw_grid(self, surface): '''draw visual of the game grid''' size_between = self.width // self.rows grid_x = 0 grid_y = 0 for l in range(self.rows): grid_x = grid_x + size_between grid_y = grid_y + size_between pygame.draw.line(surface, self.line_color, (grid_x, 0), (grid_x, self.width)) pygame.draw.line(surface, self.line_color, (0, grid_y), (self.width, grid_y)) def redraw_window(self, surface): '''draw visual of the full game board''' surface.fill(self.board_color) self.snake.draw(surface) self.food.draw(surface) self.draw_grid(surface) pygame.display.update() def random_food_pos(self): '''return a valid random food position''' positions = self.snake.body while True: pos = [random.randrange(self.rows), random.randrange(self.rows)] if len(list(filter(lambda z: z.pos == pos, positions))) > 0: continue break return pos def move_snake_up(self): '''Trigger one input K_UP to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_UP, mod=pygame.locals.KMOD_NONE, scancode=111, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_UP, mod=pygame.locals.KMOD_NONE, scancode=111, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_down(self): '''Trigger one input K_DOWN to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_DOWN, mod=pygame.locals.KMOD_NONE, scancode=116, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_DOWN, mod=pygame.locals.KMOD_NONE, scancode=116, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_left(self): '''Trigger one input K_LEFT to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_LEFT, mod=pygame.locals.KMOD_NONE, scancode=113, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_LEFT, mod=pygame.locals.KMOD_NONE, scancode=113, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def move_snake_right(self): '''Trigger one input K_RIGHT to the snake''' newevent = pygame.event.Event(pygame.KEYDOWN, unicode='', key=K_RIGHT, mod=pygame.locals.KMOD_NONE, scancode=114, window=None) newevent2 = pygame.event.Event(pygame.KEYUP, key=K_RIGHT, mod=pygame.locals.KMOD_NONE, scancode=114, window=None) pygame.event.post(newevent) pygame.event.post(newevent2) def greedy(self): ''' Méthode vorace qui avais beaucoup plus de succès ''' snakePos = self.get_snake_head_pos() foodPos = self.get_food_pos() input = [snakePos[0], snakePos[1], foodPos[0], foodPos[1]] #méthode vorace x = input[0] - input[2] y = input[1] - input[3] if (x < 0 and y <= 0): if (x < y): self.move_snake_right() else: self.move_snake_down() elif (x >= 0 and y >= 0): if (x > y): self.move_snake_left() else: self.move_snake_up() elif (x >= 0 and y <= 0): if (x > abs(y)): self.move_snake_left() else: self.move_snake_down() elif (x < 0 and y > 0): if (abs(x) > y): self.move_snake_right() else: self.move_snake_up() def start(self): '''Main loop of the game''' self.size = 0 win = pygame.display.set_mode((self.width, self.width)) clock = pygame.time.Clock() counter = 0 while True: pygame.time.delay(50) clock.tick(10) #appel send inputs utilise une methode vorace pour faire un mouvement self.greedy() #fonction qui prend les events de deplacement et l'applique self.snake.move() #si le serpent a mangé une nourriture if self.snake.body[0].pos == self.food.pos: self.snake.add_cube() self.food = Square(self.random_food_pos(), self.food_color) #si le serpent meurt if self.snake.alive == False: print('Score:', len(self.snake.body)) self.snake.reset(data.getConfig("initialSnakePos")) self.snake.alive = True self.redraw_window(win)
from time import sleep from square import Square from line import Line from point import Point def app_init(): root = tk.Tk() root.geometry("500x500") canvas = tk.Canvas(root, height=500, width=500) canvas.place(x=0, y=0) return root, canvas # メイン r,c = app_init() s1 = Square(c, Point(c, 100,100), Point(c, 200, 200)) s1.draw() s2 = Square(c, Point(c, 10,10), Point(c, 50, 50)) s2.draw() l1 = Line(c, Point(c, 50, 50), Point(c, 300, 300), color='red') l1.draw() # クラスメソッドを呼ぶ Square.print_num() Line.print_num() # 親クラスのスタティックメソッドを呼ぶ Square.all_rights() # Tkボタンとハンドラー def gmove(): # セッターメソッド s1.foreground = 'blue' # 追加メソッド呼び出し s1.move(Point(c,10, 10))
class Food: """This class creates food for Snake game""" def __init__(self, pen): """Constructor for Food class. This funcion is called upon initialization. It saves a Square object and list of colors as a class members. Parameters ---------- None Returns ------- None """ self.pen = pen self.square = Square(self.pen) self.colors = ["red", "green", "yellow", "blue", "magenta", "cyan"] def create_food(self): """Create a random food location for the self.square. Parameters ---------- None Returns ------- None """ self.square.x = random.randint(-self.square.size, self.square.size) * self.square.size self.square.y = random.randint(-self.square.size, self.square.size) * self.square.size self.draw_food() def collision_with_food(self, x, y): """Checks if snake has food collision. Returns True if it is and False otherwise. Parameters ---------- x : int Horizontal coordinate y : int Vertical coordinate Returns ------- collision bool """ collision = False if self.square.x == x and self.square.y == y: collision = True return collision def draw_food(self): """Draw food using Square. Parameters ---------- None Returns ------- None """ self.square.draw(self.square.x, self.square.y, random.choice(self.colors))