def __init__(self, name, start_hp): """ :param name: player's name :name type: string :param start_hp: initial hp :start_hp type: int """ try: if (start_hp <= 0): raise PlayerHPErorr( "Start HP of player cannot be set zero or below!") self.hp = start_hp except PlayerHPErorr as error: custom_log.logger.warning(error) self.hp = 1 self.name = name self.bag = 0 self.position = Vector2() self.is_trap_near_player = False self.is_treasure_near_player = False
def __init__(self, velocity = Vector2(0, 0)): self.velocity = velocity;
self.rotated_sprite = pygame.transform.rotate(self.sprite, self.rotation) self.draw_pos = self.pos self.weapon = Weapon(50, 300, 600, 0.5, 30, 30, self) def set_rotation_direction(self, r): self.rotation_direction = r def set_movement_direction(self, m): self.movement_direction = m def be(self, time_passed_seconds, (pos_x, pos_y), (mx, my)): self.time_passed_seconds = time_passed_seconds self.rotated_sprite = pygame.transform.rotate(self.sprite, self.rotation) self.pos = Vector2(pos_x, pos_y) w, h = self.rotated_sprite.get_size() self.draw_pos = Vector2(self.pos.x - w / 2, self.pos.y - h / 2) ax, ay = self.pos mx = mx - ax my = (my - ay) * -1 if mx != 0: angle = atan(my / mx) / (pi / 180.) else: angle = -90 if mx < 0: angle += 180. if mx >= 0 and my < 0: angle += 360. self.rotation = angle + 90 self.weapon.be(self.time_passed_seconds)
ballList.append(newBall) if event.key == pygame.K_s: if showVectors: showVectors = False else: showVectors = True elif event.key == pygame.K_g: if gravityOn: gravityOn = False else: gravityOn = True elasticCollisions(ballList) for ball in ballList: if gravityOn: ball.gravity = Vector2(0, 0.35) else: ball.gravity = Vector2(0, 0) ball.bounce(screenWidth, screenHeight) ball.update(1) ball.display(screen, showVectors) ball.hitbox = pygame.Rect(ball.position.x - ball.radius, ball.position.y - ball.radius, ball.radius * 2, ball.radius * 2) if ball.hitbox.colliderect( clickBox) and clicked and not alreadyClicked: alreadyClicked = True ball.clicked = True if ball.clicked and clicked:
def entry_actions(self): #Move to a random point in the nest self.ant.speed = 60. random_offset = Vector2(randint(-20, 20), randint(-20, 20)) self.ant.destination = Vector2(*NEST_POSITION) + random_offset
import geometry import pygame from vector2 import Vector2, UP, DOWN, LEFT, RIGHT from vector2 import ZERO as ZERO_VECTOR from bindable_event import BindableEvent from input_handler import InputHandler from geometry import Ray_Result GRAVITY = Vector2(0, 100) class InteractiveRectangle(geometry.Rectangle): def __init__(self, x, y, w, h, color=None): super().__init__(x, y, w, h, color) self.on_touched = BindableEvent.new() def touch(self, player): self.on_touched.fire(player) class Player: def __init__(self, object_list: dict, x=0, y=0, max_speed=200, acceleration=250, friction=400): self.pos = Vector2.new(x, y) self.vel = Vector2() self.max_speed = max_speed self.acceleration = acceleration self.friction = friction self.rect = geometry.Rectangle(x, y, 40, 40, color=(230, 50, 50)) self.jumped = False self.teleported = False self.alive = True self.object_list = object_list self.died = BindableEvent()
def column(self, j): return Vector2(self[(j, 1)], self[(j, 2)])
def __call__(self, other): "Matrix acting on a vector" [a, b] = [sum(self[(i, j)] * other[j] for j in [1, 2]) for i in [1, 2]] return Vector2(a, b)
def __init__(self,velocity): self.velocity=velocity self.direction=Vector2((0,0))
def create_grid(self): '''creating the grid with nodes''' for i in range(0, self.width): for j in range(0, self.height): new_node = Node(Vector2(i, j)) self.nodes.append(new_node)
def vectors(): return [Vector2(1, 2), Vector2(-1, -2)]
class Board: size = 9 up = Vector2(0, 1) down = Vector2(0, -1) right = Vector2(1, 0) left = Vector2(-1, 0) def __init__(self): # create 2D array self.board = [[0 for i in range(Board.size)] for j in range(Board.size)] self.turn_manager = TurnManager() self.state_history = StateHistory() self.state_history.add_state(self.create_state(self.board)) def make_move(self, position): color = self.turn_manager.get_current_player_color() if position is None: self.turn_manager.pass_turn() if self.turn_manager.pass_counter >= 2: self.end_game() return 'you passed' state_after_move = self.get_state(self.board, position, color, self.state_history.get_state_list()) if state_after_move is None: self.load_last_state() return 'invalid move' # If the current board state is valid, add it to the history of states. self.board = state_after_move self.state_history.add_state(state_after_move) self.next_turn() return None # returns None if move is invalid else returns state after correct move @staticmethod def get_state(orig_state, position, color, previous_states): if Board.in_bounds(orig_state, position) and Board.is_empty( orig_state, position): # Place a stone on any unoccupied space. state = Board.create_state(orig_state) state[position.x][position.y] = color # Check if any opposing groups are completely surrounded. If so, remove them and mark them as captured. hostile_stones_list = Board.get_neighbors_of_color( state, position, StoneColor.get_opposite(color)) if hostile_stones_list is not None: stones_to_be_deleted = set() for stone in hostile_stones_list: stones_string = Board.get_stones_string( state, stone, StoneColor.get_opposite(color)) if stones_string is not None and Board.is_string_dead( state, stones_string): stones_to_be_deleted.update(stones_string) for stone in stones_to_be_deleted: Board.delete_stone(state, stone) # Check if any friendly groups are completely surrounded. If so, the move is invalid. # Check if the current board state is in the history of states for this game. If so, the move is invalid. # 'ko' rule friendly_string = Board.get_stones_string(state, position, color) if friendly_string is None or Board.is_string_dead(state, friendly_string) \ or state in previous_states: return None return state return None @staticmethod def get_total_liberties_count(board_state, color, size): def get_stones_string_of_color(state, position, color): # if string doesn't have any liberties return it else return None string = set() string.add(position) string.update(Board.get_neighbors_of_color(state, position, color)) count = len(string) if count is 0: return None new_stones = string.copy() while True: new_set = set() for stone in new_stones: new_set.update( Board.get_neighbors_of_color(state, stone, color)) string.update(new_set) new_count = len(string) if new_count == count: break new_stones = new_set count = new_count return string board_copy = copy.deepcopy(board_state) total_liberties = 0 for i in range(size): for j in range(size): stone = Vector2(i, j) string = get_stones_string_of_color(board_copy, stone, color) for string_stone in string: total_liberties += Board.liberties_count( board_copy, string_stone) for string_stone in string: board_copy[string_stone.x][string_stone.y] = -11 return total_liberties def load_last_state(self): self.board = copy.deepcopy(self.state_history.get_last_state()) @staticmethod def get_stones_string(state, position, color): # if string doesn't have any liberties return it else return None string = set() string.add(position) string.update(Board.get_neighbors_of_color(state, position, color)) count = len(string) if count is 0: return None new_stones = string.copy() while True: new_set = set() for stone in new_stones: new_set.update( Board.get_neighbors_of_color(state, stone, color)) string.update(new_set) new_count = len(string) if new_count == count: break new_stones = new_set count = new_count return string @staticmethod def is_string_dead(state, string): for stone in string: liberties_count = Board.liberties_count(state, stone) if liberties_count is not 0: return False return True def next_turn(self): self.turn_manager.next_turn() @staticmethod def is_empty(state, position): return True if state[position.x][ position.y] == StoneColor.EMPTY else False @staticmethod def liberties_count(state, position): count = 0 points_to_check = Board.get_surrounding_points_list(state, position) for i in points_to_check: if Board.in_bounds(state, i) and Board.is_empty(state, i): count += 1 return count @staticmethod def get_neighbors_of_color(state, position, color): stones_list = [] surrounding_positions = Board.get_surrounding_points_list( state, position) for i in surrounding_positions: if state[i.x][i.y] is color: stones_list.append(i) return stones_list @staticmethod def in_bounds(state, position): if 0 <= position.x < len(state) and 0 <= position.y < len(state): return True else: return False @staticmethod def get_stone_at_position(state, position): if Board.in_bounds(state, position): stone = state[position.x][position.y] if stone is not StoneColor.EMPTY: return stone else: return None def get_board(self): return self.board @staticmethod def get_surrounding_points_list(state, position): points_to_check = [ position + Vector2(0, 1), position + Vector2(-1, 0), position + Vector2(1, 0), position + Vector2(0, -1) ] points_to_check = filter(lambda x: Board.in_bounds(state, x), points_to_check) return points_to_check @staticmethod def delete_stone(state, position): state[position.x][position.y] = 0 @staticmethod def create_state(state): new_state = copy.deepcopy(state) return new_state def end_game(self): pass def count_score(self): white_score = 0 black_score = 0 for i in range(Board.size): for j in range(Board.size): stone = self.board[i][j] if stone is StoneColor.WHITE: white_score += 1 elif stone is StoneColor.BLACK: black_score += 1 return [black_score, white_score] @staticmethod def valid_states_generator(state, color, previous_states): for i in range(Board.size): for j in range(Board.size): position = Vector2(i, j) new_state = Board.get_state(state, position, color, previous_states) if new_state is not None: yield [position, new_state]
def __init__(self, position = Vector2(0, 0)): self.position = position;
def __init__(self, force = Vector2(0, 0)): self.force = force;
def __init__(self, acceleration = Vector2(0, 0)): self.acceleration = acceleration;
assert world.get is not None assert world.cleanup is not None ent = world.createEntity() assert ent is not None ent2 = world.createEntity() assert ent2 is not None ent3 = world.createEntity() assert ent3 is not None entId = ent.getId() assert entId is not None c1 = TransformComponent(Vector2(10, 4), Vector2(0, 0), Vector2(1, 1)) c2 = GravityComponent(9.81) assert c1 is not None assert c2 is not None assert isinstance(c1, Component) assert isinstance(c1, TransformComponent) assert isinstance(c2, Component) assert isinstance(c2, GravityComponent) ent.assign(c1) ent.assign(c2) c12 = TransformComponent(Vector2(3, 27), Vector2(32, 5), Vector2(1.5, 1.5)) c22 = GravityComponent(6.34) ent2.assign(c12) ent2.assign(c22)
def __init__(self,Astar_graph,draw_surface,node_offset): self.node_offset = Vector2(0,0)#allows us to space the nodes form each other . self.draw_surface = draw_surface # the pygame is the surface that we are drawing on. self.node_visual = []# A list of visual nodes. self.Astar_graph = Astar_graph
def get_left_random_location(): x, y = game_settings.LEFT_HOME_LOCATION randX, randY = randint(x, x + 80), randint(80, game_settings.SCREEN_HEIGHT - 40) return Vector2(randX, randY)
def row(self, i): return Vector2(self[(1, i)], self[(2, i)])
def get_right_random_location(): x, y = game_settings.RIGHT_HOME_LOCATION randX, randY = randint(x - 80, x), randint(80, game_settings.SCREEN_HEIGHT - 40) return Vector2(randX, randY)
def __init__(self, pos, vel, is_obstacle=False, is_leader=False): self.pos = pos self.vel = vel self.acc = Vector2(0, 0) self.is_obstacle = is_obstacle self.is_leader = is_leader
def update(self, time_passed): super(SmartAlien, self).update(time_passed) lv = Vector2(self.rect.x, self.rect.y) dv = Vector2(self.destination) if lv.get_distance_to(dv) < 2: self._new_destination()
def random_destination(self): w, h = SCREEN_SIZE self.ant.destination = Vector2(randint(0, w), randint(0, h))
def generate_nodes(self): '''Generates nodes based on the number of rows and columns the grid should have.''' for x in range(0, self.columns): for y in range(0, self.rows): self.nodes.append(Node(Vector2(x,y)))
def get_normalized_click_pos(self, click_pos): x = click_pos[0] / self.pixels_per_square y = click_pos[1] / self.pixels_per_square vector2 = Vector2(x, y) return vector2
Based on "calculating the projection vector" demo on http://www.metanetsoftware.com/technique/tutorialA.html http://www.showmycode.com/?752955611975f706bdfabb7153315711 """ import pygame from pygame.locals import * import sys from aabb import AABB from circle import Circle from vector2 import Vector2 import math screenWidth = 600 screenHeight = screenWidth screenSize = Vector2(screenWidth, screenHeight) screenCenter = screenSize / 2 title = "Rect Circle Collision" fps = 60 backgroundColour = (200, 200, 200) alpha = 64 outlineThickness = 1 centerThickness = 2 innerLineColour = (128, 128, 128) innerLineThickness = 1 outerLineThickness = 3
sprite_image_filename = 'resources/big.png' import pygame from pygame.locals import * from sys import exit from vector2 import Vector2 pygame.init() screen = pygame.display.set_mode((480, 640), 0, 32) background = pygame.image.load(background_image_filename).convert() sprite = pygame.image.load(sprite_image_filename).convert_alpha() clock = pygame.time.Clock() position = Vector2(100.0, 100.0) heading = Vector2() destination = Vector2() speed = 200 while True: for event in pygame.event.get(): if event.type == QUIT: exit() pressed_mouse = pygame.mouse.get_pressed() if pressed_mouse[2]: destination = Vector2( *pygame.mouse.get_pos() ) - Vector2( *sprite.get_size() )/2 vector_to_mouse = Vector2.from_points(position, destination) vector_to_mouse.normalize() heading = (vector_to_mouse * speed)
from vector2 import Vector2 from humanPlayer import HumanPlayer from board import Board from game import Game from aiPlayer import AIPlayer from lstmModel import LSTMAIModel from LogOutputter import LogOutputter lstmLogs = [ LogOutputter('lstmModel_0_log.txt'), LogOutputter('lstmModel_1_log.txt') ] lstmModel_0 = LSTMAIModel(0, lstmLogs[0]) aiPlayer_0 = AIPlayer(lstmModel_0, lstmLogs[0]) lstmModel_1 = LSTMAIModel(1, lstmLogs[1]) aiPlayer_1 = AIPlayer(lstmModel_1, lstmLogs[1]) players = [aiPlayer_0, aiPlayer_1] numShipsOfSize = { 2 : 1, 3 : 2, 4 : 1, 5 : 1 } boardSize = Vector2(10, 10) while True: aiPlayer_0.ClearState() aiPlayer_1.ClearState() board = Board(boardSize, numShipsOfSize, players) game = Game(board) game.Play()
def be(self, t): distance_moved = t * self.speed self.total_distance += distance_moved self.pos += self.heading * distance_moved w, h = self.rotated_sprite.get_size() self.draw_pos = Vector2(self.pos.x - w / 2, self.pos.y - h / 2)
import time from math import * from sys import exit import pygame from vector2 import Vector2 from pygame.locals import * sprite_image_filename = 'images/play.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) sprite = pygame.image.load(sprite_image_filename).convert_alpha() clock = pygame.time.Clock() pygame.mouse.set_visible(True) pygame.event.set_grab(True) sprite_pos = Vector2(200, 150) sprite_speed = 300. sprite_rotation = 0. sprite_rotation_speed = 360. # Degrees per second while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() exit() pressed_keys = pygame.key.get_pressed() pressed_mouse = pygame.mouse.get_pressed()