python实现石头,剪刀,布(turtle库简易版)
三角形为剪刀,红色为石头,圆形为布(玩家点击)
右边为电脑
运行截图:
写的比较简易,包括鼠标的点击(主要想应付一下老师的作业,临时写的),很多都有点偏差,但是我做了控制台显示点击坐标,可以自行调整哈~
源码:
import random
import turtle
choices_index = [0, 1, 2]
choices = ["剪刀", "布", "石头"]
your_choices = 0
computer_choice = 0
# 提笔,移动🖊,放下
def move_pen(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
# 画图形
def draw_item(color: str, steps):
turtle.color(color)
turtle.begin_fill()
if steps:
turtle.circle(60, steps=steps)
else:
turtle.circle(60)
turtle.end_fill()
# 绘制ui
def draw_ui():
turtle.setup(700, 700)
turtle.penup()
move_pen(-250, 220)
# 绘制三角形
draw_item("yellow", 3)
# 画一个四边形
move_pen(-120, 220)
draw_item("red", 4)
# 画一个圆形
move_pen(20, 220)
draw_item("blue", 0)
# 绘制退出按钮
move_pen(270, 320)
turtle.pencolor("black")
turtle.write("退出游戏")
# 得出结果
def draw_answer(color1, steps1, color2, steps2):
# 您的选择
move_pen(-150, -100)
draw_item(color1, steps1)
# draw_item("blue", 0)
# 电脑选择
move_pen(150, -100)
draw_item(color2, steps2)
# draw_item("blue", 0)
# 点击事件
def click_fun(x, y):
global your_choices
global computer_choice
color = ""
step = 0
if computer_choice == 0:
color = "yellow"
step = 3
elif computer_choice == 1:
color = "red"
step = 4
elif computer_choice == 2:
color = "blue"
step = 0
print("x:%d,y:%d" % (x, y))
# 如果点击图案
if 219 < y < 311:
# 三角形
if -305 < x < -197:
draw_answer("yellow", 3, color, step)
your_choices = 0
game(computer_choice, your_choices)
# 四边形
elif -160 < x < -60:
draw_answer("red", 4, color, step)
your_choices = 1
game(computer_choice, your_choices)
# 圆形
elif -40 < x < 60:
draw_answer("blue", 0, color, step)
your_choices = 2
game(computer_choice, your_choices)
# 如果点击退出
if 265 < x < 320 and 313 < y < 340:
print("游戏结束!")
exit(0)
# 游戏判定函数 电脑选择,用户选择
def game(computer_index, your_index):
move_pen(-30, -50)
turtle.pensize(12)
turtle.pencolor("black")
print("您出的是%s,电脑出的是:%s" % (choices[your_index], choices[computer_index]))
if your_index == computer_index:
print("平局")
move_pen(-30, -60)
# 画圆
turtle.circle(10)
elif (computer_index + 1) % len(choices_index) == your_index:
print("你输了")
# 画叉
turtle.lt(-45)
turtle.fd(80)
move_pen(-30, -90)
turtle.lt(90)
turtle.fd(80)
elif (your_index + 1) % len(choices_index) == computer_index:
print("你赢了")
# 画对勾
turtle.lt(-40)
turtle.fd(30)
turtle.lt(90)
turtle.fd(80)
else:
print("Error!")
def main():
global computer_choice
global your_choices
draw_ui()
computer_choice = random.choice(choices_index)
# res = input("请输入选择:")
# your_index = choices.index(res)
main()
# draw_ui()
turtle.onscreenclick(click_fun)
turtle.done()