使用unity依赖,C#编写的简单贪吃蛇游戏代码
时间: 2023-12-10 21:41:05 浏览: 65
以下是一个简单的贪吃蛇游戏代码:
```csharp
using UnityEngine;
using System.Collections.Generic;
public class SnakeGame : MonoBehaviour {
public GameObject snakePrefab;
public GameObject foodPrefab;
private List<GameObject> snake = new List<GameObject>();
private Vector2 direction = Vector2.right;
private GameObject food;
void Start () {
InvokeRepeating("Move", 0.3f, 0.3f);
GenerateFood();
}
void Update () {
if (Input.GetKey(KeyCode.RightArrow) && direction != -Vector2.right)
direction = Vector2.right;
else if (Input.GetKey(KeyCode.DownArrow) && direction != Vector2.up)
direction = -Vector2.up;
else if (Input.GetKey(KeyCode.LeftArrow) && direction != Vector2.right)
direction = -Vector2.right;
else if (Input.GetKey(KeyCode.UpArrow) && direction != -Vector2.up)
direction = Vector2.up;
}
void Move () {
Vector2 headPosition = snake[0].transform.position;
Vector2 newHeadPosition = headPosition + direction;
if (IsOutOfBounds(newHeadPosition))
GameOver();
else if (IsSnake(newHeadPosition))
GameOver();
else {
if (food.transform.position == newHeadPosition) {
GameObject bodySegment = Instantiate(snakePrefab, newHeadPosition, Quaternion.identity);
snake.Insert(0, bodySegment);
GenerateFood();
} else {
GameObject tail = snake[snake.Count-1];
snake.RemoveAt(snake.Count-1);
tail.transform.position = newHeadPosition;
snake.Insert(0, tail);
}
}
}
bool IsOutOfBounds (Vector2 position) {
return position.x < -10f || position.x > 10f || position.y < -5f || position.y > 5f;
}
bool IsSnake (Vector2 position) {
foreach (GameObject segment in snake)
if (segment.transform.position == position)
return true;
return false;
}
void GameOver () {
CancelInvoke();
Debug.Log("Game Over!");
}
void GenerateFood () {
Vector2 position = new Vector2(Random.Range(-10, 11), Random.Range(-5, 6));
while (IsSnake(position) || IsOutOfBounds(position))
position = new Vector2(Random.Range(-10, 11), Random.Range(-5, 6));
food = Instantiate(foodPrefab, position, Quaternion.identity);
}
}
```
这个代码使用了Unity中的`GameObject`、`Vector2`、`Random`等类。在`Start()`函数中,我们通过调用`InvokeRepeating()`函数来定时调用`Move()`函数,实现贪吃蛇的运动。在`Update()`函数中,我们监听用户的按键输入,并根据输入改变贪吃蛇的方向。在`Move()`函数中,我们首先计算出贪吃蛇头部下一步的位置`newHeadPosition`,然后判断是否越界或与自身重合,如果是则游戏结束;否则,如果下一步的位置与食物位置重合,则在贪吃蛇头部插入一个新的身体段,并生成一个新的食物;否则,将贪吃蛇尾部移动到下一步的位置,并将其插入到贪吃蛇头部。
在`IsOutOfBounds()`函数中,我们判断一个位置是否越界。在`IsSnake()`函数中,我们判断一个位置是否与贪吃蛇身体段重合。`GameOver()`函数用于游戏结束的逻辑。`GenerateFood()`函数用于生成新的食物。
阅读全文