日期:2014-05-20  浏览次数:20743 次

<原创>最简易的纯代码坦克大战
效果图

不到350行
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication87
{
  /// <summary>
  /// Made by wartim 2009.10.12
  /// var 1.0.0.0
  /// </summary>
  public partial class Form1 : Form
  {
  static int HEIGHT = 300;
  static int WIDTH = 300;

  Bitmap OrgBmp = new Bitmap(WIDTH, HEIGHT);
  List<Tank> Tanks = new List<Tank>();
  UserTank UTank = null;
  List<Bullet> Bullets = new List<Bullet>();
  PictureBox PB = new PictureBox();

  public Form1()
  {
  InitializeComponent();

  this.Size = new Size(WIDTH, HEIGHT);
  this.FormBorderStyle = FormBorderStyle.FixedDialog;
  this.KeyPreview = true;
  this.KeyDown += new KeyEventHandler(Form1_KeyDown);

  using (Graphics G = Graphics.FromImage(OrgBmp))
  G.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);

  PB.Parent = this;
  PB.Dock = DockStyle.Fill;
  PB.Image = OrgBmp;

  for (int i = 0; i < 5; i++)
  {
  Tanks.Add(new Tank(Color.Blue, this.BackColor));
  Thread.Sleep(100);
  }

  UTank = new UserTank(Color.Red, this.BackColor);

  Thread T = new Thread(new ThreadStart(RunThread));
  T.IsBackground = true;
  T.Start();
  }

  void Form1_KeyDown(object sender, KeyEventArgs e)
  {
  switch (e.KeyCode)
  {
  case Keys.Up: UTank.ChangeDirection(Direction.UP); UTank.Move(); break;
  case Keys.Down: UTank.ChangeDirection(Direction.DOWN); UTank.Move(); break;
  case Keys.Left: UTank.ChangeDirection(Direction.LEFT); UTank.Move(); break;
  case Keys.Right: UTank.ChangeDirection(Direction.RIGHT); UTank.Move(); break;
  case Keys.Space: Bullets.Add(new Bullet(Color.Black, UTank)); break; // 发射子弹
  }
  }

  void RunThread()
  {
  try
  {
  int Start = Environment.TickCount;
  Random R = new Random();
  int KillCount = 0, DeathCount = 0;

  while (true)
  if (Environment.TickCount - Start > 100)
  {
  Bitmap CacheBmp = new Bitmap(OrgBmp);

  for (int i = 0; i < Tanks.Count; i++)
  {
  Tanks[i].Move();
  Tanks[i].Draw(ref CacheBmp);
  if (R.Next(10) == 0) // 电脑发子弹是10分之一的可能
  Bullets.Add(new Bullet(Color.Red, Tanks[i]));
  }
  UTank.Draw(ref CacheBmp);
  List<Bullet> TempBullets = new List<Bullet>();
  for (int i = 0; i < Bullets.Count; i++)
  {
  if (Bullets[i].ObjStep != -1)