剪刀,石头,布用 中文标识,重新给个例子
时间: 2023-11-09 13:23:45 浏览: 33
好的,以下是使用中文标识的剪刀石头布游戏代码示例:
```python
import tensorflow as tf
import random
# 定义手势对应的数字
jiandao = 0
shitou = 1
bu = 2
# 定义手势名称,用于展示结果
gesture_names = ['剪刀', '石头', '布']
# 定义训练数据,手势对应的数字
training_data = [
[jiandao, jiandao],
[jiandao, shitou],
[jiandao, bu],
[shitou, jiandao],
[shitou, shitou],
[shitou, bu],
[bu, jiandao],
[bu, shitou],
[bu, bu]
]
# 定义训练目标,0 表示平局,1 表示胜利,-1 表示失败
target_data = [
0,
-1,
1,
1,
0,
-1,
-1,
1,
0
]
# 定义神经网络模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(16, input_shape=(2,), activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
# 编译模型,使用交叉熵作为损失函数,使用 Adam 优化器
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 将训练数据和目标数据转换为张量
training_data = tf.constant(training_data)
target_data = tf.constant(target_data)
# 将目标数据转换为 one-hot 编码
target_data = tf.one_hot(target_data + 1, depth=3)
# 训练模型
model.fit(training_data, target_data, epochs=1000)
# 循环进行游戏
while True:
# 让用户输入猜拳手势
user_gesture = input('请输入您的手势(0表示剪刀,1表示石头,2表示布):')
# 将用户输入转换为数字
user_gesture = int(user_gesture)
# 计算模型的预测结果
prediction = model.predict([[user_gesture, random.randint(0, 2)]])
# 获取预测结果中概率最大的手势
computer_gesture = tf.argmax(prediction, axis=1).numpy()[0]
# 打印出用户和计算机的手势
print('您出:', gesture_names[user_gesture])
print('计算机出:', gesture_names[computer_gesture])
# 判断胜负
if user_gesture == computer_gesture:
print('平局!')
elif (user_gesture == jiandao and computer_gesture == bu) or (user_gesture == shitou and computer_gesture == jiandao) or (user_gesture == bu and computer_gesture == shitou):
print('恭喜您,您赢了!')
else:
print('很遗憾,您输了!')
```
这个程序与之前的示例非常类似,唯一的区别在于使用中文标识手势名称。程序的执行流程与之前的示例相同。