text:
<repo_name>DrewThomas562/Trampoline-Rush---1.3<file_sep>/Assets/Resources/Game/Actors/Physical/Visual/cWindow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cWindow : cPhysicalObject {
}
<file_sep>/Assets/Resources/Game/Actors/Physical/Interactive/FallingObject/cDebris.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cDebris : cFallingObject {
    private void OnTriggerEnter2D(Collider2D collision) {
        cPlayer OTHER = collision.GetComponent<cPlayer>();
        if ( OTHER == null ) { return; }
        else if ( OTHER.tag == "Player" ) {
            OTHER.GetComponent<cPlayer>().Stun();
            Destroy(gameObject);
        }
    }
}
<file_sep>/Assets/Resources/Game/Actors/Physical/Interactive/cFallingObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cFallingObject : cPhysicalObject {
    private static float killZ = -3f;
    private static cPlayer player;

    protected override void Start() {
        base.Start();
        if ( player == null ) { player = FindObjectOfType<cPlayer>(); }
    }

    private void Update() {
        if ( transform.position.y < killZ ) {
            if ( tag == "Crook" || tag == "Civilian" ) { player.FailedObjective(); }
            Destroy(gameObject);
        }
    }
}
<file_sep>/Assets/Resources/Game/Actors/Abstract/cSpawner.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class cActorWrapper {
    public List<cActor> spawnpoints;
}

/// <summary>
/// In Trampoline Rush, the Spawner is given the task of determining when and where falling hazards and objectives will appear...
/// during the course of the game. The Spawner controls most of the difficulty of the game, being in control of spawn timers...
/// and density of spawns within spawning columns.
/// The Spawner must be able to start waves, pause while the player is looking through menus, and stop at the end of waves.
/// </summary>

public class cSpawner : cActor {
    // In Trampoline Rush, delays are needed to prevent single spawnpoint columns from getting too cluttered with objects...
    // so spawnpoints can be grouped as sets - delays can prevent objects from overlapping too closely when spawning.
    // In Trampoline Rush, those sets are Windows vertical to each other.
    [Header("SPAWNPOINT SETS")]
    [SerializeField] private List<cActorWrapper> spawnpointSets;
    [SerializeField] private float spawnSetNextAvailableTimer;
    [SerializeField] private List<float> spawnSetNextAvailableTick;
    [Space(10)]

    // In Trampoline Rush, the difficulty curve depends mainly on the spawn timers of objectives, and hazards independently...
    // so the spawner uses two independent variable sets to separate the spawning behaviors of objectives, and hazards
    // Minimum and maximum spawn timers are dependent on the Spawner's level;
    [Header("DIFFICULTY")]
    [SerializeField] private int level;
    [SerializeField] private List<sMinMax> objectiveSpawnTimer;
    [SerializeField] private List<sMinMax> hazardSpawnTimer;
    [Space(10)]

    [Header("ACTORS")]
    [SerializeField] private List<cActor> objectives;
    [SerializeField] private List<cActor> hazards;
    private float objectiveSpawnTick;
    private float hazardSpawnTick;

    // Coroutine handle
    Coroutine cofxnSpawnerRoutine;

    // Cleanup for Spawner routine
    // And initial ticker setup
    protected override void OnDestroy() {
        if ( cofxnSpawnerRoutine != null ) { StopCoroutine(cofxnSpawnerRoutine); }
        base.OnDestroy();
    }
    protected override void Start() {
        bool bSPAWNER_FAILED_INITIALIZATION = false;

        // Check for spawnpoints
        for ( int i = 0; i < spawnpointSets.Count; i++ ) {
            for ( int j = 0; j < spawnpointSets[i].spawnpoints.Count; j++ ) {
                if ( spawnpointSets[i].spawnpoints[j] == null ) {
                    print("WARNING: Spawnpoint set " + i + " has an empty element. Removing element " + j);
                    spawnpointSets[i].spawnpoints.RemoveAt(j);
                }
            }
            if ( spawnpointSets[i].spawnpoints.Count < 1 ) {
                print("WARNING: Spawnpoint set " + i + " must have at least one spawnpoint. Removing element " + i);
                spawnpointSets.RemoveAt(i);
            }
        }
        if ( spawnpointSets.Count < 1 ) {
            print("ERROR: Spawner must have at least one spawnpoint set.");
            bSPAWNER_FAILED_INITIALIZATION = true;
        }

        // If no spawnpoints were found, destroy the spawner and request corrective action.
        if ( bSPAWNER_FAILED_INITIALIZATION ) {
            print("ERROR: Spawner failed to initialize. Please correct errors.");
            Destroy(this);
            return;
        }

        // Check to make sure there are objectives and hazards to spawn.
        for ( int i = 0; i < objectives.Count; i++ ) {
            if ( objectives[i] == null ) {
                print("WARNING: Spawner objective element " + i + " is empty. Removing element.");
                objectives.RemoveAt(i);
            }
        }
        if ( objectives.Count < 1 ) {
            print("WARNING: Spawner has no objective element to spawn.");
        }
        for ( int i = 0; i < hazards.Count; i++ ) {
            if ( objectives[i] == null ) {
                print("WARNING: Spawner hazard element " + i + " is empty. Removing element.");
                objectives.RemoveAt(i);
            }
        }
        if ( hazards.Count < 1 ) {
            print("WARNING: Spawner has no hazard element to spawn.");
        }

        // Initialize only if at least one objective or hazard can be spawned.
        if ( hazards.Count + objectives.Count < 1 ) {
            print("ERROR: Spawner failed to initialize. No elements to spawn. Please add hazards and objectives.");
            Destroy(this);
            return;
        }

        // Make sure spawn timers were set. Otherwise create default spawn times.
        if ( objectiveSpawnTimer.Count < 1 ) {
            objectiveSpawnTimer.Add(new sMinMax(0.5f, 1.0f));
            print("WARNING: Spawner has no objective spawn timer. Creating element with 0.5->1.0 seconds.");
        }
        if ( hazardSpawnTimer.Count < 1 ) {
            objectiveSpawnTimer.Add(new sMinMax(0.5f, 1.0f));
            print("WARNING: Spawner has no hazard spawn timer. Creating element with 0.5->1.0 seconds.");
        }

        // All spawnpoints are active at the start of the game.
        spawnSetNextAvailableTick = new List<float>();
        for ( int i = 0; i < spawnpointSets.Count; i++ ) { spawnSetNextAvailableTick.Add(0f); }

        // Set up all ticks to match a reasonable timer value before the game starts.
        // Otherwise objects will spawn the same frame that the Spawner routine begins.
        int SELECT_RATE = Mathf.Clamp(level, 0, objectiveSpawnTimer.Count - 1);
        objectiveSpawnTick = UnityEngine.Random.Range(objectiveSpawnTimer[SELECT_RATE].min, objectiveSpawnTimer[SELECT_RATE].max);
        SELECT_RATE = Mathf.Clamp(level, 0, hazardSpawnTimer.Count - 1);
        hazardSpawnTick = UnityEngine.Random.Range(hazardSpawnTimer[SELECT_RATE].min, hazardSpawnTimer[SELECT_RATE].max);

        StartSpawnerRoutine();
    }

    // The Spawner passes a spawn command to actors listed as one of its spawnpoints.
    // Spawnpoint availability for use is determined by checking if its spawn set availability ticker is down.
    // From the available spawnpoint sets, the Spawner chooses a random set, and random spawnpoint within the set...
    // And PASSES a spawn command to that spawnpoint.
    // Afterwards, the spawn set's availability ticker is set and that set cannot be used until it is down.
    public virtual cActor Generate(cActor SPAWNED) {
        if (SPAWNED == null) { return null; }

        // Check for available columns. Note that a default list has a count of 1 with null or 0 entry.
        bool bCOLUMN_AVAILABLE=false;
        List<int> AVAILABLE_COLUMNS = new List<int>();

        for ( int i = 0; i < spawnpointSets.Count; i++ ) {
            if ( spawnSetNextAvailableTick[i] <= 0 ) {
                AVAILABLE_COLUMNS.Add(i);
                bCOLUMN_AVAILABLE = true;
            }
        }
        if ( !bCOLUMN_AVAILABLE ) { return null; }

        // Select a spawnpoint from any of the available columns
        int SELECTED_COLUMN = AVAILABLE_COLUMNS[UnityEngine.Random.Range(0, AVAILABLE_COLUMNS.Count)];
        int SELECTED_WINDOW = UnityEngine.Random.Range(0, spawnpointSets[SELECTED_COLUMN].spawnpoints.Count);

        cActor CHOSEN_SPAWNPOINT = spawnpointSets[SELECTED_COLUMN].spawnpoints[SELECTED_WINDOW];
        if ( CHOSEN_SPAWNPOINT == null ) { return null; }

        // Tell the spawnpoint ot spawn instance of the given actor
        // Set the column ticker to mark it as unavailable until ticked down
        cActor INSTANCE = CHOSEN_SPAWNPOINT.Spawn(SPAWNED);
        spawnSetNextAvailableTick[SELECTED_COLUMN] = spawnSetNextAvailableTimer;

        return INSTANCE;
    }

    // The Spawner will continue to step its spawn timers so long as its routine is in play.
    // This routine can be initiated and interrupted in-game via starting the game, pauses, resumes, and so on.
    public void SetDifficulty(int LEVEL) {
        if ( LEVEL < 0 ) {
            print("Cannot set difficulty below level 0. Setting difficulty to 0.");
            LEVEL = 0;
        }
        level = LEVEL;
    }
    public void StopSpawnerRoutine() {
        if ( cofxnSpawnerRoutine != null ) { StopCoroutine(cofxnSpawnerRoutine); }
    }
    public void StartSpawnerRoutine() {
        StopSpawnerRoutine();
        cofxnSpawnerRoutine = StartCoroutine(RunSpawnerRoutine());
    }
    IEnumerator RunSpawnerRoutine() {
        // Continue running routine until stopped by an external command
        while ( true ){

            // If the game is paused
            while ( bExecutionPaused ) { yield return null; }

            // Update spawnpoint availability
            for ( int i = 0; i < spawnpointSets.Count; i++ ) {
                if ( spawnSetNextAvailableTick[i] > 0 ) { spawnSetNextAvailableTick[i] -= Time.deltaTime; }
            }

            // Spawn the objective at intervals
            // Yield steps to avoid rare case where both spawns are run in a single frame
            StepObjectiveSpawner();
            yield return null;
            StepHazardSpawner();

            yield return null;
        }
    }

    // Tick and Timer steppers. Each time these functions are called, spawning ticks move toward zero.
    // When a tick hits zero, a spawn is triggered, and the tick is reset.
    void StepObjectiveSpawner() {
        if ( objectiveSpawnTick > 0 ) { objectiveSpawnTick -= Time.deltaTime; }
        else {
            if ( objectives.Count > 0 ) { Generate(objectives[UnityEngine.Random.Range(0, objectives.Count)]); }
            int SELECT_RATE = Mathf.Min(level, objectiveSpawnTimer.Count - 1);
            objectiveSpawnTick = UnityEngine.Random.Range(objectiveSpawnTimer[SELECT_RATE].min, objectiveSpawnTimer[SELECT_RATE].max);
        }
    }
    void StepHazardSpawner() {
        if ( hazardSpawnTick > 0 ) { hazardSpawnTick -= Time.deltaTime; }
        else {
            if ( hazards.Count > 0 ) { Generate(hazards[UnityEngine.Random.Range(0, hazards.Count)]); }
            int SELECT_RATE = Mathf.Min(level, hazardSpawnTimer.Count - 1);
            hazardSpawnTick = UnityEngine.Random.Range(hazardSpawnTimer[SELECT_RATE].min, hazardSpawnTimer[SELECT_RATE].max);
        }
    }
}
<file_sep>/Assets/Resources/Game/Actors/Physical/Interactive/cVehicle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cVehicle : cPhysicalObject {
    protected cGameManager scoreKeeper;
    protected cPlayer player;

    public override IEnumerator PostBeginPlay() {
        yield return new WaitForEndOfFrame();
        scoreKeeper = FindObjectOfType<cGameManager>();
        player = FindObjectOfType<cPlayer>();
        yield break;
    }
}
<file_sep>/Assets/Resources/Game/Actors/Physical/Interactive/Vehicle/cAmbulance.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cAmbulance : cVehicle {
    private void OnTriggerEnter2D(Collider2D collision) {
        cFallingObject OTHER = collision.GetComponent<cFallingObject>();
        if ( OTHER == null ) { return; }
        else if ( OTHER.tag == "Civilian" ) { scoreKeeper.GainScore(1); }
        else { //if ( OTHER.tag == "Crook" ) {
            // Play sound here
            player.FailedObjective();
        }
        Destroy(OTHER.gameObject);
    }
}
<file_sep>/Assets/Resources/Game/Actors/Physical/cPhysicalObject.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// Declarations
[Serializable]
public partial class cPhysicalObject : cActor {
    // Movement coroutine handling
    new protected Rigidbody2D rigidbody;
    private delegate IEnumerator delegateMoveType(Vector2 VECTOR, float MODIFIER);
    private event delegateMoveType selectedMoveType;
    Coroutine cofxnMoveType;
    bool bIsMoving;

    protected override void Start() {
        rigidbody = GetComponent<Rigidbody2D>();
        selectedMoveType = MoveTypeQuadratic;
        base.Start();
    }
}

// Movement scripts
public partial class cPhysicalObject {
    protected override void OnDestroy() {
        base.OnDestroy();
        bIsMoving = false;
        if ( cofxnMoveType != null ) { StopCoroutine(cofxnMoveType); }
    }

    protected void StartMove(Vector2 TRANSLATION_VECTOR, float MODIFIER) {
        float x, y;
        x = Mathf.Round(transform.position.x / 0.32f) * 0.32f;
        y = Mathf.Round(transform.position.y / 0.32f) * 0.32f;

        transform.position = new Vector2(x,y);

        bIsMoving = true;
        if (cofxnMoveType != null) {
            StopCoroutine(cofxnMoveType);
        }
        cofxnMoveType = StartCoroutine(selectedMoveType(TRANSLATION_VECTOR, MODIFIER));
    }
    protected IEnumerator MoveTypeInstant(Vector2 TRANSLATION, float DELAY) {
        Vector2 END = rigidbody.position + TRANSLATION;
        yield return new WaitForSeconds(DELAY);
        rigidbody.MovePosition(END);
        bIsMoving = false;
    }
    protected IEnumerator MoveTypeLinear(Vector2 TRANSLATION, float MOVE_TIME){
        float INVERSE_MOVE_TIME = 1f/MOVE_TIME;
        float START_TIME = Time.time;
        float END_TIME = START_TIME + MOVE_TIME;
        Vector2 START = rigidbody.position;
        Vector2 END = START + TRANSLATION;

        while (Time.time < END_TIME) {
            rigidbody.MovePosition(START + TRANSLATION * (Time.time-START_TIME)*INVERSE_MOVE_TIME);
            yield return null;
        }
        rigidbody.MovePosition(END);
        bIsMoving = false;
    }
    protected IEnumerator MoveTypeQuadratic(Vector2 TRANSLATION, float MOVE_TIME) {
        float SINE_MOD = 180f / MOVE_TIME;
        float START_TIME = Time.time;
        float END_TIME = START_TIME + MOVE_TIME;
        Vector2 START = rigidbody.position;
        Vector2 END = START + TRANSLATION;

        while (Time.time < END_TIME) {
            rigidbody.MovePosition(START + TRANSLATION * (Mathf.Sin(Mathf.Deg2Rad * (-90f + (Time.time - START_TIME) * SINE_MOD))+1f)/2f);
            yield return null;
        }
        rigidbody.MovePosition(END);
        bIsMoving = false;
    }
}

// AI inputs
public partial class cPhysicalObject {
    public Collider2D[] DetectObjects(Vector2 center) {
        Collider2D[] hitColliders = Physics2D.OverlapPointAll(center);
        return hitColliders;
    }
}
//    public bool CheckBlockingAdjacent(Vector2 TRANSLATION) {
//        Vector2 ADJACENT = (Vector2)transform.position + TRANSLATION;
//        Collider2D[] DETECTED_OBJECTS = DetectObjects(ADJACENT);
//
//        foreach ( Collider2D OTHER in DETECTED_OBJECTS ) {
//            cTile TILE_OTHER = OTHER.GetComponent<cTile>();
//            if ( TILE_OTHER != null ) {
//                if ( TILE_OTHER.CheckIfBlocked(GetComponent<cPhysicalObject>(), traversibleTerrain) ) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }<file_sep>/Assets/Resources/Game/cActor.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
struct sMinMax {
    public float min;
    public float max;

    public sMinMax(float MIN, float MAX) {
        min = MIN;
        max = MAX;
    }
}

public class cActor : MonoBehaviour {
    protected bool bExecutionPaused;
    Coroutine cofxnMovePattern;

    protected virtual void OnDestroy() {
        if ( cofxnMovePattern != null ) { StopCoroutine(cofxnMovePattern); }
    }
    protected virtual void Start() {
        StartCoroutine(PostBeginPlay());
    }

    public virtual IEnumerator PostBeginPlay() {
        yield return new WaitForEndOfFrame();
        // Do stuff here
        yield break;
    }

    public virtual cActor Spawn(cActor SPAWNED) {
        if ( SPAWNED == null ) return null;

        cActor INSTANCE = Instantiate(SPAWNED);
        SPAWNED.transform.position = transform.position;

        return INSTANCE;
    }

    public virtual void ExecutionPause() { bExecutionPaused = true; }
    public virtual void ExecutionResume() { bExecutionPaused = false; }
    public virtual void MakeMove() {
        if ( cofxnMovePattern != null ) { StopCoroutine(cofxnMovePattern); }
        cofxnMovePattern = StartCoroutine(RunMovePattern());
    }
    protected virtual IEnumerator RunMovePattern() {
        // If paused, do nothing until unpaused
        while ( bExecutionPaused ) { yield return null; }

        // Execute behavior patterns here...
        yield return null;

        // End turn
        yield break;
    }
}<file_sep>/Assets/Resources/Game/Actors/Physical/Player/cPlayer.cs
using UnityEngine;
using System.Collections;

public partial class cPlayer : cPhysicalObject {
    [Header("BOUNCE TARGETS")]
    [SerializeField] private cAmbulance ambulance;
    [SerializeField] private cSWAT swat;
    [Space(10)]

    [Header("PLAYER PROPERTIES")]
    [SerializeField] private float defaultStunTimer;
    [SerializeField] private float runSpeed;
    private float stunTick;
    [Space(10)]

    [Header("ANIMATION")]
    private Animator animator;
    [SerializeField] private float idleMarginWidth;
    private sMinMax idleMargins;
    [Space(10)]

    [Header("MOUSE MOVEMENT")]
    [SerializeField] private bool bClampX;
    [SerializeField] private bool bClampY;
    [SerializeField] private sMinMax ClampX;
    [SerializeField] private sMinMax ClampY;
    private Vector3 mousePosition;

    private enum enumDirection {
        Left,
        Right
    };
    private enumDirection tiltDirection;

    protected override void Start() {
        base.Start();

        bool bFAILED_INITIALIZATION = false;
        if ( ambulance == null ) { bFAILED_INITIALIZATION = true; print("ERROR: The Player is not connected to and instance of the Ambulance car to bounce civilians."); }
        if ( swat == null ) { bFAILED_INITIALIZATION = true; print("ERROR: The Player is not connected to and instance of the SWAT car to bounce crooks."); }

        if ( bFAILED_INITIALIZATION ) { Destroy(gameObject); print("ERROR: Player destroyed. The player must have connections to an Ambulance and SWAT car."); }

        animator = GetComponent<Animator>();
    }
    public override IEnumerator PostBeginPlay() {
        yield return new WaitForEndOfFrame();
        GotoIdle();
        yield break;
    }

    public void FailedObjective() { Stun(); }
    public void Stun( float SECONDS = -1f ) {
        if ( SECONDS < 0 ) { SECONDS = defaultStunTimer; }
        stunTick = SECONDS;
        animator.SetTrigger("Trigger_Dizzy");
    }
    public void GotoIdle() {
        if ( tiltDirection == enumDirection.Left ) { animator.SetTrigger("Trigger_IdleLeft"); }
        else { animator.SetTrigger("Trigger_IdleRight"); }

        // Set up idle margins
        idleMargins.min = transform.position.x - idleMarginWidth*0.5f;
        idleMargins.max = transform.position.x + idleMarginWidth*0.5f;
    }
    public void ChangeTilt() {
        if ( tiltDirection == enumDirection.Left ) { tiltDirection = enumDirection.Right; }
        else { tiltDirection = enumDirection.Left; }

        if ( stunTick <= 0 ) { GotoIdle(); }
    }

    private void Update() {
        // Update trampoline tilt direction
        if ( Input.GetMouseButtonDown(0) ) { ChangeTilt(); }

        if ( stunTick > 0 ) {
            stunTick -= Time.deltaTime;
            if ( stunTick <= 0 ) { GotoIdle(); }
            return;
        }

        // Update mouse position
        mousePosition = Input.mousePosition;
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
        if ( bClampX ) { mousePosition.x = Mathf.Clamp(mousePosition.x, ClampX.min, ClampX.max); }
        if ( bClampY ) { mousePosition.y = Mathf.Clamp(mousePosition.y, ClampY.min, ClampY.max); }

        // If the mouse is moving outside of a small "idle" margin, the player will run toward the mouse position
        if ( mousePosition.x < idleMargins.min || mousePosition.x > idleMargins.max ) {

            // Set up new idle margins
            if ( mousePosition.x < idleMargins.min ) {
                idleMargins.min = mousePosition.x;
                idleMargins.max = idleMargins.min + idleMarginWidth;
            }
            else {
                idleMargins.max = mousePosition.x;
                idleMargins.min = idleMargins.max - idleMarginWidth;
            }
        }

        // Move the player toward the idle margins
        bool bRunning=false;
        if ( transform.position.x > idleMargins.max ) { bRunning = true; transform.position = (Vector2)transform.position + new Vector2(-Mathf.Min(transform.position.x - idleMargins.max, runSpeed * Time.deltaTime), 0f); }
        else if ( transform.position.x < idleMargins.min ) { bRunning = true; transform.position = (Vector2)transform.position + new Vector2(Mathf.Min(idleMargins.min - transform.position.x, runSpeed * Time.deltaTime), 0f); }
        // Trigger running animation
        if ( bRunning ) {
            if ( tiltDirection == enumDirection.Left ) {
                if ( !animator.GetCurrentAnimatorStateInfo(0).IsName("Player_RunLeft") ) { animator.SetTrigger("Trigger_RunLeft"); }
            }
            else { // tiltDirection == enumDirection.Right
                if ( !animator.GetCurrentAnimatorStateInfo(0).IsName("Player_RunRight") ) { animator.SetTrigger("Trigger_RunRight"); }
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D collision) {
        cFallingObject OTHER = collision.GetComponent<cFallingObject>();
        if ( OTHER == null ) { return; }
        else if ( OTHER.tag == "Crook" || OTHER.tag == "Civilian" ) {
            Rigidbody2D OTHER_RIGIDBODY = OTHER.GetComponent<Rigidbody2D>();
            if ( OTHER_RIGIDBODY.velocity.y > 0 ) { return; }

            // Depending on the trampoline's tilt direction, set velocity so the objective goes either to the SWAT or Ambulance
            float NEW_VELOCITY_X;
            float NEW_VELOCITY_Y = Mathf.Abs(OTHER_RIGIDBODY.velocity.y) * UnityEngine.Random.Range(0.7f, 0.8f);
            if ( tiltDirection == enumDirection.Left ) {
                NEW_VELOCITY_X = -(swat.transform.position.x - OTHER.transform.position.x) / (NEW_VELOCITY_Y / Physics2D.gravity.y);
                OTHER_RIGIDBODY.angularVelocity += UnityEngine.Random.Range(90f, 180f);
            } else {
                NEW_VELOCITY_X = -(ambulance.transform.position.x - OTHER.transform.position.x) / (NEW_VELOCITY_Y / Physics2D.gravity.y);
                OTHER_RIGIDBODY.angularVelocity -= UnityEngine.Random.Range(90f, 180f);
            }
            OTHER_RIGIDBODY.velocity = new Vector2(NEW_VELOCITY_X * 0.5f, NEW_VELOCITY_Y);
        }
    }
}
    //: cPawn {
    //    public Texture healthIcon;
    //    public Rect healthIconDisplay = new Rect(Screen.width-64, 0, 32, 32);
    //    public Rect healthValueDisplay = new Rect(Screen.width-32, 0, 32, 32);

    //    protected override void Start() {
    //        base.Start();
    //    }
    //
    //    private void OnGUI() {
    //        healthIconDisplay.position = new Vector2(Screen.width - 64f, 0);
    //        healthValueDisplay.position = new Vector2(Screen.width - 32f, 0);
    //        GUI.DrawTexture(healthIconDisplay, healthIcon, ScaleMode.StretchToFill, true, 1.0f);
    //        GUI.Label(healthValueDisplay, "" + health);
    //    }

    //    protected override IEnumerator RunMovePattern() {
    //
    //        // Do not run calculations until the player is done moving
    //        while ( bIsMoving ) { yield return null; }
    //
    //        // If the player is dead, go ahead and skip their turn
    //        if ( health < 1 ) {
    //            // End of turn
    //            bTurnInProgress = false;
    //            yield break;
    //        }
    //
    //        // Now, wait for the player to make a legal move into an empty nearby space
    //        bool bMOVE_BLOCKED;
    //        do {
    //            int HORIZONTAL;
    //            int VERTICAL;
    //            bool TRIED_BOMB = false;
    //
    //            // First, grab the player's directional input. Cannot move diagonally.
    //            do {
    //                VERTICAL = (int)(Input.GetAxisRaw("Vertical"));
    //                HORIZONTAL = (int)(Input.GetAxisRaw("Horizontal"));
    //
    //                // If the player presses SPACE, skip turns
    //                if ( Input.GetKey(KeyCode.Space) ) {
    //                    // End of turn
    //                    bTurnInProgress = false;
    //                    yield break;
    //                }
    //                // If the player presses "F", try and activate a bomb
    //                else if ( Input.GetKeyDown(KeyCode.F) && !TRIED_BOMB ) {
    //                    TRIED_BOMB = true;
    //                    cItem BOMB_ITEM = inventory.FindItem<cPowderBomb>();
    //                    if ( BOMB_ITEM != null ) {
    //                        // If the player has at least one key, use it to unlock the door, and allow the player through
    //                        cPowderBomb BOMB = BOMB_ITEM.GetComponent<cPowderBomb>();
    //                        if ( BOMB.charges > 0 ) {
    //                            BOMB.Activate();
    //                            yield return new WaitForSeconds(moveSpeed);
    //
    //                            // End of turn
    //                            bTurnInProgress = false;
    //                            yield break;
    //                        }
    //                    }
    //                    print("You have no bombs!");
    //                }
    //                yield return null;
    //            } while ( HORIZONTAL == 0 && VERTICAL == 0 );
    //            if ( HORIZONTAL != 0 ) { VERTICAL = 0; }
    //
    //            // With player's input, determine if objects in selected adjacent cell are blocking.
    //            // Only one blocking object is required to count as blocking
    //            Vector2 DESIRED_MOVE = new Vector2(HORIZONTAL, VERTICAL) * 0.32f;
    //            bMOVE_BLOCKED = CheckBlockingAdjacent(DESIRED_MOVE);
    //
    //            // If there were no blocking objects in the adjacent cell, the player can move there.
    //            if ( !bMOVE_BLOCKED ) {
    //                StartMove(DESIRED_MOVE, moveSpeed);
    //                while ( bIsMoving ) { yield return null; }
    //
    //                // End of turn
    //                bTurnInProgress = false;
    //                yield break;
    //            }
    //
    //            // Repeat loop until the player makes a move into an open tile
    //            yield return null;
    //        } while (bMOVE_BLOCKED);
    //    }

    //    public override void TakeDamage(cPhysicalObject INSTIGATOR, int DAMAGE, enumDamageType TYPE = enumDamageType.Normal, Vector2 DIRECTION = default(Vector2)) {
    //        health -= DAMAGE;
    //        print("OUCH! " + INSTIGATOR.name + " hit you for "+DAMAGE+" damage!");
    //        if ( health <= 0 ) {
    //            StartCoroutine(Died(INSTIGATOR));
    //        }
    //    }

    //    public virtual IEnumerator Died(cPhysicalObject INSTIGATOR) {
    //        print("You have been killed by "+INSTIGATOR.name);
    //        yield return new WaitForSeconds(3f);
    //        Application.LoadLevel(Application.loadedLevel);
    //        yield break;
    //    }

    //    virtual protected void OnTriggerEnter2D(Collider2D OTHER) {
    //        cItem ITEM_OTHER = OTHER.GetComponent<cItem>();
    //        if (ITEM_OTHER != null) {
    //            inventory.PickUp(ITEM_OTHER);
    //        }
    //    }<file_sep>/Assets/Resources/Game/Gameplay/cGameManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// The Game Manager for Trampoline Rush is the hub of central information for in-game actors.
/// Information such as difficulty, waves/levels completed, score, penalties, audio/graphics preferences
/// and the like are stored on a single accessible game object.
/// This Game Manager is also in charge of executing targeted commands at related actor groups in order to...
/// halt or resume routines, switch game and menu states, call a game reset, update actor information, etc.
/// </summary>

[Serializable]
public class cGameManager : cActor {
    //Static instance of GameManager which allows it to be accessed by any other script.
    public static cGameManager instance = null;

    [Header("GAME PROPERTIES")]
    [SerializeField] private cSpawner waveSpawner;
    [SerializeField] private List<float> gravityScale;
    private Vector2 defaultGravity;

    public int level;
    public int score;
    public List<int> scoreToNextLevel;

    protected override void Start() {
        base.Start();
        if ( instance == null ) { instance = this; }
        else { Destroy(this); }
        if ( waveSpawner == null ) { print("Game Controller was not linked to a wave spawner, or wave spawner was not found."); }
        if ( gravityScale.Count < 1 ) { gravityScale.Add(1.0f); }
        defaultGravity = Physics2D.gravity;
        Physics2D.gravity = defaultGravity * gravityScale[Mathf.Min(level,gravityScale.Count-1)];
    }
    public override IEnumerator PostBeginPlay() {
        yield return new WaitForEndOfFrame();
        waveSpawner = FindObjectOfType<cSpawner>();
        yield break;
    }

    public void GainScore(int SCORE) {
        score += SCORE;
        if ( level < scoreToNextLevel.Count ) {
            if ( score > scoreToNextLevel[level] ) { GainLevel(); }
        }
    }
    private void GainLevel() {
        level++;
        waveSpawner.SetDifficulty(level);
        Physics2D.gravity = defaultGravity * gravityScale[Mathf.Min(level, gravityScale.Count - 1)];
    }

    private void OnGUI() {
        GUI.Label(new Rect(0, 0, 32, 32), "Level:"+level);
        GUI.Label(new Rect(0, 32, 32, 32), "Score:" + score);
    }
}


text:
<file_sep>import AutoDictionary from "./AutoDictionary";

function App() {
  return (

        <AutoDictionary />

  );
}

export default App;
<file_sep>import React, { useState, useEffect } from "react";

/* material ui imports */
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { createFilterOptions } from "@material-ui/lab/Autocomplete";

/* toastify imports */
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

/* styling */
const useStyles = makeStyles({
  inputRoot: {
    color: "#eee",
    "& .MuiOutlinedInput-notchedOutline": {
      borderRight: 0,
      borderWidth: "1px",
      borderColor: "#e0e0e0 !important",
      color: "#fff",
      borderRadius: "3px 0 0 3px",
      boxShadow:
        "0px 2px 4px -1px rgba(0,0,0,0.2), 0px 4px 5px 0px rgba(0,0,0,0.14), 0px 1px 10px 0px rgba(0,0,0,0.12)",
    },
    "& .MuiSvgIcon-root": {
      color: "#fff",
    },
  },
});
const textStyles = makeStyles({
  root: {
    "& label": {
      color: "#eee",
    },
    "& .MuiInputLabel-shrink": {
      color: "#eee",
    },
  },
});

/* dictionary component */
export default function AutoDictionary() {
  const [dictionary, setDictionary] = useState([]);

  /* fetch local data */
  const getData = () => {
    fetch("data/dictionary.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (myJson) {
        setDictionary(myJson);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  /* bring in custom styles*/
  const classes = useStyles();
  const textClasses = textStyles();

  /* map through local words.json */
  const options = dictionary.map((option) => {
    const firstLetter = option.Fieldname[0].toUpperCase();
    return {
      firstLetter: /[0-9]/.test(firstLetter) ? "0-9" : firstLetter,
      ...option,
    };
  });

  /* state controllers */
  const [inputValue, setInputValue] = useState("");

  /* toast function */
  const ToastMsg = ({ newInputValue }) => (
    <>
      Copied {newInputValue} to the
      clipboard
    </>
  );

  const notify = (newInputValue) =>
    toast(<ToastMsg newInputValue={newInputValue} />);

  /* filter options */
  const filterOptions = createFilterOptions({
    matchFrom: "any",
    trim: "true",
  });

  return (

      <Autocomplete
        /* get value on input change for copy to clipboard function */
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          navigator.clipboard.writeText(newInputValue);
          setInputValue(newInputValue);
        }}
        onChange={(event, newInputValue) => {
          if (event.type === "click" || event.type === "keydown") {
            notify(newInputValue.Fieldname);
          }
        }}
        /* filter options */
        filterOptions={filterOptions}
        /* identity */
        id='combo-box'
        classes={classes}
        /* general config */
        disableClearable
        forcePopupIcon={true}
        options={options.sort(
          (a, b) => -b.firstLetter.localeCompare(a.firstLetter)
        )}
        groupBy={(option) => option.firstLetter}
        getOptionSelected={(option, inputValue) =>
          option.Fieldname === inputValue.Fieldname
        }
        getOptionLabel={(option) => option.Fieldname}
        style={{ width: 500 }}
        renderInput={(params) => (
          <TextField
            {...params}
            classes={textClasses}
            label='Form Field Dictionary'
            variant='outlined'
          />
        )}
      />
      <Button
        variant='contained'
        style={{ borderRadius: "0 3px 3px 0" }}
        onClick={() => {
          if (inputValue !== '') {
            navigator.clipboard.writeText(inputValue);
            notify(inputValue);
          }
        }}
      >

          Copy
      </Button>
      <ToastContainer
        position='top-center'
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
      />

  );
}

branch_name: refs/heads/main

repo_language: JavaScript

repo_name: aidanjmaunder/form-building-dictionary


text: <file_sep>Hop to put the things in

repo_language: Text


text:
<repo_name>iamxuas/swagger-demo<file_sep>/src/main/java/com/swagger/SwaggerConfig.java
package com.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * SwaggerConfigInfo
 *
 * @author: Xuas
 * @date: 2018-06-03 23:53
 */
@Configuration
// 使用@Configuration注解，等价于XML中配置beans，使用@Bean，等价于XML中配置bean
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swagger"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger示例标题")
                .description("Swagger示例标题描述")
                .termsOfServiceUrl("http://www.baidu.com")
                .version("1.0")
                .contact(new Contact("iamxuas", "http://github.com/iamxuas", "<EMAIL>"))
                .build();
    }
}

branch_name: refs/heads/master

repo_language: Java

repo_name: iamxuas/swagger-demo


text:
<repo_name>fermosh/fermosh.github.io<file_sep>/README.md
FlappyBird-in-pure-JavaScript
=============================

FlappyBird written in pure JavaScript!

Works in Firefox, Chrome, Safari, maybe in IE9?(let me know if it does :))

![Screenshot](https://raw.githubusercontent.com/loveky/FlappyBird-in-pure-JavaScript/master/images/screenshot.png)

repo_language: Markdown


text:
<repo_name>Mohan-blog/Multibranch<file_sep>/settings.gradle
include ':app'
rootProject.name='AndroidBranchGit'

repo_language: Gradle

repo_name: Mohan-blog/Multibranch


text:
<file_sep>.PHONY: test release doc

test:
	flake8 queued_storage --ignore=E501,E127,E128,E124
	coverage run --branch --source=queued_storage `which django-admin.py` test queued_storage
	coverage report --omit=queued_storage/test*

release:
	python setup.py sdist bdist_wheel register upload -s

doc:
	cd docs; make html; cd ..

branch_name: HEAD

repo_language: Makefile

repo_name: jaddison/django-queued-storage


text:
<file_sep># Angular
Basic examples and custom architecture
<file_sep>This is a custom architecture of ng4

STEPS TO IMPLEMENT:

1. Clone the repository
2. Run: npm install
3. For Development build: npm run build
4. For Production build: npm run build:prod

* NOTE: Plese verify the versions of node_modules in package.json file in case of any package error.

repo_name: juhidave/Angular


text:
<file_sep>const cars = require('./data/cars');
const cart = require('./cart')

describe('Cart Properties:', () => {
    test('Is cart an empty array?', () => {
        expect(Array.isArray(cart.cart)).toBe(true)
        expect(cart.cart.length).toBe(0)
    })

    test('Is total 0?', () => {
        expect(+cart.total).toBe(0)
    })

})

describe('Cart Methods:', () => {
    afterEach(function () {
        cart.cart = [];
        cart.total = 0;
    });

    test('addToCart needs to add 1 of a product to cart', () => {
        cart.addToCart(cars[0])
        cart.addToCart(cars[1])

        expect(cart.cart.length).toBe(2);
        expect(cart.cart[0]).toBe(cars[0]);
        expect(cart.cart[1]).toBe(cars[1]);
    })

    test('addToCart needs to increase total by price of product when added to cart', ()=>{
        cart.addToCart(cars[0]);

        expect(cart.total).toBe(8605);

        cart.addToCart(cars[1]);

        expect(cart.total).toBe(8605+48539);
    })

    test('removeFromCart should remove a car from cart and maintain order of cart', ()=>{
        cart.addToCart(cars[1]);
        cart.addToCart(cars[2]);
        cart.addToCart(cars[3]);
        cart.addToCart(cars[4]);

        cart.removeFromCart(1, cars[2].price);

        expect(cart.cart.length).toBe(3);
        expect(cart.cart[0]).toBe(cars[1]);
        expect(cart.cart[1]).toBe(cars[3]);
        expect(cart.cart[2]).toBe(cars[4]);
    })

    test('removeFromCart should decrease total by price of car removed', ()=>{
        cart.addToCart(cars[1]);
        cart.addToCart(cars[2]);
        cart.addToCart(cars[3]);
        cart.addToCart(cars[4]);

        cart.removeFromCart(1, cars[2].price);

        expect(cart.total).toBe(48539+38506+16179)
    })

    test('checkout should empty the cart and return total to 0', ()=>{
        cart.addToCart(cars[1]);
        cart.addToCart(cars[2]);
        cart.addToCart(cars[3]);
        cart.addToCart(cars[4]);

        cart.checkout();

        expect(cart.total).toBe(0);
        expect(cart.cart.length).toBe(0);
    })
})

repo_name: FullFaceRub/unit-testing-afternoon


text:
<repo_name>zbuckley/datawarehousing-demo<file_sep>/README.md
# Data Warehousing Demo

Our group focused on the Couchbase Database

## Install and Setup

This is based on a linux system as we decided our demo would be ran <NAME>'s laptop (running Ubuntu 18.04.01 LTS)

### Docker Installation and Setup

```bash
sudo apt install docker
sudo usermod -aG docker zbuckley
```

*A restart will be necessary after the usermod comand is ran*

### Container Management

This section describes the process of starting and managing the container on your
local system.

#### Downloading/Creating/Starting Docker Container

```bash
docker run -d --name db -p 8091-8094:8091-8094 -p 11210:11210 couchbase:community
```

Or, use the convenient script provided:

```bash
./docker_image_start
```

#### Stopping the Docker container

```bash
docker stop db
```

Or, use the convenient script provided:

```bash
./docker_image_stop
```

#### Delete the Docker container

*NOTE: Deleting the container, also deletes data and configuration settings*

```bash
docker rm db
```

Or, use the convenient script provided:

```bash
./docker_image_delete
```

#### Restart the Docker Container

*Note: This assumes you've created the container, and stopped it.*

```bash
docker start db
```

Or, use the convenient script provided:

```bash
./docker_image_restart
```

## Cluster Setup

1. Open a web browser to the following address: `http://localhost:8091`
2. Startup screen should say `Couchbase Server`, and `Community Edition 6.0.0 build 1693`. The exact build number shouldn't really matter that much.
3. Select `Setup New Cluster`
4. Enter Cluster Name: `rocinante`
5. Change Admin Username: `jholden`
6. Set the password: `<PASSWORD>`
7. Select `Next: Accept Terms`
8. Accept the Terms
9. Select `Finish With Defaults`

## Sample Bucket

1. Open a web browser to the following address `http://localhost:8091`
2. Select `Settings` either on the left, or from top-right menu
3. Select `Sample Buckets` Tab
4. Select `travel-sample`
5. Select `Load Sample Data`

### Bucket Management Exploration

1. From the main menu, select `Buckets`
2. Select `travel-sample` Bucket, by clicking on the bucket Name
3. See:

  * Number of Items
  * Memory Usage
  * Disk Usage

4. Select Statistics from the right side:
5. See:

  * Lots of stats for helping to diagnose issues/monitor usage levels

### Queries (N1QL, SQL-like)

Complete Reference for [N1QL Query Language](https://docs.couchbase.com/server/4.0/n1ql/n1ql-language-reference/index.html).

1. From the main menu, select `Query` to open the `Query Editor`
2. Experiment with the sample Queries below:

#### CRUD Operations

Create, Read, Update, and Delete operations covered in this section:

As a *Read* operation, lets view the first 10 records in travel sample.
*NOTE: throughout the N1QL queries we'll need to use back-ticks in order refer to travel-sample*

```SQL
SELECT * FROM `travel-sample` LIMIT 10;
```

You can view the results in different formats, by selecting a different tab
in the results area of the editor. Select `Table` for example.

Lots of airlines... As another *Read* operation, lets see if there are other types:

```SQL
SELECT * FROM `travel-sample` WHERE type != 'airline' LIMIT 10;
```

Interesting.. Can we get a list of all the different types (*Read* Operation)?

```SQL
SELECT DISTINCT type FROM `travel-sample`;
```

How many airlines are in our bucket (*Read* Operation)?

```SQL
SELECT COUNT(name) FROM `travel-sample` WHERE type == 'airline';
```

Let's look for an airline to delete (*Read* Operation).
*NOTE: META().id to show the primary key for the documents*

```SQL
SELECT name, id, META().id as document_key FROM `travel-sample` WHERE type == 'airline';
```

Let's go for... Locair. First, here's a query by primary key for the airline document (*Read* Operation)

```SQL
SELECT * FROM default WHERE META().id = "airline_10748";
```

Ok, our first *Delete* operation, let's delete Locair airline.
We'll use the `RETURNING` clause to get back the contents of the airline document,
and it's primary key, as we delete it.

```SQL
DELETE FROM `travel-sample` WHERE type == 'airline' AND name == 'Locair' RETURNING *, META().id as document_key;
```

Using the primary Key query above, lets verify that the document is no longer in no longer in the database.
NOTE: While the query below does work, according to the [N1QL Docs](https://docs.couchbase.com/server/4.1/developer-guide/retrieving.html), it is typically recommended to use the key-value api when the key is known

```SQL
SELECT * FROM `travel-sample` WHERE META().id = "airline_10748";
```

As our first *Create* Operation, let's see how we would put Locair's airline record back into the database:
*NOTE: To restore the document, and maintain relationships between this document and others, we need to
ensure that the key we insert the document under, comes from the deletion output above.*

```SQL
INSERT INTO `travel-sample` (KEY, VALUE)
VALUES(
    "airline_10748",
    {  "callsign": "LOCAIR",
      "country": "United States",
      "iata": "ZQ",
      "icao": "LOC",
      "id": 10748,
      "name": "Locair",
      "type": "airline"
    }
) RETURNING META().id as document_key, *;
```

Let's check that Locair is back in the system (*Read* Operation):

```SQL
SELECT * FROM `travel-sample` WHERE META().id = "airline_10748";
```

Now, as our first *Update* operation, lets update LOCAIR's country, by replacing the whole document:

```SQL
UPSERT INTO `travel-sample` (KEY, VALUE)
VALUES(
    "airline_10748",
    {  "callsign": "LOCAIR",
      "country": "Australia",
      "iata": "ZQ",
      "icao": "LOC",
      "id": 10748,
      "name": "Locair",
      "type": "airline"
    }
) RETURNING META().id as document_key, *;
```

Let's check that the update occurred (*Read* Operation):

```SQL
SELECT * FROM `travel-sample` WHERE META().id = "airline_10748";
```

Now, we'll change all airlines with country = Australia to AU... but lets do that,
without replacing all the documents. Instead our *Update* operation should only change
the value we care about in each document:

```SQL
UPDATE `travel-sample`
SET country = "AU"
WHERE type = "airline"
AND country = "Australia"
RETURNING META().id as document_key, *;
```

We can see from the return information, that Locair was updated... and appears to have
been the only document where `country = 'AU'`. For completeness, Let's check that
using our *Read* operation from above, shows Locair being updated.

```SQL
SELECT * FROM `travel-sample` WHERE META().id = "airline_10748";
```

Highly recommend reviewing stats and metrics to see the effect of the operations above,
on the database performance. The metrics and monitoring available out of the box (so to speak),
are great tools.
<file_sep>/docker_image_stop
#!/bin/bash
docker stop db
<file_sep>/docker_image_restart
#!/bin/bash
docker start db
<file_sep>/docker_image_delete
#!/bin/bash
docker rm db

languages: Markdown Shell

repo_name: zbuckley/datawarehousing-demo


text:
<file_sep>let board1 = null;
let dratini = null;
let game = new Chess();
let score = 0;
let computerSide = "black";

const $ = (...args) => document.querySelector(...args);

const formatMB = (n) => {
    return (n ? (n / 1e6).toPrecision(3) : "?") + "MB";
};

const isSupported = () => {
    if (typeof WebAssembly !== "object") return false;
    const source = Uint8Array.from([
    0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 7, 8,
    1, 4, 116, 101, 115, 116, 0, 0, 10, 15, 1, 13, 0, 65, 0, 253, 17, 65, 0,
    253, 17, 253, 186, 1, 11,
    ]);
    if (
    typeof WebAssembly.validate !== "function" ||
    !WebAssembly.validate(source)
    )
    return false;
    if (typeof Atomics !== "object") return false;
    if (typeof SharedArrayBuffer !== "function") return false;
    return true;
};

const RequestProgress = ({ attrs: { url, onFinishDownload } }) => {
    let state = "INIT"; // 'LOADING', 'DONE', 'FAILED'
    let loaded = 0;
    let total = 0;

    const oninit = () => {
    state = "LOADING";
    m.request({
        url: url,
        method: "GET",
        responseType: "arraybuffer",
        headers: { Accept: "*/*" },
        config: (xhr) => {
        xhr.onprogress = (e) => {
            // TODO:
            // When gzip compressed, the value of "loaded/total" gets messed up.
            // On Chrome, "loaded" is the value after decompression, but on the other hand,
            // On Firefox, "loaded" is the value before decompression.
            loaded = e.loaded;
            total =
            e.total ||
            Number(
                e.target.getResponseHeader("x-decompressed-content-length")
            );
            m.redraw();
        };
        },
    }).then(
        (response) => {
        state = "DONE";
        onFinishDownload(response);
        },
        (e) => {
        console.error(e);
        state = "FAILED";
        onFinishDownload(null);
        }
    );
    };

    const view = () => {
    const fraction =
        total == -1 ? `?MB/?MB` : `${formatMB(loaded)}/${formatMB(total)}`;
    return m("span", [
        `${fraction} [${state}] `,
    ]);
    };

    return { oninit, view };
};

let engine_state = "INIT"; // 'READY', 'FAILED'

const App = () => {
    let output = "";
    let tail_mode = true;

    const sendCommand = () => {
    const command = $("#command").value;
    if (command.length > 0) {
        dratini.postMessage(command);
    }
    };

    const takeBack = () => {
    console.log("Takeback");
    game.undo();
    game.undo();
    board1.position(game.fen())
    engine_state = "PROCESSING...";
    m.redraw();
    setTimeout(function(){
        dratini.postMessage("position " + game.fen());
    }, 100);
    }

    const flip = () => {
    console.log("Flipping");
    if(computerSide === "white") {
        computerSide = "black";
    } else {
        computerSide = "white";
    }
    score = -score;
    // if we flip now it's the computers' turn
    engine_state = "THINKING";
    m.redraw();
    setTimeout(function() {
        dratini.postMessage("position " + game.fen());
        dratini.postMessage("go");
    }, 100);
    }

    const reset = () => {
    console.log("Resetting position");
    game.reset();
    board1.position(game.fen());
    score = 0;
    m.redraw();
    if(computerSide === "white") {
        dratini.postMessage("position " + game.fen());
        dratini.postMessage("go");
    }
    }

    const parseLine = (line) => {
    if(line.includes("score")) {
        words = line.split(" ");
        for(let i = 0; i < words.length; i++) {
        if(words[i] == "score") {
            score = -parseInt(words[i + 1]);
            break;
        }
        }
    }
    if(!line.includes("bestmove")) {
        return;
    }
    engine_state = "READY";
    words = line.split(" ");
    for(let i = 0; i < words.length; i++) {
        if(words[i] === "bestmove") {
        let moveStr = words[i + 1];
        console.log("Making move", moveStr)
        console.log("Prev fen was", game.fen());
        // game.move(moveStr, { sloppy: true });
        let from = moveStr[0] + moveStr[1]
        let to = moveStr[2] + moveStr[3];
        let promotion = 'Q';
        if(computerSide == "black") promotion = 'q';
        console.log(game.turn());
        let move_return = game.move({
            from: from, to: to, promotion: promotion
        });
        console.log(move_return);
        console.log("FEN is now", game.fen());
        board1.position(game.fen());
        m.redraw();
        break;
        }
    }
    }

    const scrollOutput = () => {
    if (!tail_mode) {
        return;
    }
    $("#output").scrollTo({
        top: $("#output").scrollHeight,
        behavior: "smooth",
    });
    };

    // Make error catchable
    const loadEngine = async (params) => {
    return await Dratini(params);
    };

    const onFinishDownload = (data) => {
    if (!data) {
        engine_state = "FAILED";
        m.redraw();
        return;
    }

    loadEngine({ wasmBinary: data })
        .then((_dratini) => {
        dratini = _dratini;
        engine_state = "READY";
        dratini.addMessageListener((line) => {
            parseLine(line);
            output += line + "\n";
            m.redraw();
        });
        })
        .catch((e) => {
        engine_state = "FAILED";
        throw e;
        })
        .finally(() => m.redraw());
    };

    const oninit = () => {
    engine_state = "LOADING";
    };

    const map = (value, x1, y1, x2, y2) => (value - x1) * (y2 - x2) / (y1 - x1) + x2;

    const min = (x, y) => {
    if(x < y) {
        return x;
    }
    return y;
    }

    const getColor = (score) => {
    let red = 1;
    let green = 1;
    if(score < 0) {
        red = -map(-score, 0, min(-score, 2000), 1, 255);
    } else {
        green = map(score, 0, min(score, 2000), 1, 255);
    }
    return `rgb(${red}, ${green}, 100)`;
    }

    const getSidebar = () => {
    if(engine_state === "READY") {
        return m("div#right-col", [
            m("h3#score", { style: { "background-color": "#CBCBCB", "color": getColor(score) } }, `Score is ${score}`),
            m("div#click", { onclick: takeBack }, "Take back"),
            m("div#click", { onclick: reset }, "Reset"),
            m("div#click", { onclick: flip }, "Flip")
        ]);
    } else {
        return m("div#right-col", [
            m("h3#score", { style: { "background-color": "#CBCBCB", "color": getColor(score) } }, `Score is ${score}`),
            m("div#dead-click", "Take back"),
            m("div#dead-click", "Reset"),
            m("div#dead-click", "Flip")
        ]);
    }
    }

    const view = () => {
    return m("main", [
        m("div#central-col", [
        m("div#title", "Dratini v2.0"),
        m("div#board1"),
        m("div#misc", [
            m("div", [
            "- download: ",
            m(RequestProgress, {
                url: "./lib/dratini.wasm",
                onFinishDownload,
            }),
            ]),
            m("div", `- stockfish state: ${engine_state}`),
            m("div", `- the engine plays ${computerSide}`),
            m("div", `- engine's raw UCI output:`)
        ]),
        m("div#output", { onupdate: scrollOutput }, m("pre", output)),
        ]),
        getSidebar()
    ]);
    };

    return { oninit, view };
};

m.mount($("#root"), App);

if (!isSupported()) {
    window.alert(
    "Your browser is not supported ): If you're using Chrome enable chrome://flags/#enable-webassembly-simd. If you're using Firefox enable javascript.options.wasm_simd."
    );
}

const onDrop = (source, target, piece, newPos, oldPos, orientation) => {
    // we want to check if the move is legal
    var move = game.move({
    from: source,
    to: target,
    promotion: 'q' // NOTE: always promote to a queen for example simplicity
    })

    // illegal move
    if (move === null) return 'snapback'
}

function onDragStart (source, piece, position, orientation) {
    // do not pick up pieces if the game is over
    if(game.game_over())
    return false

    // only pick up pieces for White
    if((piece.search(/^b/) !== -1 && computerSide === "white")
    || (piece.search(/^w/) !== -1 && computerSide === "black"))
    return false
}

const onSnapEnd = () => {
    board1.position(game.fen())
    engine_state = "THINKING...";
    m.redraw();
    setTimeout(function(){
    dratini.postMessage("position " + game.fen());
    dratini.postMessage("go");
    }, 100);
}

board1 = Chessboard('board1', {
    position: "start",
    draggable: true,
    onDrop: onDrop,
    onSnapEnd: onSnapEnd
});
<file_sep># Dratini NNUE Webassembly demo

Demo frontend for [Dratini](https://github.com/obalcells/Dratini)

```
npm install

npm run serve
```
# dratini-web

languages: Markdown JavaScript

repo_name: obalcells/dratini-web


text:
<file_sep>def get(grp):
    inf=[]
    if(grp=='A+'):
        lines=open('apos.txt',encoding="utf8").readlines()
        for line in lines:
            info=line.split(',')
            inf.append([info])
    elif(grp=='B+'):
        lines=open('bpos.txt',encoding="utf8").readlines()
        for line in lines:
            info=line.split(',')
            inf.append([info])
    elif(grp=='O+'):
        lines=open('opos.txt',encoding="utf8").readlines()
        for line in lines:
            info=line.split(',')
            inf.append([info])
    elif(grp=='O-'):
        lines=open('oneg.txt',encoding="utf8").readlines()
        for line in lines:
            info=line.split(',')
            inf.append([info])
    elif(grp=='AB+'):
        lines=open('abpos.txt',encoding="utf8").readlines()
        for line in lines:
            info=line.split(',')
            inf.append([info])
    return (inf)<file_sep>from flask import Flask,request
from bdgp import get

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])
def adder_page():
    if request.method=='POST':
        opt=request.form.get('bldgrp')
        inf=get(opt)
        s='''

        '''
        s+='''

The matches with blood group {} ({} matches) are as follows:

'''.format(opt,len(inf))
        for people in inf:
            s=s+'''

NAME                  :  {name}
'''.format(name=people[0].upper())
            if(people[1]=="Not given"):
                s+='''

MOBILE                :  NOT GIVEN
'''
            else:
                s+='''

MOBILE                :  {mobile}
'''.format(mobile=people[1])
            s+='''

EMAIL                 :  {email}

.......................................................................

            '''.format(email=people[2])
        s+='''

        '''
        return s
    return '''

            <form method="POST" action=".">

SELECT THE BLOOD GROUP :

            <select id="bldgrp" name="bldgrp">
                <option value="A+">A+</option>
                <option value="B+">B+</option>
                <option value="AB+">AB+</option>
                <option value="O+">O+</option>
                <option value="O-">O-</option>
            </select>
            <button class="btn btn-default" type="submit">Submit</button>

N.B. No matches for blood groups A- , B- , AB-

            </form>

    '''
<file_sep># IUT-CSE-19-Blood_Group

A project done by me to show the blood group of my batchmates so that it becomes easier to scout people for blood donation when the need arises.

Python version : 3.9\
Framework used : Flask

I scraped the data from the IUT CSE batch 19 google sheets.

See it in action : http://bloodgroup.pythonanywhere.com/

languages: Markdown Python


text:
<file_sep>const rates = [{ base: "GBP", currency: "£" }, { base: "IDR", currency: "Rp" }, { base: "ILS", currency: "₪" }, { base: "DKK", currency: "kr" }, { base: "CHF", currency: "CHF" }, { base: "CZK", currency: "Kč" }, { base: "THB", currency: "฿" }, { base: "HRK", currency: "kn" }, { base: "EUR", currency: "€" }, { base: "MYR", currency: "RM" }, { base: "CNY", currency: "¥" }, { base: "BGN", currency: "лв" }, { base: "PHP", currency: "₱" }, { base: "PLN", currency: "zł" }, { base: "BRL", currency: "\R$" }, { base: "RON", currency: "lei" }, { base: "JPY", currency: "¥" }, { base: "RUB", currency: "₽" }, { base: "KRW", currency: "₩" }, { base: "USD", currency: "$" }, { base: "HUF", currency: "Ft" }, { base: "ZAR", currency: "R" }]

let canCall = true;

const baseURL = (base, symbol = "BRL") => {
  return `https://api.ratesapi.io/api/latest?base=${base}&symbols=${symbol}`;
}

function getSelectionText() {
  var text = "";
  var activeEl = document.activeElement;
  var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
  if (
    (activeElTagName == "textarea") || (activeElTagName == "input" &&
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
    (typeof activeEl.selectionStart == "number")
  ) {
    text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
  } else if (window.getSelection) {
    text = window.getSelection().toString();
  }
  return text;
}

const interval = setInterval(()=>{
  canCall = true
}, 1000)

document.onmouseup = document.onkeyup = document.onselectionchange = () => {
  let val = getSelectionText();
  if (val == '') return

  rates.forEach(rate => {
    const currency = rate.currency.replace("$", "\\$")
    const regex = new RegExp(`^${currency}\\s?(\\d+)[.,](\\d+)?,?(\\d{2})$`)
    if (regex.test(val)) {
      console.log(rate, regex);
      const number = Number(val.replace(/\D/g, "")) / 100;
      canCall && fetchData({ base: rate.base, value: number });
    }
  })
};

async function fetchData({base, value}) {
  canCall = false;
  let data;
  await fetch(baseURL(base))
    .then(res=>res.json())
    .then(res=>{
      console.log(res)
      data = res.rates["BRL"].toFixed(2);
    })
  alert(`Convertendo.....\n
        essa moeda esta em ${data}\n
        ${value}*${data}=R$${value*data}`)
  console.log(data * value);
}

/*
chrome.storage.local.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

chrome.storage.local.get(['key'], function(result) {
  console.log('Value currently is ' + result.key);
});
*/

repo_name: eoguvo/CurrencyConverter


text:
<repo_name>sinkdwty/word_hackingLearnLib<file_sep>/README.md
# word_hackingLearnLib
play football with hack following


text: <file_sep>## calculator challenge

repo_name: Talphlanre/Calculator


text:
<repo_name>Alban42/libgdx<file_sep>/CanyonBunny/src/com/packtpub/libgdx/canyonbunny/game/WorldController.java
/*******************************************************************************
 * Copyright 2013 <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.packtpub.libgdx.canyonbunny.game;

import java.util.ArrayList;

import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.packtpub.libgdx.canyonbunny.util.CameraHelper;
import com.packtpub.libgdx.canyonbunny.util.Trigo;

public class WorldController extends InputAdapter {

	private static final String TAG = WorldController.class.getName();

	public Sprite[] testSprites;
	public ArrayList<Bullet> bullets;
	public int selectedSprite;
	public Rectangle collisionRectangle1, collisionRectangle2;
	public Sprite tmpSprite;
	public CameraHelper cameraHelper;

	Vector3 mousePos = new Vector3();
	Vector3 objectPos = new Vector3();

	Vector2 vec1 = new Vector2();
	Vector2 vec2 = new Vector2();

	public WorldController() {
		init();
	}

	private void init() {
		Gdx.input.setInputProcessor(this);
		cameraHelper = new CameraHelper();
		initTestObjects();
	}

	private void initTestObjects() {
		// init bullets
		bullets = new ArrayList<Bullet>();
		// Create the collisions rectangles
		collisionRectangle1 = new Rectangle();
		collisionRectangle2 = new Rectangle();
		// Create temporary sprite (for collisions)
		tmpSprite = new Sprite();
		// Create new array for 5 sprites
		testSprites = new Sprite[5];
		// Create empty POT-sized Pixmap with 8 bit RGBA pixel data
		final int width = 32;
		final int height = 32;
		final Pixmap pixmap = createProceduralPixmap(width, height);
		// Create a new texture from pixmap data
		final Texture texture = new Texture(pixmap);
		// Create new sprites using the just created texture
		for (int i = 0; i < testSprites.length; i++) {
			final Sprite spr = new Sprite(texture);
			// Define sprite size to be 1m x 1m in game world
			spr.setSize(1, 1);
			// Set origin to sprite�s center
			spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f);
			setRandomPosition(spr);
			while (testCollision(spr, spr)) {
				setRandomPosition(spr);
			}
			// Put new sprite into array
			testSprites[i] = spr;
		}
		// Set first sprite as selected one
		selectedSprite = 0;
	}

	private void fire(Sprite origin, float angle) {
		// Create empty POT-sized Pixmap with 8 bit RGBA pixel data
		final int width = 32;
		final int height = 32;
		final Pixmap pixmap = createProceduralPixmap(width, height);
		// Create a new texture from pixmap data
		final Texture texture = new Texture(pixmap);
		// Create new sprites using the just created texture
		final Sprite spr = new Sprite(texture);
		// Define sprite size to be 1m x 1m in game world
		spr.setSize(0.25f, 0.25f);
		// Set origin to sprite�s center
		spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f);
		setRandomPosition(spr);
		while (testCollision(spr, spr)) {
			setRandomPosition(spr);
		}
		spr.setPosition(origin.getX(), origin.getY());
		// Put new sprite into array
		bullets.add(new Bullet(spr, angle));
	}

	private void setRandomPosition(final Sprite spr) {
		final float randomX = MathUtils.random(-5.0f, 5.0f);
		final float randomY = MathUtils.random(-5.0f, 5.0f);
		spr.setPosition(randomX, randomY);
	}

	private Pixmap createProceduralPixmap(final int width, final int height) {
		final Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888);
		// Fill square with red color at 50% opacity
		pixmap.setColor(1, 0, 0, 0.5f);
		pixmap.fill();
		// Draw a yellow-colored X shape on square
		pixmap.setColor(1, 1, 0, 1);
		pixmap.drawLine(0, 0, width, height);
		pixmap.drawLine(width, 0, 0, height);
		// Draw a cyan-colored border around square
		pixmap.setColor(0, 1, 1, 1);
		pixmap.drawRectangle(0, 0, width, height);
		return pixmap;
	}

	public void update(final float deltaTime) {
		handleDebugInput(deltaTime);
		updateTestObjects(deltaTime);
		updateBullets(deltaTime);
		cameraHelper.update(deltaTime);
	}

	private void updateBullets(float deltaTime) {
		final float bulletMoveSpeed = 5 * deltaTime;
		Vector2 vector2 = new Vector2();
		Vector2 newPosition;
		for(Bullet bullet: bullets){
			vector2.set(bullet.getSprite().getX(), bullet.getSprite().getY());
			newPosition = Trigo.getPoint(vector2, bullet.getAngle(), bulletMoveSpeed);
			bullet.getSprite().setPosition(newPosition.x, newPosition.y);
		}
	}

	private void updateTestObjects(final float deltaTime) {
		final float rotation = getAngleFromSpriteAndMouse(testSprites[selectedSprite]);
		tmpSprite.set(testSprites[selectedSprite]);
		tmpSprite.setRotation(rotation);
		if (!testCollision(testSprites[selectedSprite], tmpSprite)) {
			testSprites[selectedSprite].set(tmpSprite);
		}
	}

	private float getAngleFromSpriteAndMouse(Sprite sprite) {
		objectPos.set(sprite.getX(), sprite.getY(), 0);
		mousePos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
		cameraHelper.unproject(mousePos);
		vec1.set(objectPos.x, objectPos.y);
		vec2.set(mousePos.x, mousePos.y);
		final float rotation = (float) Trigo.getAngle(vec1, vec2);
		return rotation;
	}

	private void handleDebugInput(final float deltaTime) {
		if (Gdx.app.getType() != ApplicationType.Desktop) {
			return;
		}

		// Selected Sprite Controls
		final float sprMoveSpeed = 5 * deltaTime;
		if (Gdx.input.isKeyPressed(Keys.Q)) {
			moveSelectedSprite(-sprMoveSpeed, 0);
		}
		if (Gdx.input.isKeyPressed(Keys.D)) {
			moveSelectedSprite(sprMoveSpeed, 0);
		}
		if (Gdx.input.isKeyPressed(Keys.Z)) {
			moveSelectedSprite(0, sprMoveSpeed);
		}
		if (Gdx.input.isKeyPressed(Keys.S)) {
			moveSelectedSprite(0, -sprMoveSpeed);
		}

		// Camera Controls (move)
		float camMoveSpeed = 5 * deltaTime;
		final float camMoveSpeedAccelerationFactor = 5;
		if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT)) {
			camMoveSpeed *= camMoveSpeedAccelerationFactor;
		}
		if (Gdx.input.isKeyPressed(Keys.LEFT)) {
			moveCamera(-camMoveSpeed, 0);
		}
		if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
			moveCamera(camMoveSpeed, 0);
		}
		if (Gdx.input.isKeyPressed(Keys.UP)) {
			moveCamera(0, camMoveSpeed);
		}
		if (Gdx.input.isKeyPressed(Keys.DOWN)) {
			moveCamera(0, -camMoveSpeed);
		}
		if (Gdx.input.isKeyPressed(Keys.BACKSPACE)) {
			cameraHelper.setPosition(0, 0);
		}

		// Camera Controls (zoom)
		float camZoomSpeed = 1 * deltaTime;
		final float camZoomSpeedAccelerationFactor = 5;
		if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT)) {
			camZoomSpeed *= camZoomSpeedAccelerationFactor;
		}
		if (Gdx.input.isKeyPressed(Keys.COMMA)) {
			cameraHelper.addZoom(camZoomSpeed);
		}
		if (Gdx.input.isKeyPressed(Keys.PERIOD)) {
			cameraHelper.addZoom(-camZoomSpeed);
		}
		if (Gdx.input.isKeyPressed(Keys.SLASH)) {
			cameraHelper.setZoom(1);
		}
	}

	private void moveSelectedSprite(final float x, final float y) {
		tmpSprite.set(testSprites[selectedSprite]);
		tmpSprite.translate(x, y);
		if (!testCollision(testSprites[selectedSprite], tmpSprite)) {
			testSprites[selectedSprite].set(tmpSprite);
		}
	}

	private boolean testCollision(Sprite origin, Sprite sprite) {
		boolean collision = false;
		collisionRectangle1.set(sprite.getX(), sprite.getY(),
				sprite.getWidth(), sprite.getHeight());
		for (Sprite spr : testSprites) {
			if (spr != null) {
				if (!origin.equals(spr)) {
					collisionRectangle2.set(spr.getX(), spr.getY(),
							spr.getWidth(), spr.getHeight());
					if (collisionRectangle1.overlaps(collisionRectangle2)) {
						collision = true;
						break;
					}
				}
			}
		}

		return collision;
	}

	private void moveCamera(float x, float y) {
		x += cameraHelper.getPosition().x;
		y += cameraHelper.getPosition().y;
		cameraHelper.setPosition(x, y);
	}

	@Override
	public boolean keyUp(final int keycode) {
		// Reset game world
		if (keycode == Keys.R) {
			init();
			Gdx.app.debug(TAG, "Game world resetted");
		}
		// Select next sprite
		else if (keycode == Keys.SPACE) {
			selectedSprite = (selectedSprite + 1) % testSprites.length;
			// Update camera's target to follow the currently
			// selected sprite
			if (cameraHelper.hasTarget()) {
				cameraHelper.setTarget(testSprites[selectedSprite]);
			}
			Gdx.app.debug(TAG, "Sprite #" + selectedSprite + " selected");
		}
		// Toggle camera follow
		else if (keycode == Keys.ENTER) {
			cameraHelper.setTarget(cameraHelper.hasTarget() ? null
					: testSprites[selectedSprite]);
			Gdx.app.debug(TAG,
					"Camera follow enabled: " + cameraHelper.hasTarget());
		}
		return false;
	}

	@Override
	public boolean touchDown(int screenX, int screenY, int pointer, int button) {
		Gdx.app.log("FIRE! ", "");
		fire(testSprites[selectedSprite], getAngleFromSpriteAndMouse(testSprites[selectedSprite]));
		return false;
	}
}
<file_sep>/CanyonBunny/src/com/packtpub/libgdx/canyonbunny/game/Bullet.java
package com.packtpub.libgdx.canyonbunny.game;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Bullet {

	private Sprite sprite;
	private float angle;

	public Bullet(Sprite sprite, float angle){
		this.setSprite(sprite);
		this.angle = angle;
	}

	public float getAngle() {
		return angle;
	}

	public void setAngle(float angle) {
		this.angle = angle;
	}

	public Sprite getSprite() {
		return sprite;
	}

	public void setSprite(Sprite sprite) {
		this.sprite = sprite;
	}

	public void draw(SpriteBatch batch) {
		getSprite().draw(batch);
	}
}


text:
<file_sep># 2)
# Dado el array:
a = [1,2,3,9,1,4,5,2,3,6,6]
# 1. Eliminar el último elemento.
a.pop
# 2. Eliminar el primer elemento.
a.shift
# 3. Eliminar el elemento que se encuentra en la posición media, si el arreglo tiene un número par de
# elementos entonces remover el que se encuentre en la mitad izquierda.
if (a.length).odd?
    a.delete(a[a.length/2])
else
    a.delete(a[(a.length/2)-1])
end
# Ejemplo, en el arreglo [1,2,3,4] se elimina el número 2.
# 4. Borrar el último elemento mientras ese número sea distinto a 1.
a.pop if a[-1] != 1
print a
# 5. Utilizando un arreglo vacío auxiliar y operaciones de push and pop invertir el orden de los
# elementos en un arreglo.
b = []
(a.length).times do
b.push(a.pop)
end
print b<file_sep># 6)
# Dado los arrays
a = [1,2,3,9,12,31, "domingo"]
b = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"]

# Obtener:
# 1. La concatenación de a y b. (hint: Los elementos que se repiten en a y b pueden aparecer dos
# veces en el resultado).
c = a + b

# 2. La unión de a y b. (hint: Los elementos que se repiten en a y b NO deben aparecer repetidos en
# el resultado).

# print a | b
c.uniq

# 3. La intersección de a y b. (hint: El resultado debe estar compuesto por los elementos que se
# repiten en a y b).
a & b
# 4. Intercalar los elementos:
# resultado = [[1, "lunes"], [2, "martes"], [3, "miércoles"], [9, "jueves"],
# [12, "viernes"], [31, "sábado"], ["domingo", "domingo"]]

c = a.zip(b)
print c<file_sep># 3)
# Dado el array:
a = [1,2,3,9,1,4,5,2,3,6,6]
# 1. Eliminar todos los números pares del arreglo.
a.each do |x|
    a.delete(x) if x.even?
end
print a
# 2. Obtener la suma de todos los elementos del arreglo utilizando .each
acumulador = 0
a.each do |i|
    acumulador += i
end

# 3. Obtener el promedio de los elementos del arreglo.
promedio = acumulador / (a.length).to_f

# 4. Incrementar todos los elementos en 1 retornando un nuevo arreglo.
a2 = []
a.each do |f|
    a2 << f + 1
    #a2.push(f + 1)
end
print a2<file_sep># 1)
# Dado el array:
arreglo = [1,2,3,9,1,4,5,2,3,6,6]

# 1. Imprimir el primer elemento.
puts arreglo[0]
# 2. Imprimir el último elemento.
puts arreglo[-1]
# 3. Imprimir, utilizando una iteración, todos los elementos.
arreglo.each do |x|
    print x
end
puts
# 4. Imprimir, utilizando una iteración, todos los elementos junto con su índice.
arreglo.each_with_index do |a,b|
    puts "#{a}, indice #{b}"
end
puts
# 5. Imprimir todos los elementos que se encuentren en una posición (índice) par.
arreglo.each_with_index do |f,c|
    puts "#{f}, indice #{c}" if c.even?
end

repo_language: Ruby