跳跃游戏 Jump Game 分析与整理

参考文章 点这儿查看
给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以向后跳跃的最大长度。

问题一

判断你能不能到达数组的最后一个位置。
思路:从数组的第一个位置开始,往后一格一格遍历数组,当所遍历的位置还没超出可reach范围时,根据跳力更新可reach范围,可遍历的范围必须小于等于reach值。若可reach范围可覆盖数组最后一个位置,则可到达;若不可覆盖则不可到达。

class Solution1{
    public boolean jumpGame(int[] num){
        int N=num.length,reach=0;
        for(int i=0;i<=reach;i++){
            if(reach<i+num[i]) reach=i+num[i];
            if(reach>=N-1) return true;
        }
        return false;
    }
}

问题二

若可以到达数组最后一个位置,求出所用最小步数;若不可到达,返回-1。
思路:参照问题一,只不过在遍历时要更加细化一些,在遍历完x步可到的位置后,和遍历x+1步可到的位置前时,更新步数参数step为x+1。

class Solution2{
      public int jumpGame(int[] num){
        int N=num.length,i = 0,reach=0,step=0,nextReach=0;
        if(N=1) 
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C#跳跃游戏的源代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float jumpForce = 10f; public float moveSpeed = 5f; public Transform groundCheck; public LayerMask groundLayer; public GameObject gameOverPanel; private Rigidbody2D rb; private Animator anim; private bool isJumping = false; private bool isGrounded = false; void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); } void Update() { if (Input.GetKeyDown(KeyCode.Space) && isGrounded) { isJumping = true; rb.velocity = Vector2.up * jumpForce; } anim.SetBool("isJumping", isJumping); anim.SetFloat("yVelocity", rb.velocity.y); float horizontalInput = Input.GetAxisRaw("Horizontal"); rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y); if (rb.velocity.x > 0) { transform.localScale = new Vector3(1, 1, 1); } else if (rb.velocity.x < 0) { transform.localScale = new Vector3(-1, 1, 1); } isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer); if (!isGrounded) { gameOverPanel.SetActive(true); Time.timeScale = 0f; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Coin")) { Destroy(collision.gameObject); } } } 在此代码中,我们定义了玩家控制器的变量和属性。我们还定义了开始和更新函数,以便在游戏中实现跳跃和移动。我们还在代码中添加了碰撞检测和游戏结束的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值