使方法每次调用都会生成一个新数字?

时间:2019-02-27 05:00:40

标签: python python-3.x

目标:我正在尝试做到这一点,当调用self.damage时,它会生成一个介于1和参数“ damage”之间的随机数。但是,此随机数仅是第一次使用,然后在整个代码中使用。我当前的代码如下:

package com.dshgh.webview;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.firebase.analytics.FirebaseAnalytics;

import com.dshgh.webview.Fragments.WebViewFragment;


public class MainActivity extends AppCompatActivity  {

    private BroadcastReceiver mRegistrationBroadcastReceiver;
    boolean doubleBackToExitPressedOnce = false;
    private FirebaseAnalytics mFirebaseAnalytics;
    RelativeLayout rel_layout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //ButterKnife.bind(this);
        rel_layout = (RelativeLayout)findViewById(R.id.rel_layout);
        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        Bundle bundle = new Bundle();
        WebViewFragment webViewFragment = new WebViewFragment();
        bundle.putString("url", Config.homeUrl);
        webViewFragment.setArguments(bundle);
        loadFragment(webViewFragment, false, "webViewFragment");
        try {
            Intent intent = getIntent();
            String message = intent.getStringExtra("message");
            String url = intent.getStringExtra("url");
            Log.d("notification Data", message + url);
            if (url.length() > 0) {
                bundle.putString("url", url);
                webViewFragment.setArguments(bundle);
                loadFragment(webViewFragment, false, "webViewFragment");
            }
        }
        catch (Exception e) {
            Log.d("error notification data", e.toString());
        }
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        displayFirebaseRegId();
    }


    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e("FCM", "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId)) {
            //txtRegId.setText("Firebase Reg Id: " + regId);
        }
        else
            Log.d("Firebase", "Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {

        Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
        if(fragment != null && fragment instanceof WebViewFragment) {
            if(((WebViewFragment) fragment).onBackPressed()) {
                if (doubleBackToExitPressedOnce) {
                    super.onBackPressed();
                    return;
                }

                this.doubleBackToExitPressedOnce = true;
                // Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show();
                Snackbar snackbar = Snackbar
                        .make(rel_layout, "Press back once more to exit", Snackbar.LENGTH_LONG);
                snackbar.setActionTextColor(Color.RED);
                View snackbarView = snackbar.getView();
                snackbarView.setBackgroundColor(Color.DKGRAY);
                TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.YELLOW);
                snackbar.show();

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        doubleBackToExitPressedOnce = false;
                    }
                }, 2000);
            }
        }
    }

    public void loadFragment(Fragment fragment, Boolean bool) {
        loadFragment(fragment, bool, null);
    }

    public void loadFragment(Fragment fragment, Boolean bool, String TAG) {
        showAds();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(TAG == null) {
            transaction.replace(R.id.frameLayout, fragment);
        }else {
            transaction.replace(R.id.frameLayout, fragment, TAG);
        }
        if (bool)
            transaction.addToBackStack(null);
        transaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
        if(fragment != null && fragment instanceof WebViewFragment) {
            ((WebViewFragment)fragment).onActivityResult(requestCode, resultCode, intent);
        }
        super.onActivityResult(requestCode, resultCode, intent);

    }

    public void hideAds() {

    }

    public void showAds() {

    }
}

当我在while循环内说Spider.damage时,我希望它选择一个新的随机数,当前它仅使用第一个,而不选择任何新的随机数。 我不确定为什么会发生这种情况或如何解决,我能否在此找到任何线索? 这是我第一次使用类,所以我仍然对它们的工作原理还只是半途而废! 感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

仅在类random.randint(1, damage)的初始化器(在__init__中)调用损害。我建议您仅在初始化器中初始化max_damage,然后创建一个会产生损坏的新函数,例如:

import random

class PC(object): 
    def __init__(self, health, damage):
        self.health = health 
        self.max_damage = max_damage

    def get_damage():
         return random.randint(1, self.max_damage)

然后可以使用Spider.damage代替Spider.get_damage()来获取每次产生的损害。希望这是有道理的,祝您编程工作顺利!

答案 1 :(得分:0)

您已经用“ python-3.x”标记了这个问题,所以我想您正在使用3.x

您以两种不同的方式使用Spider.damage

  1. 您正在将其用作返回存储在damage属性中的当前值的表达式。
  2. 您还期望它充当函数调用,它将以某种方式调用random.randint()并将新的随机数重新分配给damage属性。

第一次使用可以。第二个不起作用。

我建议您编写一个名为set_damage()的方法,该方法将在内部调用 random.randint(),并更新damage属性。