Пример #1
0
def from_midi(stream) :
    import midi
    m = midi.MidiFile()
    m.open(stream)
    m.read()
    m.close()
    trackvar = []
    
    for track in m.tracks :
        curvar = Variable()
        trackvar.append(curvar)
        curpitch = Pitch()
        for ev in track.events :
            if ev.type == "NOTE_OFF" or ev.type == "NOTE_ON" :
                if curpitch.havePitches() : 
                    if curpitch.duration_ : 
                        print curpitch.duration_
                        curvar.addPitch(curpitch.copy())
                curpitch.duration_ = 0
            if ev.type == "DeltaTime": curpitch.duration_ = ev.time#curpitch.plusDuration(durFromTime(ev.time))
            elif ev.type == "NOTE_OFF" or ev.type == "NOTE_ON" and ev.velocity==0 : 
                if curpitch.havePitches() : 
                    curpitch.removePitch(ev.pitch-60)
            elif ev.type == "NOTE_ON": 
                curpitch.addPitch(ev.pitch-60)
            elif ev.type == "SET_TEMPO": print "BUGAGA", ev# TODO (?) ...
            else:
                print "midi warning: event", ev, "ignored"
Пример #2
0
def filter_intonation(intonations, threshold):
    if intonations == None: return None
    filters = []

    # remove any intonations that whose pitch change is below the threshold
    for i in intonations:
        if i.pitch < threshold:
            filters.append(i)

    intonations = [i for i in intonations if i not in filters]
    if len(intonations) == 0: return None

    # combine intonations with the same directions after filtering
    last = intonations[0]
    combined_intonations = []
    combined_intonations.append(last)
    for i in intonations:
        if i == last: continue
        if i.intonation == last.intonation:
            combined_intonations[-1].pitch += i.pitch
        else:
            combined_intonations.append(Pitch(i.pitch, i.time, i.intonation))
        last = i

    return combined_intonations
Пример #3
0
def detect_intonation(pitches):
    if pitches == None: return None
    last = pitches[0]
    
    # mark each pitch as increasing or decreasing based on the one before it
    for p in pitches:
        if p == last: continue
        if p.pitch > last.pitch:
            p.intonation = 1
        elif last.pitch > p.pitch:
            p.intonation = -1
        last = p

    # add up the pitch change over all sequential pitch changes with the same direction
    last = pitches[0]
    intonations = []
    for p in pitches:
        if p == last: continue
        if p.intonation == last.intonation:
            intonations[-1].pitch += fabs(p.pitch - last.pitch)
        else:
            intonations.append(Pitch(fabs(p.pitch - last.pitch), p.time, p.intonation))
        last = p

    if len(intonations) == 0:
        return None
    return intonations
Пример #4
0
def plot_intonation(intonations, anchor, name):
    if intonations == None: return
    # first clear axes and figure
    cla()
    clf()

    # reconstruct data since we don't keep concrete pitch data
    data = []
    data.append(Pitch(anchor, 0))
    for i in intonations:
        data.append(Pitch((data[-1].pitch + (i.pitch * i.intonation)), i.time))

    # generate lists from pitch objects
    times = [p.time for p in data]
    values = [p.pitch for p in data]
    # graph pitch
    plot(times, values)
    savefig(name[:-4] + "-int")
Пример #5
0
    def __init__(self):
        """
        Setting the internal data is done by calling functions after
        construction, such as major(), harmMinor(), etc.
        """
        # Maps a semitone to the accidental required for that semitone
        self._semiMap = {}

        # Creates a default major key
        self.major(Pitch())
Пример #6
0
def getPlaysByGame(gameID):
    session = getSession()
    try:
        r = getRequest(gameID)
        #conn.request("GET", "/mlb/v2/JSON/News?%s" % params, "{body}",
        #    headers) #response = conn.getresponse()
        if r != None:
            data = r.json()
            gameID = data['Game']['GameID']
            plays = data['Plays']
            for play in plays:
                theID = play['PlayID']
                query = session.query(Play).filter(
                    Play.PlayID == theID).scalar()
                thisPlay = Play(**{
                    k: v
                    for k, v in play.items() if k in Play.__table__.columns
                })
                thisPlay.GameID = gameID
                if query is None:
                    ''
                    session.add(thisPlay)
                else:
                    query = session.merge(
                        thisPlay
                    )  #session.query(News).filter(News.NewsID == theID).update(newsItem)
                pitches = play['Pitches']
                for pitch in pitches:
                    theID = pitch['PitchID']
                    query = session.query(Pitch).filter(
                        Pitch.PitchID == theID).scalar()
                    thisPitch = Pitch(
                        **{
                            k: v
                            for k, v in pitch.items()
                            if k in Pitch.__table__.columns
                        })
                    if query is None:
                        session.add(thisPitch)
                    else:
                        query = session.merge(thisPitch)
                session.commit()
    except Exception as e:
        print("[Errno {0}] ".format(e))
    session.close()
Пример #7
0
 def create_pitch(self, name):
     return Pitch(self.__next_id(), name, self.__next_pitch_rank())
Пример #8
0
import requests
from pandas import json_normalize
import numpy as np
from pitch import Pitch
import warnings

from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)

match_id = "8658"
side = "away"
color = "blue"
min_pass_count = 2  ##minimum number of passes for a link to be plotted

fig, ax = plt.subplots(figsize=(10, 6))
ax = Pitch(ax)


class Player:
    def __init__(self, player, df):
        self.id = player["player"]["id"]
        self.name = player["player"]["name"]
        self.average_position(df)

    def average_position(self, df):

        player_pass_df = df.query(
            "(type_name == 'Pass') & (pass_type_name not in ['Free Kick', 'Corner', 'Throw-in', 'Kick Off']) & (player_id == @self.id) & (pass_outcome_name not in ['Unknown','Out','Pass Offside','Injury Clearance', 'Incomplete'])"
        )
        self.x, self.y = np.mean(player_pass_df['location'].tolist(), axis=0)
Пример #9
0
import numpy as np
import math
import random
from pitch import Pitch

# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture('data/video.mp4')

# Check if camera opened successfully
if (cap.isOpened() == False):
    print("Error opening video stream or file")

cap.set(0, 62200)

pitch = Pitch(['BL', 'I', 'I', 'I', 'TL', 'SL', '20M'])
frame_count = 0
# Read until video is completed
while (cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()

    if ret == True:
        if frame_count % 5 == 0:
            pitch.update(frame, True)
        else:
            pitch.update(frame)

        pitch.annotate(frame)

        cv2.imshow('Frame', frame)
Пример #10
0
import pygame
from pitch import Pitch

x = 0
y = 0
tile_size = 32
level_layout = [
    [1, 1],
    [0, 0],
]

floor_image = pygame.image.load("./assets/wall.png")
wall_image = pygame.image.load("./assets/wall.png")

pitch = Pitch(floor_image, wall_image, x, y, tile_size, level_layout)

print("==Pitch Unit Test==")

test1 = "Pass" if pitch.x == x else "Fail"
print(f"1. pitch.x initialises correctly: {test1:>5}")

test2 = "Pass" if pitch.y == y else "Fail"
print(f"2. pitch.y initialises correctly: {test2:>5}")

test3 = "Pass" if pitch.getWidth() == 2 else "Fail"
print(f"3. pitch.getWidth(): {test3:>18}")

test4 = "Pass" if pitch.getHeight() == 2 else "Fail"
print(f"4. pitch.getHeight(): {test4:>17}")

test5 = "Pass" if pitch.isInBounds(1, 1) else "Fail"
Пример #11
0
    def __init__(self):
        """Constructor method for the top level class. Initialises pygame and loads sprites and text."""
        self.title = "Quidditch"
        self.width = 400
        self.height = 400
        self.tile_size = 32
        self.fps = 60
        self.background = (0, 0, 0)
        self.text_colour = (255, 255, 255)

        self.level = 1

        # Each level is defined with a 2d array of values. 0 is a floor, 1 is a wall
        self.level1_layout = [
            [1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 0, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 1, 0, 0, 0, 0, 0, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1],
        ]
        self.level2_layout = [
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        ]
        self.player1_score = 10
        self.player2_score = 10

        # Initialise pygame and setup the screen to display
        pygame.init()
        pygame.display.set_caption(self.title)
        self.screen = pygame.display.set_mode((self.width, self.height))

        # Define standard font
        try:
            self.font = pygame.font.SysFont("Verdana", 30)
        except:
            self.font = pygame.font.SysFont(None, 30)

        # Load images
        self.player1_image = pygame.image.load("./assets/player1.png")
        self.player2_image = pygame.image.load("./assets/player2.png")
        self.golden_snitch_image = pygame.image.load(
            "./assets/golden_snitch.png")
        self.wall_image = pygame.image.load("./assets/wall.png")
        self.floor_image = self.createBlankImage(self.tile_size)

        # Create a sprite group which will be responsible for rendering the sprites
        self.sprites = pygame.sprite.Group()

        # Create game objects - A pitch, 2 players and a golden snitch
        self.pitch = Pitch(self.floor_image, self.wall_image, 0, 0,
                           self.tile_size, self.level1_layout)
        self.pitch.render()
        self.player1 = Player(self.sprites, self.player1_image, 1, 2,
                              self.tile_size)
        self.player2 = Player(self.sprites, self.player2_image, 6, 5,
                              self.tile_size)
        self.golden_snitch = GoldenSnitch(self.sprites,
                                          self.golden_snitch_image, 4, 3,
                                          self.tile_size)

        # Start the game loop. Check for events and draw to screen
        self.clock = pygame.time.Clock()
        while True:
            self.clock.tick(self.fps)  # Set frame rate
            self.eventHandler()  # Check for events
            self.draw()  # Draw to screen
Пример #12
0
class Game:
    """Top Level Class."""
    def __init__(self):
        """Constructor method for the top level class. Initialises pygame and loads sprites and text."""
        self.title = "Quidditch"
        self.width = 400
        self.height = 400
        self.tile_size = 32
        self.fps = 60
        self.background = (0, 0, 0)
        self.text_colour = (255, 255, 255)

        self.level = 1

        # Each level is defined with a 2d array of values. 0 is a floor, 1 is a wall
        self.level1_layout = [
            [1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 0, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 1, 0, 0, 0, 0, 0, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1],
        ]
        self.level2_layout = [
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
            [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        ]
        self.player1_score = 10
        self.player2_score = 10

        # Initialise pygame and setup the screen to display
        pygame.init()
        pygame.display.set_caption(self.title)
        self.screen = pygame.display.set_mode((self.width, self.height))

        # Define standard font
        try:
            self.font = pygame.font.SysFont("Verdana", 30)
        except:
            self.font = pygame.font.SysFont(None, 30)

        # Load images
        self.player1_image = pygame.image.load("./assets/player1.png")
        self.player2_image = pygame.image.load("./assets/player2.png")
        self.golden_snitch_image = pygame.image.load(
            "./assets/golden_snitch.png")
        self.wall_image = pygame.image.load("./assets/wall.png")
        self.floor_image = self.createBlankImage(self.tile_size)

        # Create a sprite group which will be responsible for rendering the sprites
        self.sprites = pygame.sprite.Group()

        # Create game objects - A pitch, 2 players and a golden snitch
        self.pitch = Pitch(self.floor_image, self.wall_image, 0, 0,
                           self.tile_size, self.level1_layout)
        self.pitch.render()
        self.player1 = Player(self.sprites, self.player1_image, 1, 2,
                              self.tile_size)
        self.player2 = Player(self.sprites, self.player2_image, 6, 5,
                              self.tile_size)
        self.golden_snitch = GoldenSnitch(self.sprites,
                                          self.golden_snitch_image, 4, 3,
                                          self.tile_size)

        # Start the game loop. Check for events and draw to screen
        self.clock = pygame.time.Clock()
        while True:
            self.clock.tick(self.fps)  # Set frame rate
            self.eventHandler()  # Check for events
            self.draw()  # Draw to screen

    def createBlankImage(self, tile_size):
        """Create a transparent image of a given tile size."""
        return pygame.Surface((tile_size, tile_size), pygame.SRCALPHA,
                              32).convert_alpha()

    def eventHandler(self):
        """Checks for system events such as keyboard presses."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.quit()
                elif event.key == pygame.K_a:  # Player 1 Left
                    self.movePlayerLeft(self.player1)
                elif event.key == pygame.K_d:  # Player 1 Right
                    self.movePlayerRight(self.player1)
                elif event.key == pygame.K_w:  # Player 1 Up
                    self.movePlayerUp(self.player1)
                elif event.key == pygame.K_s:  # Player 1 Down
                    self.movePlayerDown(self.player1)
                elif event.key == pygame.K_j:  # Player 2 Left
                    self.movePlayerLeft(self.player2)
                elif event.key == pygame.K_l:  # Player 2 Right
                    self.movePlayerRight(self.player2)
                elif event.key == pygame.K_i:  # Player 2 Up
                    self.movePlayerUp(self.player2)
                elif event.key == pygame.K_k:  # Player 2 Down
                    self.movePlayerDown(self.player2)

    def draw(self):
        """Redraws the screen with the updated sprite positions and text."""
        # Clear the screen
        self.screen.fill(self.background)

        # Draw the Pitch and Sprites
        self.pitch.draw(self.screen)
        self.sprites.draw(self.screen)

        # Draw Text
        self.player1_score_text = self.font.render(
            f"Player 1: {self.player1_score - self.player1.getMoveCounter()}",
            True, self.text_colour)
        self.player2_score_text = self.font.render(
            f"Player 2: {self.player2_score - self.player2.getMoveCounter()}",
            True, self.text_colour)
        self.screen.blit(self.player1_score_text, (20, 300))
        self.screen.blit(self.player2_score_text, (20, 350))

        # Update the display to show the changes
        pygame.display.flip()

    def quit(self):
        """Clean shutdown of the game."""
        pygame.quit()
        sys.exit()

    def isSnitch(self, x, y):
        """Check whether a co-ordinate contains a Golden Snitch."""
        return self.golden_snitch.getX() == x and self.golden_snitch.getY(
        ) == y

    def isPlayer(self, x, y):
        """Check whether a co-ordinate contains a Player."""
        return (self.player1.getX() == x
                and self.player1.getY() == y) or (self.player2.getX() == x
                                                  and self.player2.getY() == y)

    def movePlayerLeft(self, player):
        """Move a player left, checking for walls, the world bounds, and the Golden Snitch."""
        player.turnLeft()
        if self.pitch.isFloor(player.getX() - 1, player.getY()):
            player.moveLeft()
            self.checkForSnitch(player)

    def movePlayerRight(self, player):
        """Move a player right, checking for walls, the world bounds, and the Golden Snitch."""
        player.turnRight()
        if self.pitch.isFloor(player.getX() + 1, player.getY()):
            player.moveRight()
            self.checkForSnitch(player)

    def movePlayerUp(self, player):
        """Move a player up, checking for walls, the world bounds, and the Golden Snitch."""
        if self.pitch.isFloor(player.getX(), player.getY() - 1):
            player.moveUp()
            self.checkForSnitch(player)

    def movePlayerDown(self, player):
        """Move a player down, checking for walls, the world bounds, and the Golden Snitch."""
        if self.pitch.isFloor(player.getX(), player.getY() + 1):
            player.moveDown()
            self.checkForSnitch(player)

    def moveSnitch(self):
        """Move the Golden Snitch in a random direction, checking for walls, the world bounds, and Players."""
        x, y = self.golden_snitch.getRandomDirection()
        if self.pitch.isFloor(x, y) and not self.isPlayer(x, y):
            self.golden_snitch.setPosition(x, y)

    def checkForSnitch(self, player):
        """Check if a player has moved onto the Golden Snitch, catching it. Add 150 to their team's score and load the next level."""
        if self.isSnitch(player.getX(), player.getY()):
            if self.player1 == player:
                self.player1_score += 150
            else:
                self.player2_score += 150
            self.loadNextLevel()
        else:
            if self.level > 1:
                self.moveSnitch()

    def loadNextLevel(self):
        """Load the layout for the next level and reposition the Players and Golden Snitch. If all levels have been played then exit the game."""
        self.level += 1
        if self.level == 2:
            self.pitch.loadTiles(self.level2_layout)
            self.player1.setPosition(1, 2)
            self.player2.setPosition(8, 7)
            self.golden_snitch.setPosition(5, 4)
        else:
            self.quit()
Пример #13
0
 def pitch(self, value):
     self._pitch = Pitch()
     (self._pitch.step, self._pitch.alter, self._pitch.octave) = value
 def pitch_handler(self, axis, value):
     pitch_value = Pitch(int(abs(value) / 30) + 1)
     if self.current_pitch != pitch_value:
         self.current_pitch = pitch_value
         self.on_pitch_change(self.current_pitch)
Пример #15
0
Файл: main.py Проект: sjk39/pong
from turtle import Screen
from scoreboard import Scoreboard
from ball import Ball
from pitch import Pitch
from paddle import Paddle
import time

sc = Screen()
sc.setup(width=1000, height=600)
p = Pitch()
sc.bgcolor("black")
sc.title("Pong")
sc.listen()
paddle_one = Paddle()
paddle_one.position(1)
paddle_two = Paddle()
paddle_two.position(2)
ball = Ball()
scoreboard = Scoreboard()
sc.onkey(paddle_one.up, "Up")
sc.onkey(paddle_one.down, "Down")

game_on = True
while game_on:
    sc.update()
    #time.sleep(0.001)

    if ball.distance(paddle_one.pos()) < 40 or ball.distance(
            paddle_two.pos()) < 40:
        ball.move(1)
        #prevents ball getting 'stuck' to paddle