编程猫捉老鼠代码怎么用

时间:2025-01-24 11:02:04 游戏攻略

编程猫捉老鼠的代码可以使用多种编程语言实现,例如Python、JavaScript等。下面我将提供两个不同编程语言的简单示例代码。

Python 示例代码

```python

import random

class Animal:

def __init__(self, name):

self.name = name

def move(self):

pass

def catch_mouse(self, mouse):

pass

class Mouse(Animal):

def __init__(self, name):

super().__init__(name)

def move(self):

direction = random.choice(['up', 'down', 'left', 'right'])

if direction == 'up':

self.y -= 1

elif direction == 'down':

self.y += 1

elif direction == 'left':

self.x -= 1

elif direction == 'right':

self.x += 1

class Cat(Animal):

def __init__(self, name):

super().__init__(name)

def move(self):

direction = random.choice(['up', 'down', 'left', 'right'])

if direction == 'up':

self.y -= 1

elif direction == 'down':

self.y += 1

elif direction == 'left':

self.x -= 1

elif direction == 'right':

self.x += 1

def catch_mouse(self, mouse):

if self.x == mouse.x and self.y == mouse.y:

print(f"{self.name} caught {mouse.name}!")

mouse.name = None

else:

print(f"{self.name} missed {mouse.name}.")

创建猫和老鼠的实例

cat = Cat("Tom")

mouse = Mouse("Jerry")

运行游戏的主循环

while mouse.name:

cat.move()

mouse.move()

if cat.x == mouse.x and cat.y == mouse.y:

cat.catch_mouse(mouse)

break

```

JavaScript 示例代码