import random def take_bean(b): #a为取豆子的个数,b为剩余豆子的个数 a=int(input("请输入取豆子的教量(一次只能取出1,2,3颗)\n") if 0<a<4: b-=a print(f'剩余{b}联豆子“) return b if b<=0: print("你输了,机器人赢了") else: print("请重新取出豆子") def computer(d): #d为剩余豆子的个业 a=random.randint(1,4) d=d-a print(f"机器人取出{a}顺豆子") if d<=0: print("机器人输了,你赢了") return d def main(): b=16 while b>0: b=take_bean(b) b=computer(b) if _name_=='_main_': main()代码分析
时间: 2024-04-28 22:26:18 浏览: 8
这是一个简单的豆子游戏,玩家和机器人轮流取1-3颗豆子,直到没有豆子可取为止。代码中的主要函数有take_bean和computer,分别表示玩家取豆子和机器人取豆子的过程。其中,take_bean函数中包含了判断玩家取豆子是否合法的逻辑,如果取的数量不在1-3之间,则需要重新取;如果剩余豆子为0,则机器人获胜。computer函数则通过随机数来模拟机器人取豆子的过程,同样需要判断剩余豆子数量是否为0。最后,在main函数中通过循环来进行游戏,直到有一方获胜为止。
相关问题
优化下以下代码:def irpoweron(ser_mcu, cmd_list='6E 51 00 2C 04 02 FD 14 EB ed 02', frame_id=0): cmd_switch = uart_tx_cmd(cmd_list, frame_id) datahex = bytes.fromhex(cmd_switch) star_sendcmd_flag = False # print(cmd_switch) time.sleep(0.1) try: ser_mcu.write(datahex) star_sendcmd_flag = True except: sys.exit(0) time_uart_start = time.perf_counter() while True: time_now = time.perf_counter() # print(time_now - time_uart_start) if time_now - time_uart_start > 0.1: # print('测试超时!') return -1 try: com_input = ser_mcu.read(8192) # 设置一次循环接收数据的个数 except: sys.exit(0) if com_input and star_sendcmd_flag == True: # 如果读取结果非空,则输出 rxdata = uartrx_pro(com_input, ser_mcu) # print('接收到指令:', rxdata) if rxdata[0] == 1: if rxdata[1] == int('0', 16) and int(rxdata[4], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') return 1 if rxdata[0] == 2: if rxdata[1] == int('0', 16) and int(rxdata[4], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') star_flag = True return 1 if rxdata[5] == int('0', 16) and int(rxdata[8], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') star_flag = True return 1
以下是对该代码的优化建议:
1. 使用参数注解来增加代码可读性;
2. 使用异常机制来处理串口通信时可能出现的异常;
3. 在 while 循环中添加 time.sleep() 来降低 CPU 占用率;
4. 使用 bytearray.fromhex() 代替 bytes.fromhex();
5. 将常量提取为变量,以提高代码可维护性;
6. 在代码中添加注释,以增加代码可读性。
下面是优化后的代码:
```python
import sys
import time
import serial
def irpoweron(ser_mcu: serial.Serial, cmd_list: str = '6E 51 00 2C 04 02 FD 14 EB ed 02', frame_id: int = 0) -> int:
# 将命令字符串转换为字节数组
cmd_switch = uart_tx_cmd(cmd_list, frame_id)
datahex = bytearray.fromhex(cmd_switch)
# 发送命令
star_sendcmd_flag = False
time_uart_start = time.perf_counter()
try:
ser_mcu.write(datahex)
star_sendcmd_flag = True
except Exception as e:
print(f"Exception: {e}")
sys.exit(0)
# 接收响应
while True:
time_now = time.perf_counter()
if time_now - time_uart_start > 0.1:
# 超时未收到响应
return -1
time.sleep(0.01) # 降低 CPU 占用率
try:
com_input = ser_mcu.read(8192)
except Exception as e:
print(f"Exception: {e}")
sys.exit(0)
if com_input and star_sendcmd_flag:
# 解析响应
rxdata = uartrx_pro(com_input, ser_mcu)
# print('接收到指令:', rxdata)
if rxdata[0] == 1:
if rxdata[1] == 0 and int(rxdata[4], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
return 1
elif rxdata[0] == 2:
if rxdata[1] == 0 and int(rxdata[4], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
star_flag = True
return 1
elif rxdata[5] == 0 and int(rxdata[8], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
star_flag = True
return 1
# 将常量提取为变量
CMD_LIST = '6E 51 00 2C 04 02 FD 14 EB ed 02'
FRAME_ID = 0
```
import numpy as np from scipy.optimize import linprog def integer_cutting_plane(c, A, b, bounds): relaxed_A = A relaxed_b = b while True: res = linprog(c=c, A_ub=relaxed_A, b_ub=relaxed_b, bounds=bounds) x = res.x if all(int(val) == val for val in x): return x.astype(int) new_constraint = (relaxed_A @ x <= relaxed_b) relaxed_A = np.vstack((relaxed_A, new_constraint)) def get_bounds(): return [(0, None), (0, None)] def get_c(): return np.array([40, 90]) def get_A(): return np.array([[-9, -7], [-7, -20]]) def get_b(): return np.array([-56, -70]) if __name__ == '__main__': bounds = get_bounds() integer_cutting_plane(get_c(), get_A(), get_b(), bounds)以上代码运行报错ValueError: Invalid input for linprog: b_ub must be a 1-D array; b_ub must not have more than one non-singleton dimension and the number of rows in A_ub must equal the number of values in b_ub 请解决
在你的代码中,报错是因为在调用linprog函数时,传递给参数b_ub的参数relaxed_b是一个二维数组。linprog函数要求b_ub是一个一维数组。
要解决这个问题,你可以使用numpy库的flatten()方法将relaxed_b转换为一维数组。flatten()方法会将多维数组展平为一维数组。
以下是修改后的代码:
```python
import numpy as np
from scipy.optimize import linprog
def integer_cutting_plane(c, A, b, bounds):
relaxed_A = A
relaxed_b = b
while True:
res = linprog(c=c, A_ub=relaxed_A, b_ub=relaxed_b.flatten(), bounds=bounds)
x = res.x
if all(int(val) == val for val in x):
return x.astype(int)
new_constraint = (relaxed_A @ x <= relaxed_b)
relaxed_A = np.vstack((relaxed_A, new_constraint))
def get_bounds():
return [(0, None), (0, None)]
def get_c():
return np.array([40, 90])
def get_A():
return np.array([[-9, -7], [-7, -20]])
def get_b():
return np.array([-56, -70])
if __name__ == '__main__':
bounds = get_bounds()
integer_cutting_plane(get_c(), get_A(), get_b(), bounds)
```
通过使用flatten()方法将relaxed_b转换为一维数组,你可以解决报错问题。请注意,这里使用的是numpy库的flatten()方法,而不是reshape()方法。