Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- f
- ************************************
- //------------------------------------------------------------------------------
- // <copyright file="FallingThings.cs" company="Microsoft">
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // </copyright>
- //------------------------------------------------------------------------------
- // This module contains code to do display falling shapes, and do
- // hit testing against a set of segments provided by the Kinect NUI, and
- // have shapes react accordingly.
- namespace ShapeGame
- {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Shapes;
- using Microsoft.Kinect;
- using ShapeGame.Utils;
- // FallingThings is the main class to draw and maintain positions of falling shapes. It also does hit testing
- // and appropriate bouncing.
- public class FallingThings
- {
- private const double BaseGravity = 0.017;
- private const double BaseAirFriction = 0.994;
- private readonly Dictionary<PolyType, PolyDef> polyDefs = new Dictionary<PolyType, PolyDef>
- {
- { PolyType.Triangle, new PolyDef { Sides = 3, Skip = 1 } },
- { PolyType.Star, new PolyDef { Sides = 5, Skip = 2 } },
- { PolyType.Pentagon, new PolyDef { Sides = 5, Skip = 1 } },
- { PolyType.Square, new PolyDef { Sides = 4, Skip = 1 } },
- { PolyType.Hex, new PolyDef { Sides = 6, Skip = 1 } },
- { PolyType.Star7, new PolyDef { Sides = 7, Skip = 3 } },
- { PolyType.Circle, new PolyDef { Sides = 1, Skip = 1 } },
- { PolyType.Bubble, new PolyDef { Sides = 0, Skip = 1 } }
- };
- private readonly List<Thing> things = new List<Thing>();
- private readonly Random rnd = new Random();
- private readonly int maxThings;
- private readonly int intraFrames = 1;
- private readonly Dictionary<int, int> scores = new Dictionary<int, int>();
- private const double DissolveTime = 0.4;
- private Rect sceneRect;
- private double targetFrameRate = 60;
- private double dropRate = 2.0;
- private double shapeSize = 1.0;
- private double baseShapeSize = 20;
- private GameMode gameMode = GameMode.Off;
- private double gravity = BaseGravity;
- private double gravityFactor = 1.0;
- private double airFriction = BaseAirFriction;
- private int frameCount;
- private bool doRandomColors = true;
- private double expandingRate = 1.0;
- private System.Windows.Media.Color baseColor = System.Windows.Media.Color.FromRgb(0, 0, 0);
- private PolyType polyTypes = PolyType.All;
- private DateTime gameStartTime;
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //@@לדעת מהי העצם שפגע ב"סינג"
- private string currentTypeOfHit;//@@
- public bool loadImg;
- private int score = 0;
- private string basketOrShape;
- private int numOfScore = 0;
- private JointType _currentTypeOfHit;
- private bool _shapeTurn = true;//תור תפיסת הצורה למעלה
- private Tuple<Point, Point, KeyValuePair<string, string>> _wantedGesture;
- private bool _canTouchBasket = false;
- private int currentIndexshapePositionList = 0;
- public bool GetLoadImg() { return loadImg; }
- List<Tuple<Point, Point, KeyValuePair<string, string>>> _shapeBasketList = new List<Tuple<Point, Point, KeyValuePair<string, string>>>()
- {
- new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeLeftUp*/new System.Windows.Point(200, 200), /*posBasketRightDown*/new System.Windows.Point(400, 400), /*"D1 right"*/new KeyValuePair<string, string>("HandRight","HandRight")),
- new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeRightUp*/new System.Windows.Point(400, 200), /*posBasketLeftDown*/new System.Windows.Point(200, 400), /*"D1 left"*/new KeyValuePair<string, string>("HandLeft","HandLeft")),
- new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeRightUp*/new System.Windows.Point(400, 200), /*posBasketLeftDown*/new System.Windows.Point(200, 400), /*"D2 right"*/new KeyValuePair<string, string>("HandRight","HandRight")),
- new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeLeftUp*/new System.Windows.Point(200, 200), /*posBasketRightDown*/new System.Windows.Point(400, 400), /*"D2 left"*/new KeyValuePair<string, string>("HandLeft","HandLeft")),
- //new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeRightUp*/new System.Windows.Point(400, 200), /*posBasketLeftDown*/new System.Windows.Point(200, 400), /*"D2 right"*/new KeyValuePair<string, string>("HandRight","HandLeft")),
- //new Tuple<Point, Point, KeyValuePair<string, string>>(/*posShapeLeftUp*/new System.Windows.Point(200, 200), /*posBasketRightDown*/new System.Windows.Point(400, 400), /*"D2 left"*/new KeyValuePair<string, string>("HandLeft","HandRight"))
- };
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- public FallingThings(int maxThings, double framerate, int intraFrames)
- {
- this.maxThings = maxThings;
- this.intraFrames = intraFrames;
- this.targetFrameRate = framerate * intraFrames;
- this.SetGravity(this.gravityFactor);
- this.sceneRect.X = this.sceneRect.Y = 0;
- this.sceneRect.Width = this.sceneRect.Height = 100;
- this.shapeSize = this.sceneRect.Height * this.baseShapeSize / 1000.0;
- this.expandingRate = Math.Exp(Math.Log(6.0) / (this.targetFrameRate * DissolveTime));
- }
- public enum ThingState
- {
- Falling = 0, //$$-נופל
- Bouncing = 1,//$$-מתפוצץ
- Dissolving = 2,//$$-מעומעם
- Remove = 3//$$-מוסר
- }
- public static Label MakeSimpleLabel(string text, Rect bounds, System.Windows.Media.Brush brush)
- {
- Label label = new Label { Content = text };
- if (bounds.Width != 0)
- {
- label.SetValue(Canvas.LeftProperty, bounds.Left);
- label.SetValue(Canvas.TopProperty, bounds.Top);
- label.Width = bounds.Width;
- label.Height = bounds.Height;
- }
- label.Foreground = brush;
- label.FontFamily = new System.Windows.Media.FontFamily("Arial");
- label.FontWeight = FontWeight.FromOpenTypeWeight(600);
- label.FontStyle = FontStyles.Normal;
- label.HorizontalAlignment = HorizontalAlignment.Center;
- label.VerticalAlignment = VerticalAlignment.Center;
- return label;
- }
- public void SetFramerate(double actualFramerate)
- {
- this.targetFrameRate = actualFramerate * this.intraFrames;
- this.expandingRate = Math.Exp(Math.Log(6.0) / (this.targetFrameRate * DissolveTime));
- if (this.gravityFactor != 0)
- {
- this.SetGravity(this.gravityFactor);
- }
- }
- public void SetBoundaries(Rect r)
- {
- this.sceneRect = r;
- this.shapeSize = r.Height * this.baseShapeSize / 1000.0;
- }
- public void SetDropRate(double f)
- {
- this.dropRate = f;
- }
- public void SetSize(double f)
- {
- this.baseShapeSize = f;
- this.shapeSize = this.sceneRect.Height * this.baseShapeSize / 1000.0;
- }
- public void SetShapesColor(System.Windows.Media.Color color, bool doRandom)
- {
- this.doRandomColors = doRandom;
- this.baseColor = color;
- }
- public void Reset()
- {
- for (int i = 0; i < this.things.Count; i++)
- {
- Thing thing = this.things[i];
- if ((thing.State == ThingState.Bouncing) || (thing.State == ThingState.Falling))//bbb
- {
- thing.State = ThingState.Dissolving;//bbb
- thing.Dissolve = 0;
- this.things[i] = thing;
- }
- }
- this.gameStartTime = DateTime.Now;
- this.scores.Clear();
- }
- public void SetGameMode(GameMode mode)
- {
- this.gameMode = mode;
- this.gameStartTime = DateTime.Now;
- this.scores.Clear();
- }
- public void SetGravity(double f)
- {
- this.gravityFactor = f;
- this.gravity = f * BaseGravity / this.targetFrameRate / Math.Sqrt(this.targetFrameRate) / Math.Sqrt(this.intraFrames);
- this.airFriction = f == 0 ? 0.997 : Math.Exp(Math.Log(1.0 - ((1.0 - BaseAirFriction) / f)) / this.intraFrames);
- if (f == 0)
- {
- // Stop all movement as well!
- for (int i = 0; i < this.things.Count; i++)
- {
- Thing thing = this.things[i];
- thing.XVelocity = thing.YVelocity = 0;
- this.things[i] = thing;
- }
- }
- }
- public void SetPolies(PolyType polies)
- {
- this.polyTypes = polies;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$////@@
- public string GetcurrentTypeOfHitThing()
- {
- return currentTypeOfHit;
- }//@@
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$////@@
- public HitType LookForHits(Dictionary<Bone, BoneData> segments, int playerId)
- {
- DateTime cur = DateTime.Now;
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//?
- //מאתחלים את ערך החזרת הפונקציה(סוג הפגיעה-פןפ,שום פגיעה,סקוויז וכו)בשום פגיעה
- HitType allHits = HitType.None; //bbb
- // Zero out score if necessary
- if (!this.scores.ContainsKey(playerId))
- {
- this.scores.Add(playerId, 0);
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//?
- //עוברים במקביל על כל מקטעי השלד ועל הצורות ובודקים אם היתה פגיעה
- foreach (var pair in segments)
- {
- for (int i = 0; i < this.things.Count; i++)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //מאתחל משתנה שישמור את סוג הפגיעה לשום פגיעה
- HitType hit = HitType.None; //bbb
- Thing thing = this.things[i];
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //בודק פגיעה בסינג בתנאי שהסינג היה במצב "פגיע" 0
- if (thing.CanHit)
- {
- switch (thing.State)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//?
- //מצבים בהם ישנה אפשרות לפגוע
- case ThingState.Bouncing://bbb
- case ThingState.Falling://bbb
- {
- var hitCenter = new System.Windows.Point(0, 0); //bbb
- double lineHitLocation = 0; //bbb
- Segment seg = pair.Value.GetEstimatedSegment(cur);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //אם הפונקציה "איט" החזריה "טרו" סימן שהיתה פגיעה
- if (thing.Hit(seg, ref hitCenter, ref lineHitLocation)) //bbb
- {
- double fMs = 1000;
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //כאשר זמן פגיעה בצורה שונה מהערך שאתחלו אותה
- if (thing.TimeLastHit != DateTime.MinValue)//bbb
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //fMs-מחשבים את מספר השניות שעברו מזמן שהצורה אותחלה והוצגה בעצם על המסך עד לזמן שנפגעה
- //ומחשבים את ממוצע משך זמן הפגיעה
- //cur-זהו הזמן האמיתי של הפגיעה
- fMs = cur.Subtract(thing.TimeLastHit).TotalMilliseconds; //bbb
- thing.AvgTimeBetweenHits = (thing.AvgTimeBetweenHits * 0.8) + (0.2 * fMs); //bbb
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //לשם בדיקה-מתי הזמן של הסינג נשאר אותו דבר
- else if (thing.TimeLastHit != DateTime.MinValue)
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- {
- ;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //נעדכן את "סינג" בזמן האמיתי של הפגיעה
- thing.TimeLastHit = cur; //bbb
- // Bounce off head and hands
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //פגיעה בעצמות ראש/ידיים/רגלים
- if (seg.IsCircle())
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //שמתי בהערה כדי שלא תזוז הצורה בתנועה לא נכונה
- // Bounce off of hand/head/foot
- //thing.BounceOff(
- // hitCenter.X,
- // hitCenter.Y,
- // seg.Radius,
- // pair.Value.XVelocity / this.targetFrameRate,
- // pair.Value.YVelocity / this.targetFrameRate);
- if (fMs > 100.0)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //במצב שהיתה פגיעה חלשה--נגיעה קלה עם היד
- hit |= HitType.Hand; //bbb
- }
- }
- else
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //שמתי בהערה כדי שלא תזוז הצורה בתנועה לא נכונה
- // Bounce off line segment
- //double velocityX = (pair.Value.XVelocity * (1.0 - lineHitLocation)) + (pair.Value.XVelocity2 * lineHitLocation);
- //double velocityY = (pair.Value.YVelocity * (1.0 - lineHitLocation)) + (pair.Value.YVelocity2 * lineHitLocation);
- //thing.BounceOff(
- // hitCenter.X,
- // hitCenter.Y,
- // seg.Radius,
- // velocityX / this.targetFrameRate,
- // velocityY / this.targetFrameRate);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //במצב של פגיעה בזרוע
- if (fMs > 100.0)
- {
- hit |= HitType.Arm; //bbb
- }
- }
- if (this.gameMode == GameMode.TwoPlayer)
- {
- if (thing.State == ThingState.Falling)//bbb
- {
- thing.State = ThingState.Bouncing;//bbb
- thing.TouchedBy = playerId;
- thing.Hotness = 1;
- thing.FlashCount = 0;
- }
- else if (thing.State == ThingState.Bouncing)//bbb
- {
- if (thing.TouchedBy != playerId)
- {
- if (seg.IsCircle())
- {
- thing.TouchedBy = playerId;
- thing.Hotness = Math.Min(thing.Hotness + 1, 4);
- }
- else
- {
- hit |= HitType.Popped; //bbb
- this.AddToScore(thing.TouchedBy, 5 << (thing.Hotness - 1), thing.Center, "");
- }
- }
- }
- }
- else if (this.gameMode == GameMode.Solo)
- {
- //$$$$$$$$$$$$$$$$$$$$$$
- //@@בשביל לצבוע את הסגמנט שפגע ב"סינג
- var w1 = pair.Key.Joint1;
- var w2 = pair.Key.Joint2;
- //@@
- JointType typeOfHit = pair.Key.Joint1;
- currentTypeOfHit = typeOfHit.ToString(); //1234
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //אם רוצים לחלק לפי סוג פגיעה
- //switch (typeOfHit)
- //{
- // case JointType.AnkleLeft:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 21;
- // break;
- // case JointType.AnkleRight:
- // //Console.WriteLine("The color is green");
- // // numOfScore = 2;
- // break;
- // case JointType.ElbowLeft:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 3;
- // break;
- // case JointType.ElbowRight:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 4;
- // break;
- // case JointType.FootLeft:
- // //Console.WriteLine("The color is green");
- // //numOfScore = 5;
- // break;
- // case JointType.FootRight:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 6;
- // break;
- // case JointType.HandLeft:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 7;
- // break;
- // case JointType.HandRight:
- // //Console.WriteLine("The color is green");
- // //numOfScore = 8;
- // break;
- // case JointType.Head:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 9;
- // break;
- // case JointType.HipCenter:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 10;
- // break;
- // case JointType.HipLeft:
- // //Console.WriteLine("The color is green");
- // //numOfScore = 11;
- // break;
- // case JointType.HipRight:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 12;
- // break;
- // case JointType.KneeLeft:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 13;
- // break;
- // case JointType.KneeRight:
- // //Console.WriteLine("The color is green");
- // //numOfScore = 14;
- // break;
- // case JointType.ShoulderCenter:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 15;
- // break;
- // case JointType.ShoulderLeft:
- // //Console.WriteLine("The color is red");
- // numOfScore = 16;
- // break;
- // case JointType.ShoulderRight:
- // //Console.WriteLine("The color is red");
- // numOfScore = 17;
- // break;
- // case JointType.Spine:
- // //Console.WriteLine("The color is green");
- // //numOfScore = 18;
- // break;
- // case JointType.WristLeft:
- // //Console.WriteLine("The color is blue");
- // //numOfScore = 19;
- // break;
- // case JointType.WristRight:
- // //Console.WriteLine("The color is red");
- // //numOfScore = 20;
- // break;
- // default:
- // //Console.WriteLine("The color is unknown.");
- // // numOfScore = 200;
- // break;
- //}
- //@@
- //$$$$$$$$$$$$$$$$$$$$$$$$
- if (seg.IsCircle())
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //היתה פגיעה והצורה היתה במצב נפילה(מצב בו היא מאותחלת ברגע שנכנסת למערך ה"סינגים" ןמןצגת על המסך) תעדכן אותה להיות במצב מתפוצץ
- if (thing.State == ThingState.Falling)//bbb
- {
- thing.State = ThingState.Bouncing;//bbb
- thing.TouchedBy = playerId;
- thing.Hotness = 1;
- thing.FlashCount = 0;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //כאשר ה"סינג" כבר במצב מעומעם-נגדיר את סוג הפגיעה להיות "פופ" ונרצה להציג ניקוד על הפגיעה(במקום הצורה שנפגעה) ולעדכן ניקוד כללי
- else if ((thing.State == ThingState.Bouncing) && (fMs > 100.0))//bbb
- {
- hit |= HitType.Popped; //bbb
- }
- }
- }
- this.things[i] = thing;
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //אם ממוצע משך זמן הפגיעה קטן מ8 זה אומר שהפגיעה היתה מסוג "פופ" או "סקייז
- if (thing.AvgTimeBetweenHits < 8) //bbb
- {
- hit |= HitType.Popped | HitType.Squeezed; //bbb
- }
- }
- }
- break;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //היתה פגיעה והיא והיא מסוג "פופ" תעדכןאת מצב ה"סינג" להיות מעומעם ותעדכן כמה דברים שצריך בכמה דברים שדרושים כדי להיכנס למצב הזה
- //הוספנו אפשרות ל"סקייז"
- if ((hit & HitType.Popped) != 0 || (hit & HitType.Squeezed) != 0)/* /*|| (hit & HitType.Arm)!=0 || (hit & HitType.Hand)!=0 )*/ //$$
- {
- if (thing.TypeOfShape == "shape")
- {
- if (currentTypeOfHit == _wantedGesture.Item3.Key)
- {
- loadImg = false; //$$
- thing.State = ThingState.Dissolving;
- thing.Dissolve = 0;
- thing.XVelocity = thing.YVelocity = 0;
- thing.SpinRate = (thing.SpinRate * 6) + 0.2;
- this.things[i] = thing;
- numOfScore = 5;
- }
- }
- else if (thing.TypeOfShape == "basket")
- {
- if (currentTypeOfHit == _wantedGesture.Item3.Value)
- {
- loadImg = true; //$$
- thing.State = ThingState.Dissolving;
- thing.Dissolve = 0;
- thing.XVelocity = thing.YVelocity = 0;
- thing.SpinRate = (thing.SpinRate * 6) + 0.2;
- this.things[i] = thing;
- numOfScore = 2;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //כאשר ה"סינג" כבר במצב מעומעם נרצה להציג ניקוד על הפגיעה(במקום הצורה שהתפוצצה) ולעדכן ניקוד כללי אך זאת בתנאי שמצב המשחק אינו כבוי כלומר יש 1/2 שחקנים במשחק
- if (this.gameMode != GameMode.Off)
- {
- this.AddToScore(
- thing.TouchedBy,
- numOfScore,
- thing.Center, "joint" + " " + currentTypeOfHit);
- }
- thing.TouchedBy = playerId;
- }
- allHits |= hit; //bbb
- }
- }
- }
- }
- return allHits; //bbb
- }
- public void AdvanceFrame()
- {
- // Move all things by one step, accounting for gravity
- for (int thingIndex = 0; thingIndex < this.things.Count; thingIndex++)
- {
- Thing thing = this.things[thingIndex];
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //כך מונעים תזוזה של צורה-הן רק הסתבובבו אך לא יזוזו ממש
- //thing.Center.Offset(thing.XVelocity, thing.YVelocity);//$$
- thing.YVelocity += this.gravity * this.sceneRect.Height;
- thing.YVelocity *= this.airFriction;
- thing.XVelocity *= this.airFriction;
- thing.Theta += thing.SpinRate;
- // bounce off walls
- if ((thing.Center.X - thing.Size < 0) || (thing.Center.X + thing.Size > this.sceneRect.Width))
- {
- thing.XVelocity = -thing.XVelocity;
- thing.Center.X += thing.XVelocity;
- }
- // Then get rid of one if any that fall off the bottom
- if (thing.Center.Y - thing.Size > this.sceneRect.Bottom)
- {
- thing.State = ThingState.Remove;//bbb
- }
- // Get rid of after dissolving.
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- // במצב שה"סינג" במצב מעומעם תעמעם את ה"סינג" שלו כאשר המשתנה "דיסולב" שהפך בין מצב התפוצצות למצב עמעום ל0
- //עולה לאט לאט וכשהוא גדול שווה ל1 מצב ה"סינג" הופך להיות במצב מוסר
- if (thing.State == ThingState.Dissolving)//bbb
- {
- thing.Dissolve += 1 / (this.targetFrameRate * DissolveTime);
- //$$$$$$$$$$$$$$$כך גודל הצורה לא משתנה כאשר נוגעים ביד הלא נכונה
- //thing.Size *= this.expandingRate;
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
- if (thing.Dissolve >= 1.0)
- {
- thing.State = ThingState.Remove;//bbb
- }
- }
- this.things[thingIndex] = thing;
- }
- // Then remove any that should go away now
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //לאחר שעבר על מערך ה"סינגים" בודק אם יש "סינגים" שצריך להסיר
- for (int i = 0; i < this.things.Count; i++)
- {
- Thing thing = this.things[i];
- if (thing.State == ThingState.Remove)//bbb
- {
- this.things.Remove(thing);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
- //לאחר שפגע בצורה למעלה מאפשר פגיעה בסל
- //בהתחלה ברשימה הופיה קודם הצורה למעלה ומיד אחריה הצורה שבסל
- // כיוון שהסרנו את הצורה למעלה הצורה של הסל תפסה את מקומה
- int index = i;
- for (int k = 0; k < things.Count; k++)
- {
- if (k == index)
- {
- Thing thingToUpdate = this.things[k];
- thingToUpdate.CanHit = true;
- this.things[k] = thingToUpdate;
- }
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
- i--;
- }
- }
- // Create any new things to drop based on dropRate
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //if we want a few shape together we need to change code to:
- //if ((this.things.Count < this.maxThings) && (this.rnd.NextDouble() < this.dropRate / this.targetFrameRate) && (this.polyTypes != PolyType.None))
- if ((this.things.Count < 1) && (this.rnd.NextDouble() < this.dropRate / this.targetFrameRate) && (this.polyTypes != PolyType.None)) //$$
- {
- PolyType[] alltypes =
- {
- PolyType.Triangle, PolyType.Square, PolyType.Star, PolyType.Pentagon,
- PolyType.Hex, PolyType.Star7, PolyType.Circle, PolyType.Bubble
- };
- byte r;
- byte g;
- byte b;
- if (this.doRandomColors)
- {
- r = (byte)(this.rnd.Next(215) + 40);
- g = (byte)(this.rnd.Next(215) + 40);
- b = (byte)(this.rnd.Next(215) + 40);
- }
- else
- {
- r = (byte)Math.Min(255.0, this.baseColor.R * (0.7 + (this.rnd.NextDouble() * 0.7)));
- g = (byte)Math.Min(255.0, this.baseColor.G * (0.7 + (this.rnd.NextDouble() * 0.7)));
- b = (byte)Math.Min(255.0, this.baseColor.B * (0.7 + (this.rnd.NextDouble() * 0.7)));
- }
- PolyType tryType;
- do
- {
- tryType = alltypes[this.rnd.Next(alltypes.Length)];
- }
- while ((this.polyTypes & tryType) == 0);
- this.DropNewThing(tryType, this.shapeSize, System.Windows.Media.Color.FromRgb(r, g, b), currentIndexshapePositionList);
- currentIndexshapePositionList += 1;
- }
- }
- public void DrawFrame(UIElementCollection children)
- {
- this.frameCount++;
- // Draw all shapes in the scene
- for (int i = 0; i < this.things.Count; i++)
- {
- Thing thing = this.things[i];
- if (thing.Brush == null)
- {
- thing.Brush = new SolidColorBrush(thing.Color);
- double factor = 0.4 + (((double)thing.Color.R + thing.Color.G + thing.Color.B) / 1600);
- thing.Brush2 =
- new SolidColorBrush(
- System.Windows.Media.Color.FromRgb(
- (byte)(255 - ((255 - thing.Color.R) * factor)),
- (byte)(255 - ((255 - thing.Color.G) * factor)),
- (byte)(255 - ((255 - thing.Color.B) * factor))));
- thing.BrushPulse = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //כאשר היתה פגיעה והצורה היתה במצב מתפוצץ
- if (thing.State == ThingState.Bouncing)//bbb
- {
- // Pulsate edges
- double alpha = Math.Cos((0.15 * (thing.FlashCount++) * thing.Hotness) * 0.5) + 0.5;
- int type = i;
- children.Add(
- this.MakeSimpleShape(
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //החלפנו לצורך צורות מוגדרות מראש
- //this.polyDefs[thing.Shape].Sides,
- //this.polyDefs[thing.Shape].Skip,
- //thing.Size,
- //thing.Theta,
- //thing.Center,
- //thing.Brush,
- //thing.BrushPulse,
- //thing.Size * 0.1,
- //alpha));
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- thing.TypeOfShape,
- i,
- this.polyDefs[thing.Shape].Sides,
- this.polyDefs[thing.Shape].Skip,
- thing.Size,
- thing.Theta,
- thing.Center,
- thing.Brush,
- thing.BrushPulse,
- (thing.TypeOfShape == "basket") ? 0 : 3,
- alpha));
- this.things[i] = thing;
- }
- else
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //במצב מעומעם נרצה לשנות את אטימות הצבע של ה"סינג
- if (thing.State == ThingState.Dissolving)//bbb
- {
- thing.Brush.Opacity = 1.0 - (thing.Dissolve * thing.Dissolve);
- }
- int type = i;//$$
- children.Add(
- this.MakeSimpleShape(
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //החלפנו לצורך צורות מוגדרות מראש
- //this.polyDefs[thing.Shape].Sides,
- //this.polyDefs[thing.Shape].Skip,
- //thing.Size,
- //thing.Theta,
- //thing.Center,
- //thing.Brush,
- //(thing.State == ThingState.Dissolving) ? null : thing.Brush2,
- //1,
- //1));
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- thing.TypeOfShape,
- i,
- this.polyDefs[thing.Shape].Sides,
- this.polyDefs[thing.Shape].Skip,
- thing.Size,
- thing.Theta,
- thing.Center,
- thing.Brush,
- (thing.State == ThingState.Dissolving) ? null : thing.Brush2,
- (thing.TypeOfShape == "basket") ? 0 : 3,
- 1));
- }
- }
- // Show scores
- if (this.scores.Count != 0)
- {
- int i = 0;
- foreach (var score in this.scores)
- {
- Label label = MakeSimpleLabel(
- score.Value.ToString(CultureInfo.InvariantCulture),
- new Rect(
- (0.02 + (i * 0.6)) * this.sceneRect.Width,
- 0.01 * this.sceneRect.Height,
- 0.4 * this.sceneRect.Width,
- 0.3 * this.sceneRect.Height),
- new SolidColorBrush(System.Windows.Media.Color.FromArgb(200, 255, 255, 255)));
- label.FontSize = Math.Max(1, Math.Min(this.sceneRect.Width / 12, this.sceneRect.Height / 12));
- children.Add(label);
- i++;
- }
- }
- // Show game timer
- if (this.gameMode != GameMode.Off)
- {
- TimeSpan span = DateTime.Now.Subtract(this.gameStartTime);
- string text = span.Minutes.ToString(CultureInfo.InvariantCulture) + ":" + span.Seconds.ToString("00");
- Label timeText = MakeSimpleLabel(
- text,
- new Rect(
- 0.1 * this.sceneRect.Width, 0.25 * this.sceneRect.Height, 0.89 * this.sceneRect.Width, 0.72 * this.sceneRect.Height),
- new SolidColorBrush(System.Windows.Media.Color.FromArgb(160, 255, 255, 255)));
- timeText.FontSize = Math.Max(1, this.sceneRect.Height / 16);
- timeText.HorizontalContentAlignment = HorizontalAlignment.Right;
- timeText.VerticalContentAlignment = VerticalAlignment.Bottom;
- children.Add(timeText);
- }
- }
- private static double SquaredDistance(double x1, double y1, double x2, double y2)
- {
- return ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1));
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //הוספנו קבלת סוג הפגיעה
- private void AddToScore(int player, int points, System.Windows.Point center, string typeOfHit)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //ניקוד על פגיעה ספציפית
- if (this.scores.ContainsKey(player))
- {
- this.scores[player] = this.scores[player] + points;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //ניקוד כללי
- else
- {
- this.scores.Add(player, points);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //לשם בדיקה-מתי מציג פעמיים ניקוד באותו מסך
- if(scores.Count>1)
- {
- ;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- }
- // FlyingText.NewFlyingText(this.sceneRect.Width / 300, center, "+" + points);
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //הוספנו קבלת nextPos
- private void DropNewThing(PolyType newShape, double newSize, System.Windows.Media.Color newColor, int nextPos)
- {
- // Only drop within the center "square" area
- double dropWidth = this.sceneRect.Bottom - this.sceneRect.Top;
- if (dropWidth > this.sceneRect.Right - this.sceneRect.Left)
- {
- dropWidth = this.sceneRect.Right - this.sceneRect.Left;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //רצינו צורות עם מאפינים קבועים ולכן החלפנו
- //var newThing = new Thing
- //{
- // Size = newSize,
- // YVelocity = ((0.5 * this.rnd.NextDouble()) - 0.25) / this.targetFrameRate,
- // XVelocity = 0,
- // Shape = newShape,
- // Center = new System.Windows.Point((this.rnd.NextDouble() * dropWidth) + ((this.sceneRect.Left + this.sceneRect.Right - dropWidth) / 2), this.sceneRect.Top - newSize),
- // SpinRate = ((this.rnd.NextDouble() * 12.0) - 6.0) * 2.0 * Math.PI / this.targetFrameRate / 4.0,
- // Theta = 0,
- // TimeLastHit = DateTime.MinValue,
- // AvgTimeBetweenHits = 100,
- // Color = newColor,
- // Brush = null,
- // Brush2 = null,
- // BrushPulse = null,
- // Dissolve = 0,
- // State = ThingState.Falling,
- // TouchedBy = 0,
- // Hotness = 0,
- // FlashCount = 0
- //};
- //this.things.Add(newThing);
- for (int i = 0; i < _shapeBasketList.Count; i++)
- {
- if (i == nextPos)
- {
- _wantedGesture = _shapeBasketList[i];
- var newThing = new Thing
- {
- Size = newSize,
- YVelocity = ((0.5 * this.rnd.NextDouble()) - 0.25) / this.targetFrameRate,
- XVelocity = 0,
- Shape = newShape,
- Center = _shapeBasketList[i].Item1,
- SpinRate = ((this.rnd.NextDouble() * 12.0) - 6.0) * 2.0 * Math.PI / this.targetFrameRate / 4.0,
- Theta = 0,
- TimeLastHit = DateTime.MinValue,
- AvgTimeBetweenHits = 100,
- Color = newColor,
- Brush = null,
- Brush2 = null,
- BrushPulse = null,
- Dissolve = 0,
- State = ThingState.Falling,
- CanHit = true,
- TypeOfShape = "shape",
- TouchedBy = 0,
- Hotness = 0,
- FlashCount = 0,
- };
- var basket = new Thing
- {
- Size = 60,
- YVelocity = ((0.5 * this.rnd.NextDouble()) - 0.25) / this.targetFrameRate,
- XVelocity = 0,
- Shape = PolyType.Square,
- Center = _shapeBasketList[i].Item2,
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //מנענו את תזוזת הסל
- //SpinRate = ((this.rnd.NextDouble() * 12.0) - 6.0) * 2.0 * Math.PI / this.targetFrameRate / 4.0,
- SpinRate = 0,//$$
- Theta = 0,
- TimeLastHit = DateTime.MinValue,
- AvgTimeBetweenHits = 100,
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //הגדרנו את צורת הסל לצבע שקוף(כי הרי עליה יש תמונה ולא נרצה שיראו את קצוות הצורה
- //Color = newColor,
- Color = Color.FromRgb(0, 0, 0),
- Brush = null,
- Brush2 = null,
- BrushPulse = Brushes.Transparent,
- Dissolve = 0,
- State = ThingState.Falling,
- CanHit = false,
- TypeOfShape = "basket",
- TouchedBy = 0,
- Hotness = 0,
- FlashCount = 0
- };
- this.things.Add(newThing);
- this.things.Add(basket);
- }
- }
- }
- private Shape MakeSimpleShape(
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //הוספנו מאפיינים לצורה
- string typeOfShape,//$$
- int type,//$$
- int numSides,
- int skip,
- double size,
- double spin,
- System.Windows.Point center,
- System.Windows.Media.Brush brush,
- System.Windows.Media.Brush brushStroke,
- double strokeThickness,
- double opacity)
- {
- if (numSides <= 1)
- {
- var circle = new Ellipse { Width = size * 2, Height = size * 2, Stroke = brushStroke };
- if (circle.Stroke != null)
- {
- circle.Stroke.Opacity = opacity;
- }
- circle.StrokeThickness = strokeThickness * ((numSides == 1) ? 1 : 2);
- circle.Fill = (numSides == 1) ? brush : null;
- circle.SetValue(Canvas.LeftProperty, center.X - size);
- circle.SetValue(Canvas.TopProperty, center.Y - size);
- return circle;
- }
- var points = new PointCollection(numSides + 2);
- double theta = spin;
- for (int i = 0; i <= numSides + 1; ++i)
- {
- points.Add(new System.Windows.Point((Math.Cos(theta) * size) + center.X, (Math.Sin(theta) * size) + center.Y));
- theta = theta + (2.0 * Math.PI * skip / numSides);
- }
- var polyline = new Polyline { Points = points, Stroke = brushStroke };
- if (polyline.Stroke != null)
- {
- polyline.Stroke.Opacity = opacity;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //המילוי של הצורה יהיה מסוג צבע(לצורה)/מסוג תמונה(לסל)0
- if (typeOfShape == "basket")
- {
- //$$$$$$$$$$$$$$$4 relative sorce-התמונה נטענת מתוך הנתיב שנמצא בתוך הפרויקט .../shapegame/bin/debug/image
- polyline.Fill = new ImageBrush(new BitmapImage(new Uri("image/basket1.jpg", UriKind.Relative)));
- //$$$$$$$$$$$$$$$4 not relative sorce
- //polyline.Fill = new ImageBrush(new BitmapImage(new Uri(@"C:\Users\User\Desktop\Downloads\basket1.jpg")));
- basketOrShape = "basket";
- }
- else
- {
- polyline.Fill = brush;
- basketOrShape = "shape";
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- polyline.FillRule = FillRule.Nonzero;
- polyline.StrokeThickness = strokeThickness;
- return polyline;
- }
- internal struct PolyDef
- {
- public int Sides;
- public int Skip;
- }
- // The Thing struct represents a single object that is flying through the air, and
- // all of its properties.
- private struct Thing
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //הוספנו מאפיינים לצורה
- public System.Windows.Media.ImageBrush image;//$$
- public bool CanHit;//$$
- public string TypeOfShape;//regular shape or basket //$$
- public System.Windows.Point Center;
- public double Size;
- public double Theta;
- public double SpinRate;
- public double YVelocity;
- public double XVelocity;
- public PolyType Shape;
- public System.Windows.Media.Color Color;
- public System.Windows.Media.Brush Brush;
- public System.Windows.Media.Brush Brush2;
- public System.Windows.Media.Brush BrushPulse;
- public double Dissolve;
- public ThingState State;
- public DateTime TimeLastHit;
- public double AvgTimeBetweenHits;
- public int TouchedBy; // Last player to touch this thing-השחקן שנגע בצורה
- public int Hotness; // Score level
- public int FlashCount;
- // Hit testing between this thing and a single segment. If hit, the center point on
- // the segment being hit is returned, along with the spot on the line from 0 to 1 if
- // a line segment was hit.
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //מחזירה טרו אם היתה פגיעה בין "סינג" ואחת מהסגמטים=מקטעי השלד
- public bool Hit(Segment seg, ref System.Windows.Point hitCenter, ref double lineHitLocation)
- {
- double minDxSquared = this.Size + seg.Radius;
- minDxSquared *= minDxSquared;
- // See if falling thing hit this body segment
- if (seg.IsCircle())
- {
- if (SquaredDistance(this.Center.X, this.Center.Y, seg.X1, seg.Y1) <= minDxSquared)
- {
- hitCenter.X = seg.X1; //bbb
- hitCenter.Y = seg.Y1;//bbb
- lineHitLocation = 0;//bbb
- return true;
- }
- }
- else
- {
- double sqrLineSize = SquaredDistance(seg.X1, seg.Y1, seg.X2, seg.Y2);
- if (sqrLineSize < 0.5)
- {
- // if less than 1/2 pixel apart, just check dx to an endpoint
- return SquaredDistance(this.Center.X, this.Center.Y, seg.X1, seg.Y1) < minDxSquared;
- }
- // Find dx from center to line
- double u = ((this.Center.X - seg.X1) * (seg.X2 - seg.X1)) + (((this.Center.Y - seg.Y1) * (seg.Y2 - seg.Y1)) / sqrLineSize);
- if ((u >= 0) && (u <= 1.0))
- { // Tangent within line endpoints, see if we're close enough
- double intersectX = seg.X1 + ((seg.X2 - seg.X1) * u);
- double intersectY = seg.Y1 + ((seg.Y2 - seg.Y1) * u);
- if (SquaredDistance(this.Center.X, this.Center.Y, intersectX, intersectY) < minDxSquared)
- {
- lineHitLocation = u;//bbb
- hitCenter.X = intersectX;//bbb
- hitCenter.Y = intersectY;//bbb
- return true;
- }
- }
- else
- {
- // See how close we are to an endpoint
- if (u < 0)
- {
- if (SquaredDistance(this.Center.X, this.Center.Y, seg.X1, seg.Y1) < minDxSquared)
- {
- lineHitLocation = 0;//bbb
- hitCenter.X = seg.X1;//bbb
- hitCenter.Y = seg.Y1;//bbb
- return true;
- }
- }
- else
- {
- if (SquaredDistance(this.Center.X, this.Center.Y, seg.X2, seg.Y2) < minDxSquared)
- {
- lineHitLocation = 1;//bbb
- hitCenter.X = seg.X2;//bbb
- hitCenter.Y = seg.Y2;//bbb
- return true;
- }
- }
- }
- return false;
- }
- return false;
- }
- // Change our velocity based on the object's velocity, our velocity, and where we hit.
- public void BounceOff(double x1, double y1, double otherSize, double fXv, double fYv)
- {
- double x0 = this.Center.X;
- double y0 = this.Center.Y;
- double xv0 = this.XVelocity - fXv;
- double yv0 = this.YVelocity - fYv;
- double dist = otherSize + this.Size;
- double dx = Math.Sqrt(((x1 - x0) * (x1 - x0)) + ((y1 - y0) * (y1 - y0)));
- double xdif = x1 - x0;
- double ydif = y1 - y0;
- double newvx1 = 0;
- double newvy1 = 0;
- x0 = x1 - (xdif / dx * dist);
- y0 = y1 - (ydif / dx * dist);
- xdif = x1 - x0;
- ydif = y1 - y0;
- double bsq = dist * dist;
- double b = dist;
- double asq = (xv0 * xv0) + (yv0 * yv0);
- double a = Math.Sqrt(asq);
- if (a > 0.000001)
- {
- // if moving much at all...
- double cx = x0 + xv0;
- double cy = y0 + yv0;
- double csq = ((x1 - cx) * (x1 - cx)) + ((y1 - cy) * (y1 - cy));
- double tt = asq + bsq - csq;
- double bb = 2 * a * b;
- double power = a * (tt / bb);
- newvx1 -= 2 * (xdif / dist * power);
- newvy1 -= 2 * (ydif / dist * power);
- }
- this.XVelocity += newvx1;
- this.YVelocity += newvy1;
- this.Center.X = x0;
- this.Center.Y = y0;
- }
- }
- }
- }
- m
- *************************************
- //------------------------------------------------------------------------------
- // <copyright file="MainWindow.xaml.cs" company="Microsoft">
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // </copyright>
- //------------------------------------------------------------------------------
- // This module contains code to do Kinect NUI initialization,
- // processing, displaying players on screen, and sending updated player
- // positions to the game portion for hit testing.
- //*******************הערה חשובה************************
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$// הוספת הערה שלי
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//הוספת הערה שלי לא בטוחה בנכונותה
- //$$ שורות קוד שאני הוספתי
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //... כל הקטע התחום אני הוספתי
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //*******************************************************
- namespace ShapeGame
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Media;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Threading;
- using Microsoft.Kinect;
- using Microsoft.Kinect.Toolkit;
- using Microsoft.Samples.Kinect.WpfViewers;
- using ShapeGame.Speech;
- using ShapeGame.Utils;
- //@@
- using System.Windows.Media;
- //@@
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- ///
- public partial class MainWindow : Window
- {
- public static readonly DependencyProperty KinectSensorManagerProperty =
- DependencyProperty.Register(
- "KinectSensorManager",
- typeof(KinectSensorManager),
- typeof(MainWindow),
- new PropertyMetadata(null));
- #region Private State
- private const int TimerResolution = 2; // ms
- private const int NumIntraFrames = 3;
- private const int MaxShapes = 80;
- private const double MaxFramerate = 70;
- private const double MinFramerate = 15;
- private const double MinShapeSize = 12;
- private const double MaxShapeSize = 90;
- private const double DefaultDropRate = 2.5;
- private const double DefaultDropSize = 32.0;
- private const double DefaultDropGravity = 1.0;
- private readonly Dictionary<int, Player> players = new Dictionary<int, Player>();
- private readonly SoundPlayer popSound = new SoundPlayer();
- private readonly SoundPlayer hitSound = new SoundPlayer();
- private readonly SoundPlayer squeezeSound = new SoundPlayer();
- private readonly KinectSensorChooser sensorChooser = new KinectSensorChooser();
- private double dropRate = DefaultDropRate;
- private double dropSize = DefaultDropSize;
- private double dropGravity = DefaultDropGravity;
- private DateTime lastFrameDrawn = DateTime.MinValue;
- private DateTime predNextFrame = DateTime.MinValue;
- private double actualFrameTime;
- private Skeleton[] skeletonData;
- // Player(s) placement in scene (z collapsed):
- private Rect playerBounds;
- private Rect screenRect;
- private double targetFramerate = MaxFramerate;
- private int frameCount;
- private bool runningGameThread;
- private FallingThings myFallingThings;
- private int playersAlive;
- //$$$$$$$$$$$$$$$$
- private int numOfPlayers = 0;
- private System.Windows.Point positionOnScreen;
- private int currentIndexOfImg = 0;
- private int counter = 0;
- public List<string> Image = new List<string>() { "D1L", "D2R", "D2L", "D1R" };
- private double size;
- //$$$$$$$$$$$$$$$
- private SpeechRecognizer mySpeechRecognizer;
- #endregion Private State
- #region ctor + Window Events
- public MainWindow()
- {
- this.KinectSensorManager = new KinectSensorManager();
- this.KinectSensorManager.KinectSensorChanged += this.KinectSensorChanged;
- this.DataContext = this.KinectSensorManager;
- InitializeComponent();
- // this.SensorChooserUI.KinectSensorChooser = sensorChooser;
- sensorChooser.Start();
- // Bind the KinectSensor from the sensorChooser to the KinectSensor on the KinectSensorManager
- var kinectSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
- BindingOperations.SetBinding(this.KinectSensorManager, KinectSensorManager.KinectSensorProperty, kinectSensorBinding);
- this.RestoreWindowState();
- }
- public KinectSensorManager KinectSensorManager
- {
- get { return (KinectSensorManager)GetValue(KinectSensorManagerProperty); }
- set { SetValue(KinectSensorManagerProperty, value); }
- }
- // Since the timer resolution defaults to about 10ms precisely, we need to
- // increase the resolution to get framerates above between 50fps with any
- // consistency.
- [DllImport("Winmm.dll", EntryPoint = "timeBeginPeriod")]
- private static extern int TimeBeginPeriod(uint period);
- private void RestoreWindowState()
- {
- // Restore window state to that last used
- Rect bounds = Properties.Settings.Default.PrevWinPosition;
- if (bounds.Right != bounds.Left)
- {
- this.Top = bounds.Top;
- this.Left = bounds.Left;
- this.Height = bounds.Height;
- this.Width = bounds.Width;
- }
- this.WindowState = (WindowState)Properties.Settings.Default.WindowState;
- }
- private void WindowLoaded(object sender, EventArgs e)
- {
- playfield.ClipToBounds = true;
- this.myFallingThings = new FallingThings(MaxShapes, this.targetFramerate, NumIntraFrames);
- this.UpdatePlayfieldSize();
- this.myFallingThings.SetGravity(this.dropGravity);
- this.myFallingThings.SetDropRate(this.dropRate);
- this.myFallingThings.SetSize(this.dropSize);
- this.myFallingThings.SetPolies(PolyType.All);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //בזמן טעינת חלון המשחק מצב המשחק-לכבוי
- this.myFallingThings.SetGameMode(GameMode.Off);
- this.popSound.Stream = Properties.Resources.Pop_5;
- this.hitSound.Stream = Properties.Resources.Hit_2;
- this.squeezeSound.Stream = Properties.Resources.Squeeze;
- this.popSound.Play();
- TimeBeginPeriod(TimerResolution);
- var myGameThread = new Thread(this.GameThread);
- myGameThread.SetApartmentState(ApartmentState.STA);
- myGameThread.Start();
- double size = this.screenRect.Width / 30;
- System.Windows.Point positionOnScreen = new Point(this.screenRect.Width / 2, this.screenRect.Height / 2);
- string str = "סימונוע";
- FlyingText.NewFlyingText(size, positionOnScreen, str);
- //$$$$$$$$$$$מיקום טקסט סימונוע size(20.6333333333333) and position(point( 309.5 ,344)) of the text in start of game $$$$$$$$$$$$$$$$
- //enableAec.Content = size.ToString() +" "+ positionOnScreen.X.ToString()+" "+ positionOnScreen.Y.ToString();
- }
- private void WindowClosing(object sender, CancelEventArgs e)
- {
- sensorChooser.Stop();
- this.runningGameThread = false;
- Properties.Settings.Default.PrevWinPosition = this.RestoreBounds;
- Properties.Settings.Default.WindowState = (int)this.WindowState;
- Properties.Settings.Default.Save();
- }
- private void WindowClosed(object sender, EventArgs e)
- {
- this.KinectSensorManager.KinectSensor = null;
- }
- #endregion ctor + Window Events
- #region Kinect discovery + setup
- private void KinectSensorChanged(object sender, KinectSensorManagerEventArgs<KinectSensor> args)
- {
- if (null != args.OldValue)
- {
- this.UninitializeKinectServices(args.OldValue);
- }
- // Only enable this checkbox if we have a sensor
- enableAec.IsEnabled = null != args.NewValue;
- if (null != args.NewValue)
- {
- this.InitializeKinectServices(this.KinectSensorManager, args.NewValue);
- }
- }
- // Kinect enabled apps should customize which Kinect services it initializes here.
- private void InitializeKinectServices(KinectSensorManager kinectSensorManager, KinectSensor sensor)
- {
- // Application should enable all streams first.
- kinectSensorManager.ColorFormat = ColorImageFormat.RgbResolution640x480Fps30;
- kinectSensorManager.ColorStreamEnabled = true;
- sensor.SkeletonFrameReady += this.SkeletonsReady;
- kinectSensorManager.TransformSmoothParameters = new TransformSmoothParameters
- {
- Smoothing = 0.5f,
- Correction = 0.5f,
- Prediction = 0.5f,
- JitterRadius = 0.05f,
- MaxDeviationRadius = 0.04f
- };
- kinectSensorManager.SkeletonStreamEnabled = true;
- kinectSensorManager.KinectSensorEnabled = true;
- if (!kinectSensorManager.KinectSensorAppConflict)
- {
- // Start speech recognizer after KinectSensor started successfully.
- this.mySpeechRecognizer = SpeechRecognizer.Create();
- if (null != this.mySpeechRecognizer)
- {
- this.mySpeechRecognizer.SaidSomething += this.RecognizerSaidSomething;
- this.mySpeechRecognizer.Start(sensor.AudioSource);
- }
- enableAec.Visibility = Visibility.Visible;
- this.UpdateEchoCancellation(this.enableAec);
- }
- }
- // Kinect enabled apps should uninitialize all Kinect services that were initialized in InitializeKinectServices() here.
- private void UninitializeKinectServices(KinectSensor sensor)
- {
- sensor.SkeletonFrameReady -= this.SkeletonsReady;
- if (null != this.mySpeechRecognizer)
- {
- this.mySpeechRecognizer.Stop();
- this.mySpeechRecognizer.SaidSomething -= this.RecognizerSaidSomething;
- this.mySpeechRecognizer.Dispose();
- this.mySpeechRecognizer = null;
- }
- enableAec.Visibility = Visibility.Collapsed;
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //
- private void SetImg()
- {
- if (myFallingThings.GetLoadImg())
- {
- myFallingThings.loadImg = false;
- bool t = myFallingThings.GetLoadImg();
- ////if (currentIndexOfImg ==2 || currentIndexOfImg==4 ||currentIndexOfImg==6 ||currentIndexOfImg==8)
- //if (counter % 2 == 1)
- //{
- //Image specificImg = (Image)counter;
- var c = currentIndexOfImg;
- string specificImg = Image[currentIndexOfImg];
- movement.Source = new BitmapImage(new Uri(@"C:\Users\nava\Videos\פרויקטים מעודכנים\2\1\ShapeGame\image\" + specificImg.ToString() + ".PNG"));
- currentIndexOfImg++;
- if (currentIndexOfImg == 4)
- {
- currentIndexOfImg = 0;
- System.Windows.Point p = new System.Windows.Point(309.5, 344);
- //FlyingText.NewFlyingText(20.6333333333333, p, "winner");
- }
- // var x = counter;
- // var y = specificImg;
- // var z = currentIndexOfImg;
- //$$$$$$$$$$$$$$$4 relative sorce-התמונה נטענת מתוך הנתיב שנמצא בתוך הפרויקט .../shapegame/bin/debug/image
- //movement.Source = new BitmapImage(new Uri("image/" + specificImg.ToString() + ".PNG",UriKind.Relative));
- //var a = "image/" + specificImg.ToString() + ".PNG".ToString();
- // a = a.ToString();
- //movement.Source = new BitmapImage(new Uri("image/D1L.PNG", UriKind.Relative));
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4
- //$$$$$$$$$$$$$$$4 not relative sorce
- //movement.Source = new BitmapImage(new Uri(@"C:\Users\User\source\repos\פרויקטים מעודכנים\פרויקטים מעודכנים\1\finalProject_(10)\finalProject (10)\2\ShapeGame\image\D1L.PNG"));
- //movement.Source = new BitmapImage(new Uri(@"C:\Users\User\source\repos\פרויקטים מעודכנים\פרויקטים מעודכנים\1\finalProject_(10)\finalProject (10)\2\ShapeGame\image\" + specificImg.ToString() + ".PNG"));
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4
- //if (currentIndexOfImg == 3)
- // currentIndexOfImg = 0;
- //var a = counter;
- //counter++;
- else
- {
- ;
- }
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- #endregion Kinect discovery + setup
- #region Kinect Skeleton processing
- private void SkeletonsReady(object sender, SkeletonFrameReadyEventArgs e)
- {
- using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
- {
- if (skeletonFrame != null)
- {
- int skeletonSlot = 0;
- if ((this.skeletonData == null) || (this.skeletonData.Length != skeletonFrame.SkeletonArrayLength))
- {
- this.skeletonData = new Skeleton[skeletonFrame.SkeletonArrayLength];
- }
- skeletonFrame.CopySkeletonDataTo(this.skeletonData);
- foreach (Skeleton skeleton in this.skeletonData)
- {
- if (SkeletonTrackingState.Tracked == skeleton.TrackingState)
- {
- Player player;
- if (this.players.ContainsKey(skeletonSlot))
- {
- player = this.players[skeletonSlot];
- }
- else
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //קן חדש כלומר בתחילת המשחק/כאשר נקודת הכיול נעלמה
- //כאשר נקודת הכיול נעלמת הוא מסיר את השחקן מהמערך-גודל המערך כמו בתחילת המשחק שווה ל0
- //במקרה שיש יותר משחקן אחד מול המצלמה הוא בעצם רוצה להוסיף למערך פעמיים
- //התנאי הזה יגרום לו להוסיף תמיד פעם אחת בלבד
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- player = new Player(skeletonSlot);
- player.SetJointsAndBonesBrushesOfPlayers(players.Count);
- player.SetBounds(this.playerBounds);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //קן חדש כלומר בתחילת המשחק/כאשר נקודת הכיול נעלמה
- //כאשר נקודת הכיול נעלמת הוא מסיר את השחקן מהמערך-גודל המערך כמו בתחילת המשחק שווה ל0
- //במקרה שיש יותר משחקן אחד מול המצלמה הוא בעצם רוצה להוסיף למערך פעמיים
- //התנאי הזה יגרום לו להוסיף תמיד פעם אחת בלבד
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- if (players.Count == 0) //$$
- {
- player = new Player(skeletonSlot);
- player.SetJointsAndBonesBrushesOfPlayers(players.Count);
- player.SetBounds(this.playerBounds);
- this.players.Add(skeletonSlot, player);
- string s = "add" + skeletonSlot.ToString() + "," + player.GetId();
- }
- }
- player.LastUpdated = DateTime.Now;
- // Update player's bone and joint positions
- if (skeleton.Joints.Count > 0)
- {
- player.IsAlive = true;
- // Head, hands, feet (hit testing happens in order here)
- player.UpdateJointPosition(skeleton.Joints, JointType.Head);
- player.UpdateJointPosition(skeleton.Joints, JointType.HandLeft);
- player.UpdateJointPosition(skeleton.Joints, JointType.HandRight);
- player.UpdateJointPosition(skeleton.Joints, JointType.FootLeft);
- player.UpdateJointPosition(skeleton.Joints, JointType.FootRight);
- // Hands and arms
- player.UpdateBonePosition(skeleton.Joints, JointType.HandRight, JointType.WristRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.WristRight, JointType.ElbowRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.ElbowRight, JointType.ShoulderRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.HandLeft, JointType.WristLeft);
- player.UpdateBonePosition(skeleton.Joints, JointType.WristLeft, JointType.ElbowLeft);
- player.UpdateBonePosition(skeleton.Joints, JointType.ElbowLeft, JointType.ShoulderLeft);
- // Head and Shoulders
- player.UpdateBonePosition(skeleton.Joints, JointType.ShoulderCenter, JointType.Head);
- player.UpdateBonePosition(skeleton.Joints, JointType.ShoulderLeft, JointType.ShoulderCenter);
- player.UpdateBonePosition(skeleton.Joints, JointType.ShoulderCenter, JointType.ShoulderRight);
- // Legs
- player.UpdateBonePosition(skeleton.Joints, JointType.HipLeft, JointType.KneeLeft);
- player.UpdateBonePosition(skeleton.Joints, JointType.KneeLeft, JointType.AnkleLeft);
- player.UpdateBonePosition(skeleton.Joints, JointType.AnkleLeft, JointType.FootLeft);
- player.UpdateBonePosition(skeleton.Joints, JointType.HipRight, JointType.KneeRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.KneeRight, JointType.AnkleRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.AnkleRight, JointType.FootRight);
- player.UpdateBonePosition(skeleton.Joints, JointType.HipLeft, JointType.HipCenter);
- player.UpdateBonePosition(skeleton.Joints, JointType.HipCenter, JointType.HipRight);
- // Spine
- player.UpdateBonePosition(skeleton.Joints, JointType.HipCenter, JointType.ShoulderCenter);
- }
- }
- skeletonSlot++;
- }
- }
- }
- }
- private void CheckPlayers()
- {
- foreach (var player in this.players)
- {
- if (!player.Value.IsAlive)
- {
- // Player left scene since we aren't tracking it anymore, so remove from dictionary
- this.players.Remove(player.Value.GetId());
- break;
- }
- }
- // Count alive players
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //alive-מספר השחקנים שיש במשחק
- int alive = this.players.Count(player => player.Value.IsAlive);
- if (alive != this.playersAlive)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //ישנם 2 שחקנים במשחק ולכן מצב המשחק =ל2 שחקנים
- if (alive == 2)
- {
- this.myFallingThings.SetGameMode(GameMode.TwoPlayer);
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //ישנו שחקן אחד בלבד במשחק ולכן מצב המשחק =ל2שחקן אחד
- else if (alive == 1)
- {
- this.myFallingThings.SetGameMode(GameMode.Solo);
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //אים אף שחקן במשחק ולכן מצב המשחק=ל כבוי
- else if (alive == 0)
- {
- this.myFallingThings.SetGameMode(GameMode.Off);
- }
- if ((this.playersAlive == 0) && (this.mySpeechRecognizer != null))
- {
- BannerText.NewBanner(
- Properties.Resources.Vocabulary,
- this.screenRect,
- true,
- System.Windows.Media.Color.FromArgb(200, 255, 255, 255));
- }
- this.playersAlive = alive;
- }
- }
- private void PlayfieldSizeChanged(object sender, SizeChangedEventArgs e)
- {
- this.UpdatePlayfieldSize();
- }
- private void UpdatePlayfieldSize()
- {
- // Size of player wrt size of playfield, putting ourselves low on the screen.
- this.screenRect.X = 0;
- this.screenRect.Y = 0;
- this.screenRect.Width = this.playfield.ActualWidth;
- this.screenRect.Height = this.playfield.ActualHeight;
- BannerText.UpdateBounds(this.screenRect);
- this.playerBounds.X = 0;
- this.playerBounds.Width = this.playfield.ActualWidth;
- this.playerBounds.Y = this.playfield.ActualHeight * 0.2;
- this.playerBounds.Height = this.playfield.ActualHeight * 0.75;
- foreach (var player in this.players)
- {
- player.Value.SetBounds(this.playerBounds);
- }
- Rect fallingBounds = this.playerBounds;
- fallingBounds.Y = 0;
- fallingBounds.Height = playfield.ActualHeight;
- if (this.myFallingThings != null)
- {
- this.myFallingThings.SetBoundaries(fallingBounds);
- }
- }
- #endregion Kinect Skeleton processing
- #region GameTimer/Thread
- private void GameThread()
- {
- this.runningGameThread = true;
- this.predNextFrame = DateTime.Now;
- this.actualFrameTime = 1000.0 / this.targetFramerate;
- // Try to dispatch at as constant of a framerate as possible by sleeping just enough since
- // the last time we dispatched.
- while (this.runningGameThread)
- {
- // Calculate average framerate.
- DateTime now = DateTime.Now;
- if (this.lastFrameDrawn == DateTime.MinValue)
- {
- this.lastFrameDrawn = now;
- }
- double ms = now.Subtract(this.lastFrameDrawn).TotalMilliseconds;
- this.actualFrameTime = (this.actualFrameTime * 0.95) + (0.05 * ms);
- this.lastFrameDrawn = now;
- // Adjust target framerate down if we're not achieving that rate
- this.frameCount++;
- if ((this.frameCount % 100 == 0) && (1000.0 / this.actualFrameTime < this.targetFramerate * 0.92))
- {
- this.targetFramerate = Math.Max(MinFramerate, (this.targetFramerate + (1000.0 / this.actualFrameTime)) / 2);
- }
- if (now > this.predNextFrame)
- {
- this.predNextFrame = now;
- }
- else
- {
- double milliseconds = this.predNextFrame.Subtract(now).TotalMilliseconds;
- if (milliseconds >= TimerResolution)
- {
- Thread.Sleep((int)(milliseconds + 0.5));
- }
- }
- this.predNextFrame += TimeSpan.FromMilliseconds(1000.0 / this.targetFramerate);
- this.Dispatcher.Invoke(DispatcherPriority.Send, new Action<int>(this.HandleGameTimer), 0);
- }
- }
- private void HandleGameTimer(int param)
- {
- // Every so often, notify what our actual framerate is
- if ((this.frameCount % 100) == 0)
- {
- this.myFallingThings.SetFramerate(1000.0 / this.actualFrameTime);
- }
- // Advance animations, and do hit testing.
- for (int i = 0; i < NumIntraFrames; ++i)
- {
- foreach (var pair in this.players)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //ברגע שיש כבר שחקן אחד במערך-ברגע שיציג שחקן לפחות אחד על המסך יתחיל לחפש פגיעה
- HitType hit = this.myFallingThings.LookForHits(pair.Value.Segments, pair.Value.GetId());
- //@@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //@@אם היתה פגיעה ב"סינג" לא משנה מאיזה סוג
- if (hit != HitType.None)//@@ //1234
- {//@@ //1234
- int playerIdOfCurrentHitThing = pair.Key;//@@ //1234
- //@@$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$// //1234
- //@@צביעת הסגמנט שפגע ב"סינג //1234
- KeyValuePair<string, int> typeAndIdPlayerOfCurrentHitThing = new KeyValuePair<string, int>(); //1234
- { //1234
- new KeyValuePair<string, int>(myFallingThings.GetcurrentTypeOfHitThing(), playerIdOfCurrentHitThing); //1234
- } //1234
- this.players[pair.Key].typeAndPlayerIdHit = typeAndIdPlayerOfCurrentHitThing; //1234
- }//@@
- if ((hit & HitType.Squeezed) != 0)//bbb
- {
- this.squeezeSound.Play();
- SetImg(); //$$
- }
- else if ((hit & HitType.Popped) != 0)//bbb
- {
- this.popSound.Play();
- SetImg(); //$$
- }
- else if ((hit & HitType.Hand) != 0)//bbb
- {
- this.hitSound.Play();
- }
- }
- this.myFallingThings.AdvanceFrame();
- }
- // Draw new Wpf scene by adding all objects to canvas
- playfield.Children.Clear();
- this.myFallingThings.DrawFrame(this.playfield.Children);
- foreach (var player in this.players)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //לדעת כמה שחקנים יש במערך בכל זמן-לשם בדיקה
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- if (players.Count > 1)//$$
- numOfPlayers= players.Count;//$$
- player.Value.Draw(playfield.Children);
- }
- BannerText.Draw(playfield.Children);
- FlyingText.Draw(playfield.Children);
- this.CheckPlayers();
- }
- #endregion GameTimer/Thread
- #region Kinect Speech processing
- private void RecognizerSaidSomething(object sender, SpeechRecognizer.SaidSomethingEventArgs e)
- {
- FlyingText.NewFlyingText(this.screenRect.Width / 30, new Point(this.screenRect.Width / 2, this.screenRect.Height / 2), e.Matched);
- switch (e.Verb)
- {
- case SpeechRecognizer.Verbs.Pause:
- this.myFallingThings.SetDropRate(0);
- this.myFallingThings.SetGravity(0);
- break;
- case SpeechRecognizer.Verbs.Resume:
- this.myFallingThings.SetDropRate(this.dropRate);
- this.myFallingThings.SetGravity(this.dropGravity);
- break;
- case SpeechRecognizer.Verbs.Reset:
- this.dropRate = DefaultDropRate;
- this.dropSize = DefaultDropSize;
- this.dropGravity = DefaultDropGravity;
- this.myFallingThings.SetPolies(PolyType.All);
- this.myFallingThings.SetDropRate(this.dropRate);
- this.myFallingThings.SetGravity(this.dropGravity);
- this.myFallingThings.SetSize(this.dropSize);
- this.myFallingThings.SetShapesColor(System.Windows.Media.Color.FromRgb(0, 0, 0), true);
- this.myFallingThings.Reset();
- break;
- case SpeechRecognizer.Verbs.DoShapes:
- this.myFallingThings.SetPolies(e.Shape);
- break;
- case SpeechRecognizer.Verbs.RandomColors:
- this.myFallingThings.SetShapesColor(System.Windows.Media.Color.FromRgb(0, 0, 0), true);
- break;
- case SpeechRecognizer.Verbs.Colorize:
- this.myFallingThings.SetShapesColor(e.RgbColor, false);
- break;
- case SpeechRecognizer.Verbs.ShapesAndColors:
- this.myFallingThings.SetPolies(e.Shape);
- this.myFallingThings.SetShapesColor(e.RgbColor, false);
- break;
- case SpeechRecognizer.Verbs.More:
- this.dropRate *= 1.5;
- this.myFallingThings.SetDropRate(this.dropRate);
- break;
- case SpeechRecognizer.Verbs.Fewer:
- this.dropRate /= 1.5;
- this.myFallingThings.SetDropRate(this.dropRate);
- break;
- case SpeechRecognizer.Verbs.Bigger:
- this.dropSize *= 1.5;
- if (this.dropSize > MaxShapeSize)
- {
- this.dropSize = MaxShapeSize;
- }
- this.myFallingThings.SetSize(this.dropSize);
- break;
- case SpeechRecognizer.Verbs.Biggest:
- this.dropSize = MaxShapeSize;
- this.myFallingThings.SetSize(this.dropSize);
- break;
- case SpeechRecognizer.Verbs.Smaller:
- this.dropSize /= 1.5;
- if (this.dropSize < MinShapeSize)
- {
- this.dropSize = MinShapeSize;
- }
- this.myFallingThings.SetSize(this.dropSize);
- break;
- case SpeechRecognizer.Verbs.Smallest:
- this.dropSize = MinShapeSize;
- this.myFallingThings.SetSize(this.dropSize);
- break;
- case SpeechRecognizer.Verbs.Faster:
- this.dropGravity *= 1.25;
- if (this.dropGravity > 4.0)
- {
- this.dropGravity = 4.0;
- }
- this.myFallingThings.SetGravity(this.dropGravity);
- break;
- case SpeechRecognizer.Verbs.Slower:
- this.dropGravity /= 1.25;
- if (this.dropGravity < 0.25)
- {
- this.dropGravity = 0.25;
- }
- this.myFallingThings.SetGravity(this.dropGravity);
- break;
- }
- }
- private void EnableAecChecked(object sender, RoutedEventArgs e)
- {
- var enableAecCheckBox = (CheckBox)sender;
- this.UpdateEchoCancellation(enableAecCheckBox);
- }
- private void UpdateEchoCancellation(CheckBox aecCheckBox)
- {
- this.mySpeechRecognizer.EchoCancellationMode = aecCheckBox.IsChecked != null && aecCheckBox.IsChecked.Value
- ? EchoCancellationMode.CancellationAndSuppression
- : EchoCancellationMode.None;
- }
- #endregion Kinect Speech processing
- }
- }
- p
- ***********************************
- //------------------------------------------------------------------------------
- // <copyright file="Player.cs" company="Microsoft">
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // </copyright>
- //------------------------------------------------------------------------------
- namespace ShapeGame
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- using System.Windows.Shapes;
- using Microsoft.Kinect;
- using ShapeGame.Utils;
- public class Player
- {
- private const double BoneSize = 0.01;
- private const double HeadSize = 0.075;
- private const double HandSize = 0.03;
- // Keeping track of all bone segments of interest as well as head, hands and feet
- private /*readonly*/ Dictionary<Bone, BoneData> segments = new Dictionary<Bone, BoneData>();
- public /*$$ readonly $$*/ System.Windows.Media.Brush jointsBrush;
- public /*$$ readonly $$*/ System.Windows.Media.Brush bonesBrush;
- public /*$$ readonly $$*/ System.Windows.Media.Brush jointsBrushesOFsegmentHit = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 189, 0)) /*צהוב*/;
- public /*$$ readonly $$*/ System.Windows.Media.Brush bonesBrushesOFsegmentHit = new SolidColorBrush(System.Windows.Media.Color.FromRgb(13, 120, 61))/*ירוק*/;
- /*private$$*/
- public readonly int id;
- private static int colorId;
- private Rect playerBounds;
- private System.Windows.Point playerCenter;
- private double playerScale;
- //$$$$$$$$$$$$4
- private int i =0;
- int indexSegmentHit = 0;
- //$$public bool isHit=false;
- public KeyValuePair<string,int> typeAndPlayerIdHit;
- public string str;
- //$$$$$$$$$$$$$$
- public Player(int skeletonSlot)
- {
- this.id = skeletonSlot;
- }
- public bool IsAlive { get; set; }
- public DateTime LastUpdated { get; set; }
- public Dictionary<Bone, BoneData> Segments
- {
- get
- {
- return this.segments;
- }
- }
- public int GetId()
- {
- return this.id;
- }
- public void SetJointsAndBonesBrushesOfPlayers(int numOfPlayers) //$$
- {
- if (numOfPlayers == 0) //$$
- {
- this.jointsBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(10, 2, 18)); //$$סגול
- this.bonesBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(130, 20, 240)); //$$שחור
- this.LastUpdated = DateTime.Now;//$$
- }
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //במקרה של שני שחקנים צבע השלד יוגרל
- else
- {
- // Generate one of 7 colors for player
- int[] mixR = { 1, 1, 1, 0, 1, 0, 0 };
- int[] mixG = { 1, 1, 0, 1, 0, 1, 0 };
- int[] mixB = { 1, 0, 1, 1, 0, 0, 1 };
- byte[] jointCols = { 245, 200 };
- byte[] boneCols = { 235, 160 };
- int i = colorId;
- colorId = (colorId + 1) % mixR.Count();
- this.bonesBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(jointCols[mixR[i]], jointCols[mixG[i]], jointCols[mixB[i]]));
- this.jointsBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(boneCols[mixR[i]], boneCols[mixG[i]], boneCols[mixB[i]]));
- this.LastUpdated = DateTime.Now;
- }
- }
- public void SetBounds(Rect r)
- {
- this.playerBounds = r;
- this.playerCenter.X = (this.playerBounds.Left + this.playerBounds.Right) / 2;
- this.playerCenter.Y = (this.playerBounds.Top + this.playerBounds.Bottom) / 2;
- this.playerScale = Math.Min(this.playerBounds.Width, this.playerBounds.Height / 2);
- }
- public void UpdateBonePosition(Microsoft.Kinect.JointCollection joints, JointType j1, JointType j2)
- {
- var seg = new Segment(
- (joints[j1].Position.X * this.playerScale) + this.playerCenter.X,
- this.playerCenter.Y - (joints[j1].Position.Y * this.playerScale),
- (joints[j2].Position.X * this.playerScale) + this.playerCenter.X,
- this.playerCenter.Y - (joints[j2].Position.Y * this.playerScale))
- { Radius = Math.Max(3.0, this.playerBounds.Height * BoneSize) / 2 };
- this.UpdateSegmentPosition(j1, j2, seg);
- }
- public void UpdateJointPosition(Microsoft.Kinect.JointCollection joints, JointType j)
- {
- var seg = new Segment(
- (joints[j].Position.X * this.playerScale) + this.playerCenter.X,
- this.playerCenter.Y - (joints[j].Position.Y * this.playerScale))
- { Radius = this.playerBounds.Height * ((j == JointType.Head) ? HeadSize : HandSize) / 2 };
- this.UpdateSegmentPosition(j, j, seg);
- }
- public void Draw(UIElementCollection children)
- {
- if (!this.IsAlive)
- {
- return;
- }
- // Draw all bones first, then circles (head and hands).
- DateTime cur = DateTime.Now;
- foreach (var segment in this.segments)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //תפיסת הסגמנט שפגע ב"סינג" על מנת לצבוע אותו בצבע אחר
- var isHitSegment1 = (/*id == segmentAndPlayerIdHit.Value && */segment.Key.Joint1.ToString().Equals(typeAndPlayerIdHit.Key));//$$
- Segment seg = segment.Value.GetEstimatedSegment(cur);
- if (!seg.IsCircle())
- {
- var line = new Line
- {
- StrokeThickness = seg.Radius * 2,
- X1 = seg.X1,
- Y1 = seg.Y1,
- X2 = seg.X2,
- Y2 = seg.Y2,
- Stroke = isHitSegment1 ? jointsBrushesOFsegmentHit : this.bonesBrush,//$$ //1234
- StrokeEndLineCap = PenLineCap.Round,
- StrokeStartLineCap = PenLineCap.Round
- };
- children.Add(line);
- }
- }
- foreach (var segment in this.segments)
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //תפיסת הסגמנט שפגע ב"סינג" על מנת לצבוע אותו בצבע אחר
- var isHitSegment2 = (/*id == segmentAndPlayerIdHit.Value && */segment.Key.Joint1.ToString().Equals(typeAndPlayerIdHit.Key));//$$
- var s = segment.Key.Joint1.ToString();
- Segment seg = segment.Value.GetEstimatedSegment(cur);
- if (seg.IsCircle())
- {
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//??
- //תפיסת הסגמנט שפגע ב"סינג" על מנת לצבוע אותו בצבע אחר
- var circle = new Ellipse { Width = seg.Radius * 2, Height = seg.Radius * 2 };
- circle.SetValue(Canvas.LeftProperty, seg.X1 - seg.Radius);
- circle.SetValue(Canvas.TopProperty, seg.Y1 - seg.Radius);
- //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
- //צבע המתאר של מקומות עגולים כמו יד שמסמן כמו בוקס (עגול) והראש יהיה בצבע של המפרקים
- circle.Stroke = isHitSegment2 ? jointsBrushesOFsegmentHit : this.jointsBrush;//צבע המפרקים //$$
- circle.StrokeThickness = 1;
- circle.Fill = isHitSegment2 ? jointsBrushesOFsegmentHit : this.bonesBrush;//צבע העצמות //$$
- children.Add(circle);
- }
- }
- // Remove unused players after 1/2 second.
- if (DateTime.Now.Subtract(this.LastUpdated).TotalMilliseconds > 500)
- {
- this.IsAlive = false;
- }
- }
- private void UpdateSegmentPosition(JointType j1, JointType j2, Segment seg)
- {
- var bone = new Bone(j1, j2);
- if (this.segments.ContainsKey(bone))
- {
- BoneData data = this.segments[bone];
- data.UpdateSegment(seg);
- this.segments[bone] = data;
- }
- else
- {
- this.segments.Add(bone, new BoneData(seg));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement