public void updatepaddle(Ball ball,Paddle P) { counter++; AIPaddle = P; Vector2 PaddleCenter = new Vector2(AIPaddle.Position.X, AIPaddle.Position.Y + (AIPaddle.Height) / 2); if (counter != Difficulty) { if (ball.Location.Y > (PaddleCenter.Y) && ball.Motion.X < 0) { AIPaddle.computerinput(10); } else if (ball.Location.Y < (PaddleCenter.Y) && ball.Motion.X < 0) { AIPaddle.computerinput(-10); } else if (ball.Motion.X < 0 && PaddleCenter.Y < 250) { AIPaddle.computerinput(10); } else if (ball.Motion.X < 0 && PaddleCenter.Y > 250) { AIPaddle.computerinput(-10); } } else { counter = 0; } }
public static void Main (string[] args) { Window window = new Window (1200, 700, "RingPong", PixelFormat.RGB); //Definizione : Ring, Finestra del programma, Palla, Barra Player 1, Barra Player 2 Ring ring = new Ring (window); Ball ball = new Ball (); //Parametri Bar : Posizione X, Posizione Y, Comando per andare su, Comando per andare giù Bar bar1= new Bar (window.width-25, window.height/2, KeyCode.Up, KeyCode.Down); Bar bar2 = new Bar (10, window.height/2, KeyCode.W, KeyCode.S); //Inizio Gioco bool isGameRunning = true; while (isGameRunning) { //Pulizia della Finestra ring.Clear(window, 0, 0, 0); ring.Update (window, bar1, bar2, ball); window.Blit(); //Scrittura del punteggio if (bar1.GetPoints () == 15) { Console.WriteLine ("Player 1 VINCE"); isGameRunning = false; } else if (bar2.GetPoints () == 15) { Console.WriteLine ("Player 2 VINCE"); isGameRunning = false; } } }
public void Move(Window window, Ball ball, int h) { if (window.GetKey (KeyCode.Up)) { this.y -= this.speed; } if (window.GetKey (KeyCode.Down)) { this.y += this.speed; } if (this.y <= 14) this.y += this.speed; if (this.y >= h - this.height - 15) this.y -= this.speed; if ((ball.GetX () == this.x - 15) && (ball.GetY () >= this.y) && (ball.GetY () <= this.y + this.height)) { ball.SetDirezioneX (ball.GetDirezioneX () * -1); if ((ball.GetY () < this.y + (height / 5))) ball.SetDirezioneY (-2); else if ((ball.GetY () < (this.y + (height / 5) * 2))) ball.SetDirezioneY (-1); else if ((ball.GetY () < (this.y + (height / 5) * 3))) ball.SetDirezioneY (0); else if ((ball.GetY () < (this.y + (height / 5) * 4))) ball.SetDirezioneY (1); else ball.SetDirezioneY (2); } }
public BallOutMananger(Ball ball, int worldWidth, SoundEffect soundEffect, Score score) { this.score = score; this.ball = ball; this.worldWidth = worldWidth; this.soundEffect = soundEffect; }
public void Update(Window window, Bar bar1, Bar bar2, Ball ball) { //Disegno parte superiore del Ring this.DrawRectFilled (window, 10, 10, 255, 255, 255, window.width-20, 10); //Disegno parte inferiore del Ring this.DrawRectFilled (window, 10, window.height-20, 255, 255, 255, window.width-20, 10); //Disegno righe tratteggiate che separano il ring int k = 20; while(k < window.height-20) { this.DrawRectFilled(window, window.width/2, k, 255, 255, 255, 7, 30); k += 40; } //Disegno la Palla //this.DrawRectFilled (window, ball.GetX(), ball.GetY(), ball.GetR(), ball.GetG(), ball.GetB(), ball.GetWidht(), ball.GetHeight()); this.DrawCircle(window, ball.GetX(), ball.GetY(), ball.GetRaggio(), 255, 255, 255); //Disegno la barra del Player 1 this.DrawRectFilled (window, bar1.GetX(), bar1.GetY(), 255, 0, 0, bar1.GetWidht(), bar1.GetHeight()); //Disegno la Barra del Player 2 this.DrawRectFilled (window, bar2.GetX(), bar2.GetY(), 0, 255, 0, bar2.GetWidht(), bar2.GetHeight()); //Movimeto barra del Player 1 bar1.Move (window, ball); //Movimeto barra del Player 2 bar2.Move2 (window, ball, window.height); //Movimeto della Palla ball.Update (window.height, window.width); numb1.CurrentResultDec (window, bar1.GetPoints()); numb2.CurrentResult (window, bar1.GetPoints()); numb3.CurrentResultDec (window, bar2.GetPoints()); numb4.CurrentResult (window, bar2.GetPoints()); }
private async void moveBall() { while (true) { await Task.Delay(30); moving_ball.move(gameField,ball,POne,PTwo); PlayerOne_Counter.Text = "" + PlayerOnePoints; PlayerTwo_Counter.Text = "" + PlayerTwoPoints; if (moving_ball.getX() < 0) { PlayerOnePoints++; PlayerOne_Counter.Text = "" + PlayerOnePoints; moving_ball = new Ball(350, 250); } if (moving_ball.getX() > gameField.Width - ball.Width) { PlayerTwoPoints++; PlayerTwo_Counter.Text = "" + PlayerTwoPoints; moving_ball = new Ball(350, 250); } } }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); live = Content.Load<Texture2D> ("spr_ball"); background = Content.Load<Texture2D> ("spr_background"); startgame = Content.Load<Texture2D>("spr_startgame"); gameover = Content.Load<Texture2D>("spr_GameOver"); player2wins= Content.Load<Texture2D> ("spr_P2win"); player1wins = Content.Load<Texture2D>("spr_P1win"); paddle = Content.Load<Texture2D> ("spr_paddle"); ball = Content.Load<Texture2D> ("spr_ball"); paddle1 = new Paddles(); velocity = 200; paddle1.position = new Vector2(0, GraphicsDevice.Viewport.Height / 2 - paddle.Height / 2); paddle1.velocity = velocity; paddle2 = new Paddles(); paddle2.position = new Vector2(GraphicsDevice.Viewport.Width - paddle.Width, GraphicsDevice.Viewport.Height / 2 - paddle.Height / 2); paddle2.velocity = velocity; Ball = new Ball(); Ball.position = new Vector2(GraphicsDevice.Viewport.Bounds.Width / 2 - ball.Width / 2, GraphicsDevice.Viewport.Bounds.Height / 2 - ball.Height / 2); Ball.velocity = velocity; gamestate = 0; acceleration = 1.07f; color = Color.White; angle = new Vector2(1,0); player1lives = 3; player2lives = 3; }
/// <summary> /// Initialises Game Engine with given dimensions of game-world /// </summary> /// <param name="clientSize">dimensions of game-world</param> public GameEngine(Size clientSize) { this.clientSize = clientSize; ballStartPosition = new Point(clientSize.Width / 2, clientSize.Height / 2); ball = new Ball(BALL_SIZE, Color.Orange, clientSize, ballStartPosition); Size paddleSize = new Size(PADDLE_WIDTH, PADDLE_HEIGHT); Point paddlePosition = new Point(PADDLE_X, PADDLE_Y); leftPaddle = new Paddle(paddleSize, paddlePosition, Color.Red, clientSize, "femaleGrunt.wav"); paddlePosition = new Point((clientSize.Width - PADDLE_WIDTH) - PADDLE_X, PADDLE_Y); rightPaddle = new Paddle(paddleSize, paddlePosition, Color.Red, clientSize, "maleGrunt.wav"); topCentre = new Point((clientSize.Width / 2), 0); bottomCentre = new Point((clientSize.Width / 2), clientSize.Height); dashedLinePen = new Pen(Color.White, PENWIDTH); dashedLinePen.DashStyle = DashStyle.Dash; winConditions = false; int x = Convert.ToInt32((clientSize.Width * POSITION_1ST_QUARTER) - FONT_SIZE); Point position = new Point(x, (clientSize.Height / POSITION_Y_DIVISOR)); scoreLeft = new Score(position); x = Convert.ToInt32((clientSize.Width * POSITION_3RD_QUARTER) - FONT_SIZE); position = new Point (x, (clientSize.Height / POSITION_Y_DIVISOR)); scoreRight = new Score(position); }
static void BounceX(Paddle p1, Ball b1) { if ((b1.Pos[1] <= p1.Pos[1] && b1.Pos[1] >= p1.Pos[1] - p1.Size) && (p1.Pos[0] >= b1.Pos[0] - (b1.Vel[0] + 1) && p1.Pos[0] <= b1.Pos[0] + b1.Vel[0])) { b1.Vel[0] = -b1.Vel[0]; b1.Last = p1; } }
public PongGame(Size ScreenDimensions) { PongBall = new Ball(new Vector2(0.0f, 0.0f), 1.0f); LeftPaddle = new Paddle(new Vector2(-19.0f, 0.0f), 3.0f); RightPaddle = new Paddle(new Vector2(19.0f, 0.0f), 3.0f); Board = new GameBoard(20.0f, 15.0f); Score = new int[2] { 0, 0 }; }
public static void KeyboardPlayer(RectangleF area, float timeRatio, Ball ball, Racquet racquet, Keys keysEvent, Point? mouseLocation) { const int moveSpeed = 50; if (keysEvent == Keys.Z) racquet.SetY(racquet.Y - (int) (moveSpeed * timeRatio), area); else if (keysEvent == Keys.S) racquet.SetY(racquet.Y + (int)(moveSpeed * timeRatio), area); }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { ScreenWidth = GraphicsDevice.Viewport.Width; ScreenHeight = GraphicsDevice.Viewport.Height; player1 = new Player(); player2 = new Player(); ball = new Ball(); base.Initialize(); }
//In questo metodo facciamo gli UPDATE della barra del player 1 public void Move(Window window, Ball ball) { if(window.GetKey(this.up)) { this.y -= this.speed; } if(window.GetKey(this.down)) { this.y += this.speed; } //Controllo pe non superare il bordo superiore if (this.y <= 14) this.y = 20; //Controllo per non superare il bordo inferiore if (this.y >= window.height-this.height-17) this.y = window.height - this.height-20; //int distance = (int)(ball.GetRaggio() * 26.67)/100; //Controllo il punto della barra in cui è avvenuto il contatto con la pallina per far cambiare l'angolazione del tiro if ((ball.GetX () + ball.GetRaggio()-17 >= this.x - 15) && (ball.GetY () >= this.y) && (ball.GetY () <= this.y + this.height)) { ball.SetDirezioneX (ball.GetDirezioneX () * -1); ball.SetR(255); ball.SetG(0); ball.SetB(0); if ((ball.GetY () < this.y + (height / 5))) ball.SetDirezioneY (-2); else if ((ball.GetY () < (this.y + (height / 5) * 2))) ball.SetDirezioneY (-1); else if ((ball.GetY () < (this.y + (height / 5) * 3))) ball.SetDirezioneY (0); else if ((ball.GetY () < (this.y + (height / 5) * 4))) ball.SetDirezioneY (1); else ball.SetDirezioneY (2); } else if (ball.GetX () > window.width) { points++; ball.SetX (window.width/2); ball.SetY (window.height/2); if (RandomGenerator.GetRandom (0, 1) == 0) ball.SetDirezioneX (-1); else ball.SetDirezioneX (1); ball.SetDirezioneY (RandomGenerator.GetRandom (-2, 2)); } }
static void DrawB(Ball b1) { try { Console.SetCursorPosition(b1.Pos[0], b1.Pos[1]); Console.Write(b1.Char); } catch { b1.Pos[0] = -b1.Pos[0]; } }
protected override void Init() { base.Init(); Entities.world2D.Gravity /= 10.0f; Entities.Register(new Sprite(new Texture("Background.jpg"), new Size(2.0f, 1.4f))); ball = new Ball(new Sprite(new Texture("Ball.png"), Constants.BallSize)); ResetBall(); var paddleTexture = new Texture("Paddle.png"); leftPaddle = new Paddle(new Sprite(paddleTexture, Constants.PaddleSize), new Vector2D(Constants.LeftPaddleX, 0)); rightPaddle = new Paddle(new Sprite(paddleTexture, Constants.PaddleSize), new Vector2D(Constants.RightPaddleX, 0)); }
public Ball Clone() { Ball newBall = new Ball(); newBall.position = this.position; newBall.width = this.width; newBall.height = this.height; newBall.speedX = this.speedX; newBall.speedY = this.speedY; newBall.boundingBox = this.boundingBox; newBall.right = this.right; newBall.start = this.start; newBall.up = this.up; return newBall; }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); var gameBoundaries = new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height); var paddleTexture = Content.Load<Texture2D>("Paddle"); playerPaddle = new Paddle(paddleTexture, Vector2.Zero, gameBoundaries, PlayerTypes.Human); computerPaddle = new Paddle(paddleTexture, new Vector2(gameBoundaries.Width - paddleTexture.Width, 0), gameBoundaries, PlayerTypes.Computer); ball = new Ball(Content.Load<Texture2D>("Ball"), Vector2.Zero, gameBoundaries); ball.AttachTo(playerPaddle); score = new Score(Content.Load<SpriteFont>("GameFont"), gameBoundaries); gameObjects = new GameObjects { PlayerPaddle = playerPaddle, ComputerPaddle = computerPaddle, Ball = ball, Score=score }; }
public override void UpdatePosition(Ball ball) { if (ball.GetDirection() > 1.5 * Math.PI || ball.GetDirection() < 0.5 * Math.PI) { if (ball.GetPosition().Y - 5 > GetPosition().Y + GetSize().Height / 2) { MoveDown(); } else if (ball.GetPosition().Y == GetPosition().Y + GetSize().Height / 2) { } else if (ball.GetPosition().Y + 5 < GetPosition().Y + GetSize().Height / 2) { MoveUp(); } } base.UpdatePosition(ball); }
public GameScene() { this.Camera.SetViewFromViewport(); _physics = new PongPhysics(); ball = new Ball(_physics.SceneBodies[(int)PongPhysics.BODIES.Ball]); _player = new Paddle(Paddle.PaddleType.PLAYER, _physics.SceneBodies[(int)PongPhysics.BODIES.Player]); _ai = new Paddle(Paddle.PaddleType.AI, _physics.SceneBodies[(int)PongPhysics.BODIES.Ai]); _scoreboard = new Scoreboard(); this.AddChild(_scoreboard); this.AddChild(ball); this.AddChild(_player); this.AddChild(_ai); // This is debug routine that will draw the physics bounding box around the players paddle if(DEBUG_BOUNDINGBOXS) { this.AdHocDraw += () => { var bottomLeftPlayer = _physics.SceneBodies[(int)PongPhysics.BODIES.Player].AabbMin; var topRightPlayer = _physics.SceneBodies[(int)PongPhysics.BODIES.Player].AabbMax; Director.Instance.DrawHelpers.DrawBounds2Fill( new Bounds2(bottomLeftPlayer*PongPhysics.PtoM,topRightPlayer*PongPhysics.PtoM)); var bottomLeftAi = _physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMin; var topRightAi = _physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMax; Director.Instance.DrawHelpers.DrawBounds2Fill( new Bounds2(bottomLeftAi*PongPhysics.PtoM,topRightAi*PongPhysics.PtoM)); var bottomLeftBall = _physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMin; var topRightBall = _physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMax; Director.Instance.DrawHelpers.DrawBounds2Fill( new Bounds2(bottomLeftBall*PongPhysics.PtoM,topRightBall*PongPhysics.PtoM)); }; } //Now load the sound fx and create a player _pongSound = new Sound("/Application/audio/pongblip.wav"); _pongBlipSoundPlayer = _pongSound.CreatePlayer(); Scheduler.Instance.ScheduleUpdateForTarget(this,0,false); }
public GameWorld(ContentManager Content) { ballTex = Content.Load<Texture2D>("UI/lives"); backgroundTex = Content.Load<Texture2D>("UI/background"); startTex = Content.Load<Texture2D>("UI/startScreen"); gameFont = Content.Load<SpriteFont>("UI/gameFont"); MediaPlayer.Play(Content.Load<Song>("Sound/bg_music")); rightPlayer = new Pad(Content, 1); leftPlayer = new Pad(Content, 0); ball = new Ball(Content); disco = new Disco[maxDisco]; for (int i = 0; i < maxDisco; i++) { disco[i] = new Disco(Content); } Reset(GameState.GameStart); //Sets the game to initial positions and sets correct gamestate }
public static void Computer(RectangleF area, float timeRatio, Ball ball, Racquet racquet, Keys keysEvent, Point? mouseLocation) { const int moveSpeed = 10; if (ball.CenterY < racquet.Y) { racquet.SetY( racquet.Y - (int) Math.Min( racquet.Y - ball.CenterY, moveSpeed * timeRatio ), area ); } else if (ball.CenterY > racquet.Y) { racquet.SetY( racquet.Y + (int)Math.Min( ball.CenterY - racquet.Y, moveSpeed * timeRatio ), area ); } }
public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; menuSprite = new Sprite(); pointerSprite = new Sprite(); creditSprite = new Sprite(); gameOverSprite = new Sprite(); gameball = new Ball(285, 285, 30, 30, 5, 5); paddle1 = new Paddle(1); paddle2 = new Paddle(2); paddle3 = new Paddle(3); paddle4 = new Paddle(4); ballsprite = new Sprite(gameball.getx(), gameball.gety()); paddlesprite1 = new Sprite(paddle1.getX(), paddle1.getY()); paddlesprite2 = new Sprite(paddle2.getX(), paddle2.getY()); paddlesprite3 = new Sprite(paddle3.getX(), paddle3.getY()); paddlesprite4 = new Sprite(paddle4.getX(), paddle4.getY()); menu = new Menu(); }
public void Render() { PaddleName? GameStatus = PongBall.UpdateBallLocation(LeftPaddle.YLocation, RightPaddle.YLocation); if (GameStatus != null) { //Add 1 to the score of the winning side if (GameStatus == PaddleName.LEFT) Score[0]++; if (GameStatus == PaddleName.RIGHT) Score[1]++; Console.WriteLine("Player1: {0} | Player2: {1}", Score[0].ToString(), Score[1].ToString()); //reset the ball PongBall = new Ball(new Vector2(0.0f, 0.0f), 1.0f); } PongBall.Render(); LeftPaddle.Render(); RightPaddle.Render(); Board.Render(); }
// Retourne le nouveau mouvement effectué par la // balle en fonction de l'endroit où elle touche // la raquette. public Ball.Movement NewMove(Ball.Movement oldMove, int y) { float xBar = (float) (y - this.Y) / (Heigth / 2); float direction; if (this.Side == RacquetSides.Left) direction = +1; else direction = -1; // Vitesse avant réflexion (distance de Manathan) var oldSpeed = Math.Sqrt( oldMove.X * oldMove.X + oldMove.Y * oldMove.Y ); // Vitesse uni-dimentionnelle amortie (si dx = dy); var oldSpeedMult = Math.Sqrt((oldSpeed * oldSpeed) / 2); // Direction après réflexion var reflX = DxReflection(xBar); var reflY = DyReflection(xBar); // Vitesse de la réflexion var reflSpeed = Math.Sqrt( reflX * reflX + reflY * reflY ); // Vitesse uni-dimentionnelle de la réflexion var reflSpeedMult = Math.Sqrt((reflSpeed * reflSpeed) / 2); // Rapport de vitesse entre la réflexion et l'ancienne vitesse // auquel le multiplicateur de vitesse est appliqué var speedMult = oldSpeedMult / reflSpeedMult * SpeedMult(xBar); return new Ball.Movement( (float) (reflX * speedMult * direction), (float) (reflY * speedMult) ); }
public void ResetPlayfield (int loserIndex) { Paddles = new Paddle[] { new Paddle { Bounds = new Bounds( new Vector2(24, Playfield.Bounds.Center.Y - 48), new Vector2(24 + 16, Playfield.Bounds.Center.Y + 48) ), Playfield = this.Playfield }, new Paddle { Bounds = new Bounds( new Vector2(Graphics.PreferredBackBufferWidth - 24 - 16, Playfield.Bounds.Center.Y - 48), new Vector2(Graphics.PreferredBackBufferWidth - 24, Playfield.Bounds.Center.Y + 48) ), Playfield = this.Playfield } }; var random = new Random(); var velocity = new Vector2(loserIndex == 0 ? 1 : -1, (float)random.NextDouble(-1, 1)); velocity.Normalize(); if (Math.Abs(velocity.Y) < 0.15f) velocity.Y += Math.Sign(velocity.Y) * 0.15f; velocity *= 4; Ball = new Ball { Position = Playfield.Bounds.Center, Velocity = velocity, Playfield = this.Playfield, Radius = 8.0f }; }
protected override void LoadContent() { base.LoadContent (); paddleOne = new Paddle (game, spriteBatch); paddleOne.Direction = new Vector2 (0, 0); paddleTwo = new Paddle (game, spriteBatch); paddleTwo.Direction = new Vector2 (0, 0); ball = new Ball (game, spriteBatch); ball.Direction = new Vector2 (0, 0); paddleOne.LoadContent (content); paddleOne.Position = new Vector2 (20, 20); paddleTwo.LoadContent (content); paddleTwo.Position = new Vector2 (GraphicsDevice.Viewport.Width - 40, GraphicsDevice.Viewport.Height - 100); ball.LoadContent (content); ball.Position = new Vector2 (GraphicsDevice.Viewport.Width + 10, 0); }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); IsMouseVisible = true; masterServerIP = File.ReadAllText(@"Content\MasterServerIP.txt"); if (!hasStarted) { state = State.Connect; focus = FieldFocus.Name; serverNameTextHost = new InputBox(new Vector2(100, 100)); passwordTextHost = new InputBox(new Vector2(100, 130)); serverNameTextJoin = new InputBox(new Vector2(100, 400)); passwordTextJoin = new InputBox(new Vector2(100, 430)); } ballCount = 1; powerCount = 1; powerTimer = 0; allGameObjects = new List<GameObject>(); allGameObjects.Clear(); suicidalObjects = new List<GameObject>(); addThese = new List<GameObject>(); windowHeight = Window.ClientBounds.Height; windowWidth = Window.ClientBounds.Width; if (hasStarted) { #region Sprite pongSprite = new Sprite(new Vector2(200, 200), 0.5f, new Vector2(1, 1), Color.White, SpriteEffects.None); Sprite ballSprite = new Sprite(new Vector2(200, 200), 0.5f, new Vector2(1, 1), Color.White, SpriteEffects.None); Sprite wallSprite = new Sprite(new Vector2(200, 200), 1, new Vector2(80, 2), Color.White, SpriteEffects.None); Sprite netSprite = new Sprite(new Vector2(200, 200), 0.5f, new Vector2(0.5f, 1), Color.White, SpriteEffects.None, @"PongMiddle"); Rectangle pongCollision = new Rectangle(0, 0, 10, 82); Rectangle ballColl = new Rectangle(0, 0, 15, 15); Rectangle pwrColl = new Rectangle(0, 0, 40, 40); Rectangle wallCollision = new Rectangle(0, 0, Window.ClientBounds.Width, 15); SpriteA animatedSprite = new SpriteA(new Vector2(200, 200), 0.5f, new Vector2(1, 1), Color.White, SpriteEffects.None, @"powerpad"); animatedSprite.CreateAnimation("Orb", 8, 0, 1, (648 / 8), (486 / 6), Vector2.Zero, 15f); animatedSprite.PlayAnimation("Orb"); PowerUp powerup = new PowerUp(animatedSprite, new Vector2(rnd.Next(50, 600), rnd.Next(100, 350)), new Vector2(40, 0), 0, Content, pwrColl); SoundEffect wallBounce = Content.Load<SoundEffect>(@"SoundFX\wall_effect"); SoundEffect pad1Bounce = Content.Load<SoundEffect>(@"SoundFX\pad1_effect"); SoundEffect pad2Bounce = Content.Load<SoundEffect>(@"SoundFX\pad2_effect"); GameObject net = new GameObject(netSprite, new Vector2(windowWidth / 2, windowHeight / 2), new Vector2(1, 0), 0, Content, new Rectangle(0, 0, 0, 0)); if (isHost) { p1Pad = new PongPaddle(PlayerNumber.player1, pongSprite, new Vector2(50, 250), new Vector2(0, 0), 100, Content, pongCollision, pad1Bounce); p2PadGobject = new Dummyclass(pongSprite, new Vector2(740, 250), new Vector2(0, 0), 100, Content, pongCollision, 'p', ClientPort, pad2Bounce); myBallDummy = null; } else { p1Pad = new PongPaddle(PlayerNumber.player1, pongSprite, new Vector2(740, 250), new Vector2(0, 0), 100, Content, pongCollision, pad1Bounce); p2PadGobject = new Dummyclass(pongSprite, new Vector2(50, 250), new Vector2(0, 0), 100, Content, pongCollision, 'p', ClientPort, pad1Bounce); myBallDummy = new Dummyclass(ballSprite, new Vector2(400, 200), new Vector2(0, 0), 0, Content, ballColl, 'b', ClientPort + 1, null); } p1Pad.Sprite.Scale = new Vector2(1, 8); //P2 is basicly useless though p2Pad = new PongPaddle(PlayerNumber.player2, pongSprite, new Vector2(740, 250), new Vector2(0, 0), 100, Content, pongCollision, pad2Bounce); myBall = new Ball(ballSprite, new Vector2(400, 200), new Vector2(40f, 20), 100, Content, ballColl, rnd); Wall topWall = new Wall(wallSprite, new Vector2(Window.ClientBounds.Width * 0.5f, 0), new Vector2(0, 1), 0, Content, wallCollision, wallBounce); Wall bottomWall = new Wall(wallSprite, new Vector2(Window.ClientBounds.Width * 0.5f, Window.ClientBounds.Bottom), new Vector2(0, -1), 0, Content, wallCollision, wallBounce); allGameObjects.Add(p1Pad); allGameObjects.Add(p2Pad); allGameObjects.Add(myBall); allGameObjects.Add(topWall); //allGameObjects.Add(powerup); allGameObjects.Add(myBallDummy); allGameObjects.Add(bottomWall); allGameObjects.Add(p2PadGobject); allGameObjects.Add(net); hasJustScored = false; #endregion } }
public void SpawnMoreBalls(int amount) { for (int i = 0; i < amount; i++) { Rectangle ballColl = new Rectangle(0, 0, 15, 15); Sprite ballSprite = new Sprite(new Vector2(200, 200), 0.5f, new Vector2(1, 1), Color.White, SpriteEffects.None); Ball newBall = new Ball(ballSprite, new Vector2(400, 200), new Vector2(40f, 20), 100, Content, ballColl, rnd); addThese.Add(newBall); } ballCount += amount; }
static void DrawPong(int boardX, int boardY, Player lPlayer, Player rPlayer, Ball b, int numTrial, int trialIteration) { Console.Clear(); //for (int y = 0; y < boardY + 2; y++) for (int y = 0; y < boardY; y++) { //if (y == 0 || y == boardX + 2) //{ // Console.Write("-"); //} //for (int x = 0; x < boardX + 2; x++) for (int x = 0; x < boardX; x++) { if (lPlayer == null) { //if (y == 0 || y == boardY + 1) //{ // Console.Write("-"); //} //else //{ // if (x == 0) // { // Console.Write("|"); // } //} } else { if (x == lPlayer.DiscretePaddleX && y == lPlayer.DiscretePaddleY) { Console.Write("|"); } if (x == b.DiscreteBallX && y == b.DiscreteBallY && x == lPlayer.DiscretePaddleX && y == lPlayer.DiscretePaddleY) { Console.Write("X"); } } //if (x == b.DiscreteBallX - 1 && y == b.DiscreteBallY && x == rPlayer.DiscretePaddleX - 1 && y == rPlayer.DiscretePaddleY) if (x == b.DiscreteBallX && y == b.DiscreteBallY && x == rPlayer.DiscretePaddleX && y == rPlayer.DiscretePaddleY) { Console.Write("X"); } //else if (x == rPlayer.DiscretePaddleX-1 && y == rPlayer.DiscretePaddleY) else if (x == rPlayer.DiscretePaddleX && y == rPlayer.DiscretePaddleY) { Console.Write("|"); } //else if (x == b.DiscreteBallX-1 && y == b.DiscreteBallY) else if (x == b.DiscreteBallX && y == b.DiscreteBallY) { Console.Write("*"); } else { //if (y != 0 && y != boardY + 1) //{ // Console.Write(" "); //} Console.Write(" "); } } Console.WriteLine(""); } Console.WriteLine("------------"); Console.WriteLine("Trial #: " + numTrial); Console.WriteLine("Trial Length: " + trialIteration); Console.WriteLine("Number of Agent Deflections: " + rPlayer.Deflections); }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { screenHeight = 600; screenWidth = 800; menu = new Menu(); gamestate = GameStates.Menu; resetTimer = 0; resetTimerInUse = true; lastScored = false; graphics.PreferredBackBufferWidth = screenWidth; graphics.PreferredBackBufferHeight = screenHeight; graphics.IsFullScreen = false; graphics.ApplyChanges(); // TODO: Add your initialization logic here ball = new Ball(Content, new Vector2(screenWidth, screenHeight)); SetUpMulti(); input = new Input(); base.Initialize(); }
protected void gamestart() { playerleft = new Player(new Vector2(50, 480), font,"Player Left"); playerright = new Player(new Vector2(600, 480), font,"Player Right"); Left = new Paddle(0, 213, paddle, Keys.W, Keys.S); Right = new Paddle(740, 213, paddle, Keys.Up, Keys.Down); upb = new Boundary(0, 0, 750, 20); downb = new Boundary(0, 480, 750, 20); gameball = new Ball(ball, upb.boundary, downb.boundary, Left.boundary, Right.boundary, font); timestart.Start(); timerstarted = true; gameball.keepinposition(); gamescreen = GameScreens.GameState.Play; gametimer.Start(); }
static bool deflectionDetected(Tuple <double, double, double, double, double> currState, Tuple <double, double, double, double, double> prevState, Player rP, Player lP, Ball b) { // right player deflects it if (prevState.Item1 < rP.PaddleX && currState.Item1 >= rP.PaddleX) { // Calculate Y coordinate when ball is at the same level as the paddle //double yIntersect = currState.Item4 * prevState.Item1 + prevState.Item2; double yIntersect = (b.VelocityY / b.VelocityX) * (-1 * b.VelocityX) + b.BallY; if (yIntersect <= rP.PaddleY + GlobalValues.PaddleHeight && yIntersect >= rP.PaddleY) { rP.addDeflection(); // HERE //rP.updateQ(b, rP.PrevAction, rP, lP, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor); return(true); } } if (lP != null) { // left player deflects it if (prevState.Item1 < lP.PaddleX && currState.Item1 >= lP.PaddleX) { // Calculate Y coordinate when ball is at the same level as the paddle //double yIntersect = currState.Item4 * prevState.Item1 + prevState.Item2; double yIntersect = (b.VelocityY / b.VelocityX) * (-1 * b.VelocityX) + b.BallY; if (yIntersect >= lP.PaddleY - 0.2 && yIntersect <= lP.PaddleY) { lP.addDeflection(); return(true); } } } return(false); }
static void Main(string[] args) { GlobalValues.DiscreteBoardX = 12; GlobalValues.DiscreteBoardY = 12; GlobalValues.InitialBallX = 0.5; GlobalValues.InitialBallY = 0.5; GlobalValues.InitialVelocityX = 0.03; GlobalValues.InitialVelocityY = 0.01; GlobalValues.PaddleHeight = 0.2; GlobalValues.RandomVelocityX = 0.015; GlobalValues.RandomVelocityY = 0.03; Random rand = new Random(); double boardX = 1.0; double boardY = 1.0; //double ball_x = 0.5; //double ball_y = 0.5; //double vel_x = 0.03; //double vel_y = 0.01; //double paddleHeight = 0.2; //double randomVelX = 0.015; //double randomVelY = 0.03; int totalTrials = 600000; double learningConstant = 30; //30 double discountFactor = .4; //.4 int explorationLimit = 300; //300 Ball initialBall = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false); Player rP = new Player(1, 0.5 - (GlobalValues.PaddleHeight / 2), learningConstant, discountFactor, Tuple.Create(initialBall.DiscreteBallX, initialBall.DiscreteBallY, initialBall.DiscreteVelocityX, initialBall.DiscreteVelocityY, (int)Math.Floor(GlobalValues.DiscreteBoardY * (0.5 - (GlobalValues.PaddleHeight / 2)) / (1 - GlobalValues.PaddleHeight))), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, explorationLimit); int maxDeflections = 0; int totalTrialLength = 0; DateTime start = DateTime.Now; for (int numTrial = 0; numTrial < totalTrials; numTrial++) { // initial state of the ball Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false); rP.PaddleY = 0.5 - (GlobalValues.PaddleHeight / 2); rP.DiscretePaddleY = rP.getDiscretePaddleY(); rP.PrevAction = "N/A"; //totalTrials = 300000; //learningConstant = 450000; //explorationLimit = 50000; var currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY); var prevStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); // Epsiode/Trial Loop int trialIterations = 0; rP.addGamesPlayed(); while (true) { trialIterations++; // Previous Discrete Values //int prevDiscreteBallX = b.DiscreteBallX; //int prevDiscreteBallY = b.DiscreteBallY; //int prevDiscretePaddleX = rP.DiscretePaddleX; //int prevDiscretePaddleY = rP.DiscretePaddleY; //int prevDiscreteVelX = b.DiscreteVelocityX; //int prevDiscreteVelY = b.DiscreteVelocityY; //var prevDiscreteState = Tuple.Create(prevDiscreteBallX, prevDiscreteBallY, prevDiscreteVelX, prevDiscreteVelY, prevDiscretePaddleX, prevDiscretePaddleY); prevStateTuple = currentStateTuple; b.MoveBall(); currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); if (goalState(currentStateTuple, rP, null)) { if (deflectionDetected(currentStateTuple, prevStateTuple, rP, null, b)) { if (rP.Deflections >= 9) { Console.WriteLine("HERE"); } b.BallX = 2 * rP.PaddleX - b.BallX; double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX); double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY); if (Math.Abs(randomXVel) > 0.015) { ; } if (Math.Abs(randomYVel) > .03) { ; } b.VelocityX = b.VelocityX * -1 + randomXVel; b.VelocityY = b.VelocityY + randomYVel; if (Math.Abs(b.VelocityX) < 0.03) { if (b.VelocityX < 0) { b.VelocityX = -0.03; //b.VelocityX = b.VelocityX * -1; } else { b.VelocityX = 0.03; } } // TODO: Put direction? if (Math.Abs(b.VelocityX) > 1) { if (b.VelocityX < 0) { b.VelocityX = -1; } else { b.VelocityX = 1; } } if (Math.Abs(b.VelocityY) > 1) { if (b.VelocityY < 0) { b.VelocityY = -1; } else { b.VelocityY = 1; } } } else { if (rP.Deflections >= 9) { Console.WriteLine("HERE"); } rP.addGamesLost(); //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward); break; } } // Draw Board DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial); // Right Player Makes Decision //rP.MoveRightPaddle(b); // Move Ball //b.MoveBall(); rP.MoveRightPaddle(b); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); rP.tdUpdate3(b, prevStateTuple, currentStateTuple); //// Current Discrete Values //int currDiscreteBallX = b.DiscreteBallX; //int currDiscreteBallY = b.DiscreteBallY; //int currDiscretePaddleX = rP.DiscretePaddleX; //int currDiscretePaddleY = rP.DiscretePaddleY; //int currDiscreteVelX = b.DiscreteVelocityX; //int currDiscreteVelY = b.DiscreteVelocityY; //var currDiscreteState = Tuple.Create(currDiscreteBallX, currDiscreteBallY, currDiscreteVelX, currDiscreteVelY, currDiscretePaddleX, currDiscretePaddleY); //// Check if there was a change, if so, update Q //if (prevDiscreteBallX != currDiscreteBallX || // prevDiscreteBallY != currDiscreteBallY || // prevDiscretePaddleX != currDiscretePaddleX || // prevDiscretePaddleY != currDiscretePaddleY || // prevDiscreteVelX != currDiscreteVelX || // prevDiscreteVelY != currDiscreteVelY) //{ // rP.tdUpdate2(b, prevDiscreteState, currDiscreteState); //} //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial); // Add new State //prevStateTuple = currentStateTuple; //currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); } if (rP.Deflections > maxDeflections) { maxDeflections = rP.Deflections; } totalTrialLength = totalTrialLength + trialIterations; rP.TotalTrialDeflections = rP.TotalTrialDeflections + rP.Deflections; Console.WriteLine("*********************************"); Console.WriteLine("Trial: " + numTrial); Console.WriteLine("Trial Length: " + trialIterations); Console.WriteLine("Number of deflections: " + rP.Deflections); Console.WriteLine("Avg Trial number of deflections: " + (double)rP.TotalTrialDeflections / rP.GamesPlayed); Console.WriteLine("Avg Trial length: " + (double)totalTrialLength / rP.GamesPlayed); if ((double)rP.TotalTrialDeflections / rP.GamesPlayed > 9) { Console.WriteLine("Agent may have found an optimal policy!"); } Console.WriteLine("Max number of deflections: " + maxDeflections); Console.WriteLine("*********************************"); rP.Deflections = 0; } DateTime end = DateTime.Now; Console.WriteLine("*************SUMMARY:*************"); Console.WriteLine("Training start: " + start); Console.WriteLine("Training end: " + end); Console.WriteLine("Training duration: " + (end - start)); do { Console.WriteLine("Press p to play, 1 player"); } while (Console.ReadKey().KeyChar != 'p'); int totalGames = 1000; //double learningConstant = 5; //double discountFactor = .9; maxDeflections = 0; Dictionary <int, int> gameDeflections = new Dictionary <int, int>(); rP.Deflections = 0; rP.ExplorationLimit = 1; DateTime startGame = DateTime.Now; for (int numGame = 0; numGame < totalGames; numGame++) { Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false); // initial state of the ball, make random velocity, ball in the middle, paddleY is in the middle Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX + rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX), rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false); rP.PaddleY = 0.5 - (GlobalValues.PaddleHeight / 2); rP.DiscretePaddleY = rP.getDiscretePaddleY(); rP.PrevAction = "N/A"; var currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY); var prevStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); // Epsiode/Trial Loop int gameIterations = 0; rP.addGamesPlayed(); while (true) { gameIterations++; prevStateTuple = currentStateTuple; b.MoveBall(); currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); if (goalState(currentStateTuple, rP, null)) { if (deflectionDetected(currentStateTuple, prevStateTuple, rP, null, b)) { b.BallX = 2 * rP.PaddleX - b.BallX; double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX); double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY); if (Math.Abs(randomXVel) > 0.015) { ; } if (Math.Abs(randomYVel) > .03) { ; } b.VelocityX = b.VelocityX * -1 + randomXVel; b.VelocityY = b.VelocityY + randomYVel; if (Math.Abs(b.VelocityX) < 0.03) { if (b.VelocityX < 0) { b.VelocityX = -0.03; //b.VelocityX = b.VelocityX * -1; } else { b.VelocityX = 0.03; } } // TODO: Put direction? if (Math.Abs(b.VelocityX) > 1) { if (b.VelocityX < 0) { b.VelocityX = -1; } else { b.VelocityX = 1; } } if (Math.Abs(b.VelocityY) > 1) { if (b.VelocityY < 0) { b.VelocityY = -1; } else { b.VelocityY = 1; } } } else { rP.addGamesLost(); //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward); break; } } // Draw Board DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numGame, gameIterations); rP.MoveRightPaddle(b); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); rP.tdUpdate3(b, prevStateTuple, currentStateTuple); //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial); // Add new State //prevStateTuple = currentStateTuple; //currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); } gameDeflections.Add(numGame, rP.Deflections); if (rP.Deflections > maxDeflections) { maxDeflections = rP.Deflections; } Console.WriteLine("*********************************"); Console.WriteLine("Game: " + numGame); Console.WriteLine("Game Length: " + gameIterations); Console.WriteLine("Number of deflections: " + rP.Deflections); Console.WriteLine("Max number of deflections: " + maxDeflections); double avgDeflections = (double)gameDeflections.Sum(v => v.Value) / (double)gameDeflections.Count; Console.WriteLine("Average number of deflections: " + avgDeflections.ToString()); Console.WriteLine("*********************************"); rP.Deflections = 0; } DateTime endGame = DateTime.Now; Console.WriteLine("*************SUMMARY:*************"); Console.WriteLine("Games start: " + startGame); Console.WriteLine("Games end: " + endGame); Console.WriteLine("Games duration: " + (endGame - startGame)); do { Console.WriteLine("Press p to play, 2 player"); } while (Console.ReadKey().KeyChar != 'p'); totalGames = 500; //double learningConstant = 5; //double discountFactor = .9; maxDeflections = 0; rP.GamesLost = 0; rP.GamesPlayed = 0; rP.Deflections = 0; rP.ExplorationLimit = 1; Player lP = new Player(1, 0.5 - (GlobalValues.PaddleHeight / 2), learningConstant, discountFactor, Tuple.Create(initialBall.DiscreteBallX, initialBall.DiscreteBallY, initialBall.DiscreteVelocityX, initialBall.DiscreteVelocityY, (int)Math.Floor(GlobalValues.DiscreteBoardY * (0.5 - (GlobalValues.PaddleHeight / 2)) / (1 - GlobalValues.PaddleHeight))), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, explorationLimit); DateTime start2PlayerGame = DateTime.Now; for (int numGame = 0; numGame < totalGames; numGame++) { Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false); // initial state of the ball, make random velocity, ball in the middle, paddleY is in the middle Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX + rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX), rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, true); rP.PaddleY = 0.5 - (GlobalValues.PaddleHeight / 2); rP.DiscretePaddleY = rP.getDiscretePaddleY(); rP.PrevAction = "N/A"; lP.PaddleY = 0.5 - (GlobalValues.PaddleHeight / 2); lP.DiscretePaddleY = lP.getDiscretePaddleY(); lP.PrevAction = "N/A"; var currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY); var prevStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); // Epsiode/Trial Loop int gameIterations = 0; rP.addGamesPlayed(); while (true) { gameIterations++; prevStateTuple = currentStateTuple; b.MoveBall(); currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); if (goalState(currentStateTuple, rP, lP)) { if (deflectionDetected(currentStateTuple, prevStateTuple, rP, lP, b)) { if (b.BallX < 0.5 * boardX) { b.BallX = 2 * lP.PaddleX - b.BallX; } else { b.BallX = 2 * rP.PaddleX - b.BallX; } double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX); double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY); if (Math.Abs(randomXVel) > 0.015) { ; } if (Math.Abs(randomYVel) > .03) { ; } b.VelocityX = b.VelocityX * -1 + randomXVel; b.VelocityY = b.VelocityY + randomYVel; if (Math.Abs(b.VelocityX) < 0.03) { if (b.VelocityX < 0) { b.VelocityX = -0.03; //b.VelocityX = b.VelocityX * -1; } else { b.VelocityX = 0.03; } } // TODO: Put direction? if (Math.Abs(b.VelocityX) > 1) { if (b.VelocityX < 0) { b.VelocityX = -1; } else { b.VelocityX = 1; } } if (Math.Abs(b.VelocityY) > 1) { if (b.VelocityY < 0) { b.VelocityY = -1; } else { b.VelocityY = 1; } } } else { // Who lost? if (currentStateTuple.Item1 >= rP.PaddleX) { rP.addGamesLost(); } if (currState.Item1 <= lP.PaddleX) { lP.addGamesLost(); } //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward); break; } } // Draw Board DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, lP, rP, b, numGame, gameIterations); rP.MoveRightPaddle(b); lP.MoveLeftPaddle(b); DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations); rP.tdUpdate3(b, prevStateTuple, currentStateTuple); } Console.WriteLine("*********************************"); Console.WriteLine("Game: " + numGame); Console.WriteLine("Game Length: " + gameIterations); Console.WriteLine("Number of deflections for right player: " + rP.Deflections); Console.WriteLine("Number of deflections for left player: " + (lP.Deflections)); Console.WriteLine("*********************************"); rP.Deflections = 0; } DateTime end2PlayerGame = DateTime.Now; Console.WriteLine("*************SUMMARY:*************"); Console.WriteLine("Games start: " + start2PlayerGame); Console.WriteLine("Games end: " + end2PlayerGame); Console.WriteLine("Games won by agent: " + (rP.GamesPlayed - rP.GamesLost)); Console.WriteLine("Winning Percentage of agent: " + (double)(rP.GamesPlayed - rP.GamesLost) / rP.GamesPlayed); Console.WriteLine("Games duration: " + (end2PlayerGame - start2PlayerGame)); do { Console.WriteLine("Press q to quit"); } while (Console.ReadKey().KeyChar != 'q'); }