小学生python游戏编程_适合刚入门Python小白的趣味游戏编程

数字炸弹
相信大家在聚餐时都玩过猜数字游戏,游戏是由某人随机出一个指定范围内的数,然后其他人一个一个猜,猜的过程中区间不断缩小,直到猜中为止。
这里的猜数字游戏就是用程序代替出数字的人,程序算法步骤为:1.输入数字区间→2.系统产生区间内的随机数→3.玩家输入自己猜的数字→4.比较玩家猜的与答案的高低并提示→5.未猜中则回到第3步,猜中则提示猜次数。
import random
bot = int(input('设置一个最低数\n'))
top = int(input('设置一个最高数\n'))
rand = random.randint(bot, top)
print('Random number in [' + str(bot) + ',' + str(top) + '] generated!')
num = int(input('###请说一个数###\n'))
cnt = 1
while (num != rand):
if (num < rand):
print('*_* 比正确答案低')
else:
print('T_T 比正确答案高')
num = int(input('###Guess the number###\n'))
cnt = cnt + 1
print('^_^ 您猜中答案用了 [%d] 次' % cnt)小学生python游戏编程_适合刚入门Python小白的趣味游戏编程
文章图片
效果展示
关不掉的窗口
这个小窗口的呈现效果很简单,一句话,两个按钮,我们要做一个鼠标移到按钮上就会变成肯定答案的效果,外加一个点击第一个窗口关闭按钮弹出第二个窗口的效果。这里我们就只做两个窗口即可退出的效果。
第一步先导入tkinter库;第二步设置初始窗口展示界面相关组件参数,以及两个按钮的绑定事件;第三步编写两个按钮的鼠标移入切换按钮文字事件函数;第四步触发窗口事件。
from tkinter import *
class YouLikeMe:
def __init__(self):
window = Tk()
label = Label(window, text='你是不是喜欢我?')
self.btyes = Button(window, text='不是', height=1, width=6)
self.btno = Button(window, text='是的', height=1, width=6)
label.place(x=60, y=70)
self.btyes.place(x=40, y=130)
self.btno.place(x=120, y=130)
self.btyes.bind('', self.event1) # 将按钮与鼠标事件绑定,是指鼠标光标进入按钮区域
self.btno.bind('', self.event2)
window.mainloop()
def event1(self, event): # 切换按钮文字
self.btyes['text'] = '是的'
self.btno['text'] = '不是'
def event2(self, event):
self.btyes['text'] = '不是'
self.btno['text'] = '是的'
YouLikeMe()
window = Tk()
label = Label(window, text='关闭窗口也改变不了你喜欢我的事实')
label.place(x=2, y=130)
button = Button(window, text='确定', command=window.destroy)
button.place(x=80, y=150)
window.mainloop()小学生python游戏编程_适合刚入门Python小白的趣味游戏编程
文章图片
效果展示
猜拳小游戏
实现这个程序的代码也很简单,首先我们先调用random函数生成随机数,然后用户输入数字0-2,输出与之相对应的石头剪刀布。
import random #导入随机模块
num = 1
yin_num = 0
shu_num = 0
while num <= 3:
if shu_num == 2 or yin_num == 2:
break
user = int(input('请出拳 0(石头) 1(剪刀) 2(布)'))
if user > 2:
print('不能出大于2的值')
else:
data = https://www.it610.com/article/['石头', '剪刀', '布']
com = random.randint(0, 2)
print("您出的是{},电脑出的是{}".format(data[user], data[com]))
if user == com:
print('平局')
continue
elif (user == 0 and com == 1) or (user == 1 and com == 2) or (user == 2 and com == 0):
print('你赢了')
yin_num += 1
else:
print('你输了')
shu_num += 1
【小学生python游戏编程_适合刚入门Python小白的趣味游戏编程】 num += 1小学生python游戏编程_适合刚入门Python小白的趣味游戏编程
文章图片
效果展示

    推荐阅读