我在做这组代码时被卡住了,我试图为我的手机游戏做一个random.Next(),一切都很好,但我面临着这个逻辑错误。
我的游戏有两个箭头左和右,游戏开始与一个随机的图片(这要么是左或右),如果箭头left<<出现我必须按btnLeft以获得1分,如果箭头right>>出现我将不得不按btnRight的点,因为我的random.Next(0,2) 0是btnLeft和1是btnRight。问题是当第一张图片是随机生成的,假设是左箭头,当我按下btn时,我已经按下了下一个随机箭头,这意味着屏幕可能会显示左箭头,但它已经生成了下一个随机数,但是屏幕仍然显示左箭头,当我按btnLeft时,我没有获得分数,箭头变成了right>>,这意味着我刚刚失去了一个点,我该如何解决这个问题呢?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
namespace madAssignment
{
public partial class gamePlay : PhoneApplicationPage
{
int counter = 1000000;
DispatcherTimer timer;
int count = 0;
public gamePlay()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.1);
timer.Tick += timer_Tick;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
void timer_Tick(object sender, EventArgs e)
{
//int num;
counter -= 1;
txtCount.Text = counter.ToString();
if(Convert.ToInt32(txtCount.Text) == 0)
{
timer.Stop();
Uri uri = new Uri("/gameEnd.xaml", UriKind.Relative);
this.NavigationService.Navigate(uri);
}
}
int rand()
{
Random r = new Random();
int p = 1;
if(p == 0)
{
imgLeft.Visibility = Visibility.Visible;
imgRight.Visibility = Visibility.Collapsed;
}
else
{
imgLeft.Visibility = Visibility.Collapsed;
imgRight.Visibility = Visibility.Visible;
}
int i = r.Next(0, 2);
return i;
}
private void btnTimerStart_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
imgLeft.Visibility = Visibility.Collapsed;
imgRight.Visibility = Visibility.Collapsed;
timer.Start();
rand();
}
private void btnLeft_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (rand() == 0)
{
count += 1;
txtScore.Text = count.ToString();
}
else
{
count -= 1;
txtScore.Text = count.ToString();
}
}
private void btnRight_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if(rand() == 1)
{
count += 1;
txtScore.Text = count.ToString();
}
else
{
count -= 1;
txtScore.Text = count.ToString();
}
}
}}
发布于 2014-07-22 20:58:25
您面临的问题是,您在点击按钮后会生成一个随机数。
您要做的实际上是生成轮次的随机数,将其存储在一个实例属性中,处理输入,然后才能生成和更新按钮的可见性。
另外,在rand()方法中,您显式地将p变量设置为1,因此这将始终导致左侧按钮不显示,右侧按钮可见。我猜这不是你想要的可见性。
如果您需要更多帮助,请在此答案上发表评论。
如果这解决了您的问题,请将其标记为接受的答案。
https://stackoverflow.com/questions/24884559
复制相似问题