尝试使用C#和MVC创建一个简单的Rock,Paper,Scissors游戏。目前,用户可以成功地将值输入textbox
。我使用以下代码行返回文本框中的结果:<h3>Your Guess:</h3> @Html.DisplayFor(m => m.UsersGuess)
我的问题是将随机值存储在ComputerGuess
模型属性中。我在Business类中创建了一个ComputerGuess()
方法,但不知道如何分配这个随机数。任何帮助,将不胜感激!
查看
@using RockPaperScissors.Business
@model RockPaperScissors.Models.Game
@{
ViewBag.Title = "Games";
}
<h2>Rock, Paper, Scissors</h2>
@using (Html.BeginForm("Index", "Game"))
{
<div class="form-group">
<label>Enter your decision:</label>
@Html.TextBoxFor(m => m.UsersGuess, new { @class = "form-control", required = "required" })
</div>
<div>
<input class="btn btn-primary" type="submit" value="Guess" />
</div>
}
<h3>Your Guess:</h3> @Html.DisplayFor(m => m.UsersGuess)
<h3>Computers Guess: </h3> @Html.DisplayFor(m => m.ComputersGuess)
控制器
using System.Web.Mvc;
using RockPaperScissors.Models;
namespace RockPaperScissors.Controllers
{
public class GameController : Controller
{
// GET: Game
public ActionResult Index(Game userInput)
{
return View(userInput);
}
}
}
模型
namespace RockPaperScissors.Models
{
public class Game
{
public string UsersGuess { get; set; }
public int ComputersGuess { get; set; }
}
}
业务层
using System;
using System.Collections.Generic;
using RockPaperScissors.Models;
namespace RockPaperScissors.Business
{
public class ComputerLogic
{
public int ComputersGuess()
{
List<string> options = new List<string> { "Rock", "Paper", "Scissors" };
var randomizer = new Random();
var random = randomizer.Next(options.Count);
var getRandomValue = new Game
{
ComputersGuess = random
};
return getRandomValue;
}
}
}