首页 > 解决方案 > 空气曲棍球多人游戏 - 我如何不断地从来自客户端应用程序的输入中移动图片框。

问题描述

我正在尝试通过来自客户端计算机的数据移动主机(简单服务器)屏幕上的图片框。这是一个简单的多人乒乓球游戏。每当按键被按下时,客户端都会发送数据。它主要发送图片框的 Y 轴位置,但是当我尝试更改图片框的位置时出现错误。我的客户端代码将 player1 pictureBox 的 Y 轴位置发送到服务器播放器..

private void keyisdown(object sender, KeyEventArgs e) {

    if (e.KeyCode == Keys.Up)
    {
        goup = true;


    String s = Convert.ToString(player.Location.Y);

    byte[] byteTime = Encoding.ASCII.GetBytes(s);

    ns.Write(byteTime, 0, byteTime.Length);
}
    if (e.KeyCode == Keys.Down)
    {
        godown = true;

    String s = Convert.ToString(player.Location.Y);

    byte[] byteTime = Encoding.ASCII.GetBytes(s);

    ns.Write(byteTime, 0, byteTime.Length);
}

}

我的服务器程序正在接收数据

public partial class Form1 : Form {

delegate void SetTextCallback(string text);

TcpListener listener;

TcpClient client;

NetworkStream ns;

 Thread t = null;


public Form1()
{
InitializeComponent();

listener = new TcpListener(IPAddress.Any, 4545);

listener.Start();

client = listener.AcceptTcpClient();

ns = client.GetStream();

t = new Thread(DoWork);

t.Start();
}

private void button1_Click(object sender, EventArgs e)
{
String s = textBox2.Text;

byte[] byteTime = Encoding.ASCII.GetBytes(s);

ns.Write(byteTime, 0, byteTime.Length);
}
public void DoWork()

{

byte[] bytes = new byte[1024];

while (true)

{

    int bytesRead = ns.Read(bytes, 0, bytes.Length);
    string data;
   this.SetText(Encoding.ASCII.GetString(bytes, 0, bytesRead));

   // data = (Encoding.ASCII.GetString(bytes, 0, bytesRead));

   // int Y = Convert.ToInt32(data);

   // pictureBox1.Location = new Point(769, Y);
    }

  }

  private void SetText(string text)

 {

  // InvokeRequired required compares the thread ID of the

  // calling thread to the thread ID of the creating thread.

  // If these threads are different, it returns true.

 if (this.pictureBox1.InvokeRequired)

  {

    SetTextCallback d = new SetTextCallback(SetText);

    this.Invoke(d, new object[] { text });


  }

  else

    {

    this.pictureBox1.Location = new Point(769, Convert.ToInt32( text));

  }

 }

 private void textBox1_TextChanged(object sender, EventArgs e)
 {

}



}

我正在接收客户端播放器图片框的 Y 位置,它接收到它,但不知何故它没有正确移动它只是在它获得 Y 位置时消失服务器 n 客户端程序的大小相同并且位置也相同,所以它应该像镜子一样移动

这是我想要制作的游戏,左边是 player1,右边是 player2

我还需要关于如何更新两个玩家的球位置以及如何正确实现多人游戏的帮助,现在我正在尝试慢慢更改简单的聊天客户端代码并获取我需要的数据。但是我如何才能每 20 或 50 毫秒获得一次持续的播放器更新,我很困惑。提前致谢。

标签: c#visual-studiowinformsnetwork-programming

解决方案


推荐阅读