Python小游戏

1. 猜数字

代码1:
#!usr/bin/env python
# _*_ coding:utf-8 _*_
# @Author   : TianYu
# @Time     : 2017/9/18 19:39
# @File     : 草稿本.py
import random
s = int(random.uniform(1,10))#随机生成下一个实数,它在[a,b]范围内(左闭右开)
m = int(input("请输入整数:"))
while m != s:
    if m > s:
        print("数太大了")
        m = int(input("请输入整数:"))
    if m < s:
        print("数太小了")
        m = int(input("请输入整数:"))
    if m == s:
        print("你猜对了")
        break

代码2:
import random
import math
a=random.random() #生成一个(0~1)之间的随机数
b=math.floor(a*100+1)#floor,浮点数的地板,即求一个最接近它的整数,它的值小于或等于这个浮点数。
#print(b)
flag=True
while(flag):
    c = float(input("输出一个数:"))
    if b==c:
        print('你猜对了')
        flag=False
    elif b>c:
        print('数太小')
    else:
        print('数太大了')

2. 猜拳游戏

代码:
#!usr/bin/env python3
# _*_ coding:utf-8 _*_
# @Author   : TianYu
# @Time     : 2017/9/18 19:39
# @File     : 草稿本.py
import random
while 1:
    s = int(random.randint(1, 3))
    if s == 1:
        ind = "石头"
    elif s == 2:
        ind = "剪子"
    elif s == 3:
        ind = "布"
    m = input('输入 石头、剪子、布,输入"end"结束游戏:')
    blist = ['石头', "剪子", "布"]
    if (m not in blist) and (m != 'end'):
        print ("输入错误,请重新输入!")
    elif (m not in blist) and (m == 'end'):
        print ("\n游戏退出中...")
        break
    elif m == ind :
        print ("电脑出了: " + ind + ",平局!")
    elif (m == '石头' and ind =='剪子') or (m == '剪子' and ind =='布') or (m == '布' and ind =='石头'):
        print ("电脑出了: " + ind +",你赢了!")
    elif (m == '石头' and ind =='布') or (m == '剪子' and ind =='石头') or (m == '布' and ind =='剪子'):
        print ("电脑出了: " + ind +",你输了!")

摇骰子游戏

代码:
import random
import sys
import time

result = []
#程序一直运行,需手动结束
while True:
    result.append(int(random.uniform(1,7)))#模拟投骰子,随机生成1-6中的一个数
    result.append(int(random.uniform(1,7)))
    result.append(int(random.uniform(1,7)))
    print (result)
    count = 0
    index = 2
    pointStr = ""
    while index >= 0:
        currPoint = result[index]
        count += currPoint
        index -= 1
        pointStr += " "
        pointStr += str(currPoint)
    if count <= 11:
        sys.stdout.write(pointStr + " -> " + "小" + "\n")
        time.sleep( 1 )   # 睡眠一秒
    else:
        sys.stdout.write(pointStr + " -> " + "大" + "\n")
        time.sleep( 1 )   # 睡眠一秒
    result = []

十进制转换为二进制

代码:
import sys
denum = int(input("输入十进制数:"))
print("输入的十进制数为:\n",denum)
binnum = []#用来存放二进制位
# 二进制数
while denum > 0:
    binnum.append(str(denum % 2)) # 栈压入
    denum //= 2
print("转换为二进制为:")
while len(binnum)>0:
    sys.stdout.write( binnum.pop()) # 无空格输出二进制数

九九乘法表

代码1.
for a in range(1,10):
     for b in range(1,a+1):
         print("%d*%d=%2d" % (a,b,a*b),end=' ')
     print('')

代码2.
#输出样式多样
for a in range(10):
    s = ""
    for b in range(1,a+1):
        s += str(a)+ "*" + str(b) + "="+ str(a*b) + " "
    #print(s)
    print(s.center(69," "))# 居中
    #print(s.ljust(69," ")) # 左对齐
    # print(s.rjust(69," "))# 右对齐

要努力要奋斗

你可能感兴趣的:(Python小游戏)