百度
360搜索
搜狗搜索

python游戏源码,python 编写一个彩票游戏?详细介绍

本文目录一览: python 编写一个彩票游戏?

完整的Python代码如下:
Python代码
from random import sampleresult = sample('0123456789', k=5)print (result)bonus = {0: 0, 1: 1000, 2: 2000, 3: 3000, 4: 4000, 5: 10000}data = input('输入号:')num = 0if list(data) == result:num = 5else:num = len(set(result) & set(data))print('本期开奖号码为:{0}'.format(result))print("你购买的彩票号:{0} 奖金:{1}元".format(data, bonus[num]))
输出:
输入号:12345
本期开奖号码为:['2', '7', '4', '5', '6']
你购买的彩票号:12345 奖金:3000元
在python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后在缩进块中编写函数体,函数的返回值用return语句返回
def 函数名([参数1,参数2,...,参数n]):
函数体
函数代码以def关键词开头,后接函数标识符名称和圆括号():
任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数
函数的第一行语句可以选择性的使用文档字符串-用于存放函数说明
函数内容以冒号起始,并且缩进
return[表达式]结束函数,选择性的返回一个值给调用方,不带表达式的return相当于返回None
按照题目要求编写的Python程序如下
import random
numlist=random.sample(range(0,10),5)
while numlist[0]==0:
numlist=random.sample(range(0,10),5)
num=int(''.join([str(i) for i in numlist]))
inputnum=int(input("输入号:"))
bonus=0
count=0
if inputnum==num:
bonus=10000
else:
for i in set(str(inputnum)):
if int(i) in numlist:
count+=1
bonus=1000*count
print("彩票号:%d" % num)
print("奖金:%d元" % bonus)
源代码(注意源代码的缩进)

python小游戏2048,上班摸鱼必备(附源码)

话不多说,直接上菜

为了方便大家copy,我就不分段解释了

import turtle, random

# 定义一个类,用来画除了数字方块之外的图形

class BackGround(turtle.Turtle):

? ? def __init__(self):

? ? ? ? super().__init__()

? ? ? ? self.penup()

? ? ? ? self.ht()

? ? def draw_block(self):

? ? ? ? self.shape('bg.gif')? # 画出背景方块

? ? ? ? for i in allpos:

? ? ? ? ? ? self.goto(i)

? ? ? ? ? ? self.stamp()

? ? ? ? self.color('white', 'white')? # 画出其他背景

? ? ? ? self.goto(-215, 120)

? ? ? ? self.begin_fill()

? ? ? ? self.goto(215, 120)

? ? ? ? self.goto(215, 110)

? ? ? ? self.goto(-215, 110)

? ? ? ? self.end_fill()

? ? ? ? self.shape('title.gif')

? ? ? ? self.goto(-125, 210)

? ? ? ? self.stamp()

? ? ? ? self.shape('score.gif')

? ? ? ? self.goto(125, 245)

? ? ? ? self.stamp()

? ? ? ? self.shape('top_score.gif')

? ? ? ? self.goto(125, 170)

? ? ? ? self.stamp()

? ? # 游戏失败及达成2048的提示文字

? ? def judge(self):

? ? ? ? global flag_win, flag_win_lose_text

? ? ? ? self.color('blue')

? ? ? ? judge = 0? # 判断是否还有位置可以移动

? ? ? ? for i in block_dic.values():

? ? ? ? ? ? for j in block_dic.values():

? ? ? ? ? ? ? ? if i.num == 0 or i.num == j.num and i.distance(j) == 100:

? ? ? ? ? ? ? ? ? ? judge += 1

? ? ? ? if judge == 0:? # 无位置可移动,游戏失败

? ? ? ? ? ? self.write('? ? GAME OVER\n重新开始请按空格键', align='center', font=('黑体', 30, 'bold'))

? ? ? ? ? ? flag_win_lose_text = False

? ? ? ? if flag_win is True:? # 此条件让2048达成的判断只能进行一次

? ? ? ? ? ? for k in block_dic.values():

? ? ? ? ? ? ? ? if k.num == 2048:? # 游戏达成

? ? ? ? ? ? ? ? ? ? flag_win = False

? ? ? ? ? ? ? ? ? ? self.write('? ? 达成2048\n继续游戏请按回车键', align='center', font=('黑体', 30, 'bold'))

? ? ? ? ? ? ? ? ? ? flag_win_lose_text = False

? ? def win_lose_clear(self):

? ? ? ? global flag_win_lose_text

? ? ? ? self.clear()

? ? ? ? flag_win_lose_text = True

? ? def show_score(self):? # 分值的显示

? ? ? ? global score, top_score

? ? ? ? if score > top_score:

? ? ? ? ? ? top_score = score

? ? ? ? ? ? with open('.\\score.txt', 'w') as f:

? ? ? ? ? ? ? ? f.write(f'{top_score}')

? ? ? ? self.color('white')

? ? ? ? self.goto(125, 210)

? ? ? ? self.clear()

? ? ? ? self.write(f'{score}', align='center', font=('Arial', 20, 'bold'))

? ? ? ? self.goto(125, 135)

? ? ? ? self.write(f'{top_score}', align='center', font=('Arial', 20, 'bold'))

# 数字方块类

class Block(turtle.Turtle):

? ? def __init__(self):

? ? ? ? super().__init__()

? ? ? ? self.ht()

? ? ? ? self.penup()

? ? ? ? self.num = 0

? ? def draw(self):

? ? ? ? self.clear()

? ? ? ? dic_draw = {2: '#eee6db', 4: '#efe0cd', 8: '#f5af7b',

? ? ? ? ? ? ? ? ? ? 16: '#fb9660', 32: '#f57d5a', 64: '#f95c3d',

? ? ? ? ? ? ? ? ? ? 128: '#eccc75', 256: '#eece61', 512: '#efc853',

? ? ? ? ? ? ? ? ? ? 1024: '#ebc53c', 2048: '#eec430', 4096: '#aeb879',

? ? ? ? ? ? ? ? ? ? 8192: '#aab767', 16384: '#a6b74f'}

? ? ? ? if self.num > 0:? # 数字大于0,画出方块

? ? ? ? ? ? self.color(f'{dic_draw[self.num]}')? # 选择颜色

? ? ? ? ? ? self.begin_fill()

? ? ? ? ? ? self.goto(self.xcor()+48, self.ycor()+48)

? ? ? ? ? ? self.goto(self.xcor()-96, self.ycor())

? ? ? ? ? ? self.goto(self.xcor(), self.ycor()-96)

? ? ? ? ? ? self.goto(self.xcor()+96, self.ycor())

? ? ? ? ? ? self.goto(self.xcor(), self.ycor()+96)

? ? ? ? ? ? self.end_fill()

? ? ? ? ? ? self.goto(self.xcor()-48, self.ycor()-68)

? ? ? ? ? ? if self.num > 4:? # 按照数字选择数字的颜色

? ? ? ? ? ? ? ? self.color('white')

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? self.color('#6d6058')

? ? ? ? ? ? self.write(f'{self.num}', align='center', font=('Arial', 27, 'bold'))

? ? ? ? ? ? self.goto(self.xcor(), self.ycor()+20)

class Game():

? ? def init(self):

? ? ? ? back = BackGround()? # 实例画出游戏的背景

? ? ? ? back.draw_block()

? ? ? ? for i in allpos:? # 画出16个海龟对应16个数字块

? ? ? ? ? ? block = Block()

? ? ? ? ? ? block.goto(i)

? ? ? ? ? ? block_dic[i] = block

? ? ? ? game.grow()

? ? def restart(self):? # 重开游戏的方法

? ? ? ? global score, flag_win_lose_text

? ? ? ? score = 0

? ? ? ? for i in block_dic.values():

? ? ? ? ? ? i.num = 0

? ? ? ? ? ? i.clear()

? ? ? ? win_lose_text.clear()

? ? ? ? game.grow()

? ? ? ? flag_win_lose_text = True? # 此flag为游戏达成或失败出现提示语后的判断,要提示语被clear后才能继续move

? ? def grow(self):? # 随机出现一个2或4的数字块

? ? ? ? block_list = []

? ? ? ? for i in allpos:

? ? ? ? ? ? if block_dic[i].num == 0:

? ? ? ? ? ? ? ? block_list.append(block_dic[i])? # 挑出空白方块的海龟

? ? ? ? turtle_choice = random.choice(block_list)? # 随机选中其中一个海龟

? ? ? ? turtle_choice.num = random.choice([2, 2, 2, 2, 4])? # 赋属性num=2/4

? ? ? ? turtle_choice.draw()

? ? ? ? win_lose_text.judge()

? ? ? ? show_score_text.show_score()

? ? ? ? ms.update()

? ? def move_up(self):

? ? ? ? allpos1 = allpos[::4]? # 切片为四列

? ? ? ? allpos2 = allpos[1::4]

? ? ? ? allpos3 = allpos[2::4]

? ? ? ? allpos4 = allpos[3::4]

? ? ? ? self.move_move(allpos1, allpos2, allpos3, allpos4)

? ? def move_down(self):

? ? ? ? allpos1 = allpos[-4::-4]

? ? ? ? allpos2 = allpos[-3::-4]

? ? ? ? allpos3 = allpos[-2::-4]

? ? ? ? allpos4 = allpos[-1::-4]

? ? ? ? self.move_move(allpos1, allpos2, allpos3, allpos4)

? ? def move_left(self):

? ? ? ? allpos1 = allpos[:4]

? ? ? ? allpos2 = allpos[4:8]

? ? ? ? allpos3 = allpos[8:12]

? ? ? ? allpos4 = allpos[12:16]

? ? ? ? self.move_move(allpos1, allpos2, allpos3, allpos4)

? ? def move_right(self):

? ? ? ? allpos1 = allpos[-1:-5:-1]

? ? ? ? allpos2 = allpos[-5:-9:-1]

? ? ? ? allpos3 = allpos[-9:-13:-1]

? ? ? ? allpos4 = allpos[-13:-17:-1]

? ? ? ? self.move_move(allpos1, allpos2, allpos3, allpos4)

? ? def move_move(self, allpos1, allpos2, allpos3, allpos4):

? ? ? ? if flag_win_lose_text is True:

? ? ? ? ? ? count1 = self.move(allpos1)? # 四列或四行依次移动

? ? ? ? ? ? count2 = self.move(allpos2)

? ? ? ? ? ? count3 = self.move(allpos3)

? ? ? ? ? ? count4 = self.move(allpos4)

? ? ? ? ? ? if count1 or count2 or count3 or count4:? # 判断是否有方块移动,有才能继续出现新的数字块

? ? ? ? ? ? ? ? self.grow()

? ? def move(self, pos_list):

? ? ? ? num_list = []? # 为某一列或行的数字块海龟的坐标

? ? ? ? for i in pos_list:

? ? ? ? ? ? num_list.append(block_dic[i].num)? #? 把这些海龟的NUM形成list

? ? ? ? new_num_list, count = self.list_oper(num_list)? #? 只是list_oper的方法形成新的list

? ? ? ? for j in range(len(new_num_list)):? # 把新的list依次赋值给对应的海龟.num属性并调用draw()方法

阅读更多 >>>  现在最好的编程语言,最受欢迎的计算机编程语言是哪种?

? ? ? ? ? ? block_dic[pos_list[j]].num = new_num_list[j]

? ? ? ? ? ? block_dic[pos_list[j]].draw()

? ? ? ? return count

? ? def list_oper(self, num_list):? # num_list的操作,假设其为【2,0,2,2】

? ? ? ? global score

? ? ? ? count = True

? ? ? ? temp = []

? ? ? ? new_temp = []

? ? ? ? for j in num_list:

? ? ? ? ? ? if j != 0:

? ? ? ? ? ? ? ? temp.append(j)? # temp=[2,2,2]

? ? ? ? flag = True

? ? ? ? for k in range(len(temp)):

? ? ? ? ? ? if flag:

? ? ? ? ? ? ? ? if k < len(temp)-1 and temp[k] == temp[k+1]:

? ? ? ? ? ? ? ? ? ? new_temp.append(temp[k]*2)

? ? ? ? ? ? ? ? ? ? flag = False

? ? ? ? ? ? ? ? ? ? score += temp[k]

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? new_temp.append(temp[k])? # new_temp=[4,2]

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? flag = True

? ? ? ? for m in range(len(num_list)-len(new_temp)):

? ? ? ? ? ? new_temp.append(0)? # new_temp=[4,2,0,0]

? ? ? ? if new_temp == num_list:

? ? ? ? ? ? count = False? # 此变量判断num_list没有变化,数字块无移动

? ? ? ? return(new_temp, count)

if __name__ == '__main__':

? ? ms = turtle.Screen()? # 主窗口的设置

? ? ms.setup(430, 630, 400, 50)

? ? ms.bgcolor('gray')

? ? ms.title('2048')

? ? ms.tracer(0)

? ? ms.register_shape('bg.gif')

? ? ms.register_shape('title.gif')

? ? ms.register_shape('score.gif')

? ? ms.register_shape('top_score.gif')

? ? block_dic = {}? # 放数字方块海龟的字典,位置坐标为key,对应海龟为value

? ? allpos = [(-150, 50), (-50, 50), (50, 50), (150, 50),

? ? ? ? ? ? ? (-150, -50), (-50, -50), (50, -50), (150, -50),

? ? ? ? ? ? ? (-150, -150), (-50, -150), (50, -150), (150, -150),

? ? ? ? ? ? ? (-150, -250), (-50, -250), (50, -250), (150, -250)]

? ? flag_win = True? # 达成2048的判断,让达成的文字仅出现一次

? ? flag_win_lose_text = True? # 用来判断失败或成功的提示文字是否有被清除,不清除不能继续移动方块

? ? score = 0

? ? with open('.\\score.txt', 'r') as f:

? ? ? ? top_score = int(f.read())? #? 读取score中的数据

? ? show_score_text = BackGround()

? ? win_lose_text = BackGround()

? ? game = Game()

? ? game.init()

? ? ms.listen()

? ? ms.onkey(game.move_up, 'Up')

? ? ms.onkey(game.move_down, 'Down')

? ? ms.onkey(game.move_left, 'Left')

? ? ms.onkey(game.move_right, 'Right')

? ? ms.onkey(win_lose_text.win_lose_clear, 'Return')

? ? ms.onkey(game.restart, 'space')

? ? ms.mainloop()

这是游戏界面:

欢迎挑战最高分。

要运行出来,必须本地要有这些文件:bg.gif,score.gif,title.gif,top_score.gif,score.txt

我把这些文件放在了群里,还有一些学习的资料,群号642109462,欢迎对python感兴趣的进群讨论。

支持作者的,可以关注和点赞。感谢你们!

Python游戏开发,Python实现贪吃蛇小游戏与吃豆豆 附带源码

Python版本: 3.6.4
相关模块:
pygame模块;
以及一些Python自带的模块。
安装Python并添加到环境变量,pip安装需要的相关模块即可。
贪吃蛇的 游戏 规则应该不需要我多做介绍了吧T_T。写个贪吃蛇 游戏 其实还是很简单的。首先,我们进行一下 游戏 初始化:
然后定义一个贪吃蛇类:
其中head_coord用来记录蛇头所在位置,而tail_coords是一个二维数组,用来记录所有蛇身的位置。一开始,贪吃蛇长为3,并且位置是随机生成的。用户通过 键来控制贪吃蛇的行动:
需要注意的是,贪吃蛇不能180 大拐弯,只能90 地拐弯。例如正在向左行动的贪吃蛇不能瞬间变成向右行动。具体而言,代码实现如下:
然后,我们需要随机生成一个食物,且需要保证该食物的位置不与贪吃蛇的位置相同:
在更新贪吃蛇的时候,如果它吃到了食物,则蛇身长加一,否则只是简单的按照给定的方向行动而不改变蛇身长度:
同时,当贪吃蛇吃到食物时,需要重新生成一个新的食物:
最后,当贪吃蛇碰到墙壁或者蛇头碰到蛇身时, 游戏 结束:
并显示一下 游戏 结束界面:
玩家通过 键控制 游戏 的主角吃豆人吃掉藏在迷宫内的所有豆子,并且不能被鬼魂抓到。
若能顺利吃完迷宫内的所有豆子并且不被鬼魂抓到,则 游戏 胜利,否则 游戏 失败。
逐步实现:
Step1:定义 游戏 精灵类
首先,让我们先来明确一下该 游戏 需要哪些 游戏 精灵类。
① 墙类
② 食物类(即豆豆)
③ 角色类
角色类包括吃豆人和鬼魂,鬼魂由电脑控制其运动轨迹,吃豆人由玩家控制其运动轨迹。
显然,其均需具备更新角色位置和改变角色运动方向的能力,其源代码如下:
Step2:设计 游戏 地图
利用Step1中定义的 游戏 精灵类,我们就可以开始设计 游戏 地图了。由于时间有限,我只写了一个关卡的 游戏 地图,有兴趣的小伙伴可以在此基础上进行扩展(在我的源代码基础上进行扩展是很方便滴~)。 游戏 地图的设计包括以下四方面内容:
① 创建墙
② 创建门(一开始关幽灵用的)
image.gif
③ 创建角色
④ 创建食物
因为食物不能和墙、门以及角色的位置重叠,所以为了方便设计 游戏 地图,要先创建完墙、门以及角色后再创建食物:
Step3:设计 游戏 主循环
接下来开始设计 游戏 主循环。首先是初始化:
然后定义主函数:
其中startLevelGame函数用于开始某一关 游戏 ,其源代码如下:
showText函数用于在 游戏 结束或关卡切换时在 游戏 界面中显示提示性文字,其源代码如下:

求个Python小游戏

浅浅的笑着:“我会带着你的孩子,顚节进入
Python程序开发之简单小程序实例 (11)小 游戏 -跳动的小球 一、项目功能 用户控制挡板来阻挡跳动的小球。 二、项目分析 根据项目功能自定义两个类,一个用于控制小球在窗体中的运动,一个用于接收用户按下左右键时,挡板在窗体中的运动。在控制小球的类中,我们还需要考虑当小球下降时,碰到挡板时的位置判断。 三、程序源代码 源码部分截图: 源码: #!/usr/bin/python3.6 # -*- coding: GBK -*- #导入相应模块 from tkinter import * import random import time #自定义小球的类 Ball class Ball: # 初始化 def __init__(self,canvas,paddle,color): #传递画布值 self.canvas=canvas #传递挡板值 self.paddle=paddle #画圆并且保存其ID self.id=canvas.create_oval(10,10,25,25,fill=color) self.canvas.move(self.id,245,100) #小球的水平位置起始列表 start=[-3,-2,-1,1,2,3] #随机化位置列表 random.shuffle(start) self.x=start[0] self.y=-2 self.canvas_heigh=self.canvas.winfo_height()#获取窗口高度并保存 self.canvas_width=self.canvas.winfo_width() #根据参数值绘制小球 def draw(self): self.canvas.move(self.id,self.x,self.y) pos=self.canvas.coords(self.id)#返回相应ID代表的图形的当前坐标(左上角和右上角坐标) #使得小球不会超出窗口 pad=self.canvas.coords(self.paddle.id)#获取小球挡板的坐标 if pos[1]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]
Python3X\Lib\turtledemo\nim.py自带的尼姆游戏

python实现超级玛丽小游戏(动图演示+源码分享)

效果演示:
基础源码
1.基础设置(tools部分)
2.设置背景音乐以及场景中的文字(setup部分)
3.设置 游戏 规则(load_screen)
4.设置 游戏 内菜单等(main_menu)
5.main()
6.调用以上函数实现
1.基础设置(tools部分)
这个部分设置马里奥以及 游戏 中蘑菇等怪的的移动设置。

在线等!求一个python 五子棋源代码,最好是有“人人对弈”和“人机对弈”功能的,不胜感谢!

试试这个吧。
import numpy as np
import pygame
import sys
import traceback
import copy
from pygame.locals import *
pygame.init()
pygame.mixer.init()
#颜色
background=(201,202,187)
checkerboard=(80,80,80)
button=(52,53,44)
#音乐
play_chess_sound = pygame.mixer.Sound("music/play_chess.wav")
play_chess_sound.set_volume(0.2)
button_sound = pygame.mixer.Sound("music/button.wav")
button_sound.set_volume(0.2)
victor_sound = pygame.mixer.Sound("music/victory.wav")
victor_sound.set_volume(0.2)
#绘制棋盘
def Draw_a_chessboard(screen):
#填充背景色
screen.fill(background)
Background=pygame.image.load("background.jpg").convert_alpha()
screen.blit(Background,(0,0))
#画棋盘
for i in range(21):
pygame.draw.line(screen, checkerboard, (40*i+3, 3), (40*i+3, 803))
pygame.draw.line(screen, checkerboard, (3, 40*i+3), (803, 40*i+3))
#画边线
pygame.draw.line(screen, checkerboard, (3, 3), (803, 3),5)
pygame.draw.line(screen, checkerboard, (3, 3), (3, 803),5)
pygame.draw.line(screen, checkerboard, (803, 3), (803, 803),5)
pygame.draw.line(screen, checkerboard, (3, 803), (803, 803),5)

#画定位点
pygame.draw.circle(screen, checkerboard, (163, 163), 6)
pygame.draw.circle(screen, checkerboard, (163, 643), 6)
pygame.draw.circle(screen, checkerboard, (643, 163), 6)
pygame.draw.circle(screen, checkerboard, (643, 643), 6)
pygame.draw.circle(screen, checkerboard, (403, 403), 6)

#画‘悔棋’‘重新开始’跟‘退出’按钮
pygame.draw.rect(screen,button,[900,350,120,100],5)
pygame.draw.rect(screen,button,[900,500,200,100],5)
pygame.draw.rect(screen,button,[900,650,200,100],5)
s_font=pygame.font.Font('font.ttf',40)
text1=s_font.render("悔棋",True,button)
text2=s_font.render("重新开始",True,button)
text3=s_font.render("退出游戏",True,button)
screen.blit(text1,(920,370))
screen.blit(text2,(920,520))
screen.blit(text3,(920,670))
#绘制棋子(横坐标,纵坐标,屏幕,棋子颜色(1代表黑,2代表白))
def Draw_a_chessman(x,y,screen,color):
if color==1:
Black_chess=pygame.image.load("Black_chess.png").convert_alpha()
screen.blit(Black_chess,(40*x+3-15,40*y+3-15))
if color==2:
White_chess=pygame.image.load("White_chess.png").convert_alpha()
screen.blit(White_chess,(40*x+3-15,40*y+3-15))
#绘制带有棋子的棋盘
def Draw_a_chessboard_with_chessman(map,screen):
screen.fill(background)
Draw_a_chessboard(screen)
for i in range(24):
for j in range(24):
Draw_a_chessman(i+1,j+1,screen,map[i][j])
#定义存储棋盘的列表,
#列表为24列24行是因为判断是否胜利函数里的索引会超出19
#列表大一点不会对游戏有什么影响
map=[]
for i in range(24):
map.append([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
#清零map列表
def clear():
global map
for i in range(24):
for j in range(24):
map[i][j]=0
#判断是否胜利
def win(i, j):
k = map[i][j]
p=[]
for a in range(20):
p.append(0)
for i3 in range(i-4,i+5):
for j3 in range(j-4,j+5):
if (map[i3][j3] == k and i3 - i == j3 - j and i3 <= i and j3 <= j):
p[0]+=1
if (map[i3][j3] == k and j3 == j and i3 <= i and j3 <= j):
p[1]+=1
if (map[i3][j3] == k and i3 == i and i3 <= i and j3 <= j):
p[2]+=1
if (map[i3][j3] == k and i3 - i == j3 - j and i3 >= i and j3 >= j):
p[3]+=1
if (map[i3][j3] == k and j3 == j and i3 >= i and j3 >= j):
p[4]+=1
if (map[i3][j3] == k and i3 == i and i3 >= i and j3 >= j):
p[5]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i and j3 >= j):
p[6]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i and j3 <= j):
p[7]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[8]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[9]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[10]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[11]+=1
if (map[i3][j3] == k and j == j3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[12]+=1
if (map[i3][j3] == k and i == i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[13]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 1 and i3 >= i - 3 and j3 >= j - 1 and j3 <= j + 3):
p[14]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i - 1 and i3 <= i + 3 and j3 <= j + 1 and j3 >= j - 3):
p[15]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[16]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[17]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[18]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[19]+=1
for b in range(20):
if p[b]==5:
return True
return False
#绘制提示器(类容,屏幕,字大小)
def text(s,screen,x):
#先把上一次的类容用一个矩形覆盖
pygame.draw.rect(screen,background,[850,100,1200,100])
#定义字体跟大小
s_font=pygame.font.Font('font.ttf',x)
#定义类容,是否抗锯齿,颜色
s_text=s_font.render(s,True,button)
#将字放在窗口指定位置
screen.blit(s_text,(880,100))
pygame.display.flip()
#用于控制顺序
t=True
#用于结束游戏后阻止落子
running=True
#主函数
def main():
#将 t,map,running设置为可改的
global t,map,running,maps,r,h
#将map置零
clear()
#定义储存所有棋盘状态的列表(用于悔棋)
map2=copy.deepcopy(map)
maps=[map2]

阅读更多 >>>  编程课程内容,学习编程都学些什么内容?

#定义窗口
screen = pygame.display.set_mode([1200,806])

#定义窗口名字
pygame.display.set_caption("五子棋")

#在窗口画出棋盘,提示器以及按钮
Draw_a_chessboard(screen)
pygame.display.flip()
clock=pygame.time.Clock()
while True:
#只有running为真才能落子,主要用于游戏结束后防止再次落子
if running:
if t:
color=1
text('黑棋落子',screen,54)
else:
color=2
text('白棋落子',screen,54)

for event in pygame.event.get():
#点击x则关闭窗口
if event.type ==pygame.QUIT:
pygame.quit()
sys.exit()

#点击窗口里面类容则完成相应指令
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
x,y=event.pos[0],event.pos[1]
for i in range(19):
for j in range(19):
#点击棋盘相应位置
if i*40+3+20
<x<i*40+3+60 and j*40+3+20<y<j*40+3+60 not map[i][j] running:
#在棋盘相应位置落相应颜色棋子

Draw_a_chessman(i+1,j+1,screen,color)

#播放音效

play_chess_sound.play(0)

#在map里面记录落子位置

map[i][j]=color

#将map存入maps

map3=copy.deepcopy(map)

maps.append(map3)

#判断落子后是否有五子一线

if win(i,j):

if t:

text('黑棋胜利,请重新游戏',screen,30)

else:

text('白棋胜利,请重新游戏',screen,30)

#播放音效

victor_sound.play(0)

#阻止再往棋盘落子

running=False

pygame.display.flip()

t=not t

#如果点击‘重新开始’

if 900
<x<1100 and 500<y<600:
#取消阻止

running=True

#播放音效

button_sound.play(0)

#重新开始

main()

#点击‘退出游戏’,退出游戏

elif 900
<x<1100 and 650<y<750:
#播放音效

button_sound.play(0)

pygame.quit()

sys.exit()

#点击‘悔棋’

elif 900
<x<1020 and 350<y<450 len(maps)!="1:
#播放音效

button_sound.play(0)

#删除maps里最后一个元素

del maps[len(maps)-1]

#再将最后一个元素copy给map

map=copy.deepcopy(maps[len(maps)-1])

#切换顺序

t=not t

#将map显示出来

Draw_a_chessboard_with_chessman(map,screen)

#悔棋完成,阻止再次悔棋

x,y=0,0

clock.tick(60)

if __name__ == "__main__":

try:

main()

except SystemExit:

pass

except:

traceback.print_exc()

pygame.quit()

input()
</x
</x
</x
</x

请用PYTHON编一个小游戏,如五子棋,连连看,贪吃蛇,扫雷,计算器等等

这些游戏都不小啊,很体现功力的。贪吃蛇好象看到过C语言版本的,python的应该了有。
不过很多需要先安装pygame包的。
五子棋、贪吃蛇、扫雷、俄罗斯方块、坦克大战、FlappyBird,
源码地址github
http://download.csdn.net/download/y453717489/4731713
#!/usr/bin/pythonfrom Tkinter import *import randomclass snake(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.body = [(0,0)] self.bodyid = [] self.food = [ -1, -1 ] self.foodid = -1 self.gridcount = 10 self.size = 500 self.di = 3 self.speed = 500 self.top = self.winfo_toplevel() self.top.resizable(False, False) self.grid() self.canvas = Canvas(self) self.canvas.grid() self.canvas.config(width=self.size, height=self.size,relief=RIDGE) self.drawgrid() s = self.size/self.gridcount id = self.canvas.create_rectangle(self.body[0][0]*s,self.body[0][1]*s, (self.body[0][0]+1)*s, (self.body[0][1]+1)*s, fill="yellow") self.bodyid.insert(0, id) self.bind_all("

", self.keyrelease) self.drawfood() self.after(self.speed, self.drawsnake) def drawgrid(self): s = self.size/self.gridcount for i in range(0, self.gridcount+1): self.canvas.create_line(i*s, 0, i*s, self.size) self.canvas.create_line(0, i*s, self.size, i*s) def drawsnake(self): s = self.size/self.gridcount head = self.body[0] new = [head[0], head[1]] if self.di == 1: new[1] = (head[1]-1) % self.gridcount elif self.di == 2: new[0] = (head[0]+1) % self.gridcount elif self.di == 3: new[1] = (head[1]+1) % self.gridcount else: new[0] = (head[0]-1) % self.gridcount next = ( new[0], new[1] ) if next in self.body: exit() elif next == (self.food[0], self.food[1]): self.body.insert(0, next) self.bodyid.insert(0, self.foodid) self.drawfood() else: tail = self.body.pop() id = self.bodyid.pop() self.canvas.move(id, (next[0]-tail[0])*s, (next[1]-tail[1])*s) self.body.insert(0, next) self.bodyid.insert(0, id) self.after(self.speed, self.drawsnake) def drawfood(self): s = self.size/self.gridcount x = random.randrange(0, self.gridcount) y = random.randrange(0, self.gridcount) while (x, y) in self.body: x = random.randrange(0, self.gridcount) y = random.randrange(0, self.gridcount) id = self.canvas.create_rectangle(x*s,y*s, (x+1)*s, (y+1)*s, fill="yellow") self.food[0] = x self.food[1] = y self.foodid = id def keyrelease(self, event): if event.keysym == "Up" and self.di != 3: self.di = 1 elif event.keysym == "Right" and self.di !=4: self.di = 2 elif event.keysym == "Down" and self.di != 1: self.di = 3 elif event.keysym == "Left" and self.di != 2: self.di = 4app = snake()app.master.title("Greedy Snake")app.mainloop()贪食蛇

阅读更多 >>>  python难不难学,python到底难不难学

如何Python写一个安卓APP

前言:用Python写安卓APP肯定不是最好的选择,但是肯定是一个很偷懒的选择,而且实在不想学习Java,再者,就编程而言已经会的就Python与Golang(注:Python,Golang水平都一般),那么久Google了一下Python写安卓的APP的可能性,还真行。
既然要写个APP,那么总得要有个想法吧。 其实笔者想做两个APP来着,一个是自己写着好玩的,一个是关于运维的。 关于运维的APP,设计应该如下 可能长这样:
然后设计应该是这样:
如果觉得可行的话,评论留言一下你觉得应该写进这个APP的运维常用命令吧^_^,笔者暂时想到的是top,free -m,df –h,uptime,iftop,iotop,如果有什么好的想法就狠狠的砸过来吧,笔者到时应该也会把这个写成一个项目放到github上,大家一起用嘛,开源才是王道,哈哈。
好吧,进入正题。 我们使用kivy开发安卓APP,Kivy是一套专门用于跨平台快速应用开发的开源框架,使用Python和Cython编写,对于多点触控有着非常良好的支持,不仅能让开发者快速完成简洁的交互原型设计,还支持代码重用和部署,绝对是一款颇让人惊艳的NUI框架。 因为跨平台的,所以只写一遍代码,就可以同时生成安卓及IOS的APP,很酷吧。 本文会带大家写一个Hello world并瞧一瞧Python版的2048的代码
kivy安装 环境说明:笔者在用的是Python2.7.10 这里仅介绍windows平台安装
更新pip,setuptools
python -m pip install --upgrade pip wheel setuptools12
然后是安装所需要的依赖
python -m pip install docutils pygmentspypiwin32 kivy.deps.sdl2 kivy.deps.glew \kivy.deps.gstreamer --extra-index-url ple/123
值得注意的是,上面的安卓需要访问Google,所以请自备梯子,而且kivy.deps.gstreamer这个包比较大(95MB),可以单独本地安装,h然后就是安装kivy了
python -m pip install kivy12
至此,安装就已经完毕了,值得注意的是64位系统没有开启虚拟化支持,在导入kivy的时候会报错,如果是64位系统就设置一下机器的BIOS,开启虚拟化支持吧。 注:这里只是kivy的运行环境,这样我就能直接在windows机器上直接调试了,怎么将代码编译成APK文件我们会在后面讲到。
如果kivy在python中应该就能导入了。
按照世界惯例,我们”hello”一下吧。 新建一个.py文件
from kivy.app import Appfrom kivy.uix.button importButtonclass TestApp(App):def build(self):return Button(text='Hello,kivy')TestApp().run()123456789
运行:
然后会弹出一个框,大概如下,点击”hello,kivy”会变颜色
点击窗口并按“F1”会这个窗口的一些属性
然后我们回过头看一看代码。
##导入App,然后让TestApp这个类继承from kivy.app import App##导入一个Button,运维有这个button,当你点击的时候才会有所反应from kivy.uix.button importButton###定义类,名字必须是xxxAppclass TestApp(App):###build一个Buttondef build(self):###返回一个Button,文字内容是“Hello,kivy”return Button(text='Hello,kivy')##运行,因为继承了App,所以才有的run这个方法TestApp().run()123456789101112131415
上面就是我们的Hello了 在windows上运行当然没有什么太大的意义,怎么在安卓手机上运行才是我们想要的, 这时我们需要一个编译环境。 官方说明的环境,如下:
You’ll need:A linux computer or a virtual machineJavaPython 2.7 (not 2.6.)Jinja2 (python module)Apache antAndroid SDK12345678
虽然官方提供了一个似乎还不错的虚拟机镜像,但是还是有很多内容需要翻出去,所以笔者在
当然你也可以下载官方镜像,因为第一次编译需要去国外下一大堆东西,所以请自备梯子。
Virtual Machine A Virtual Machine with Android SDK and NDK and all otherpre-requisites pre installed to ease apk generation: Kivy Buildozer VM Or select the Torrent
在笔者提供的镜像里,桌面上有一个dev_and,只要将上面写的代码,放入这个文件夹即可(当然也可以在其他目录,后面会讲到)。
cd Desktop/dev_and/12
初始化会在当前目录生成一个buildozer.spec文件 用于配置生成的apk相关信息
buildozer init12
修改buildozer.spec文件
vi buildozer.spec12
至少修改下面三项
# (str) Title of your applicationtitle = helloworld# (str) Package namepackage.name = helloapp# (str) Package domain (needed for android/ios packaging)package.domain = youer.com123456789
然后注释
# (str) Application versioning (method 1)#version.regex = __version__ = ['"](.*)['"]#version.filename = %(source.dir)s/main.py下面这行改为非注释version = 1.2.0123456
最后我们生成我们需要的apk文件
buildozer -v android debug12
buildozer命令会在当前文件夹创建一个bin,该文件夹里面有我们想要的apk文件
helloapp-1.2.0-debug.apk
安装以后应该是这样
话说在编译的时候可能出现空间不足的情况,根据虚拟机的不同(vmware或virtualbox)自行扩容吧。
最后我们来瞧瞧简易版Python开发的2048这个游戏的源代码。 先看效果图
试玩了一下,还是蛮流畅的,有兴趣的可以下载玩一下 这个游戏代码虽然不长,但是还是蛮占篇幅的,所以简要的说明一下流程:
主要由三部分组成,一是素材,图片音频之类的文件,二是Python代码,三是kv文件,这个kv文件有点像html中的css。 Python代码的文件名一般命名为main.py 然后一定有一个叫做XXXApp的类,并继承App。 比如该类叫做GameApp,那么该目录下的kv文件则必须为Game,如上图所示,如果不是,那么kv文件中的一些设定就不会生效。 比如设定一个标签
Label:id: timetext: 'xxxx'font_size: 6012345
id为time,text文本内容为’xxxx’,然后字体为60 好吧,点到为止吧,不过似乎什么都没点到~~~
从无到有做一个App,我想我会另起一篇文章吧。

用Python写一个简单的小游戏

相信大家都玩过俄罗斯方块吧,应该是小时候的回忆吧,但是想不想了解一下这个程序是怎么写出来的呢,自己写出来的应该玩起来更有感觉吧!

感觉还是蛮好玩吧!

接下来,我就分享一下这个游戏的源码过程啊!

先用python创建一个py文件

定义这次程序所需要的类

然后写出它所需要的模块

画背景图

画网格线

# 画已经落下的方块

# 画单个方块

# 画得分等信息

这样就可以写出来一个十分简单的俄罗斯方块啦,是不是觉得还不错呢!

网站数据信息

"python游戏源码,python 编写一个彩票游戏?"浏览人数已经达到22次,如你需要查询该站的相关权重信息,可以点击进入"Chinaz数据" 查询。更多网站价值评估因素如:python游戏源码,python 编写一个彩票游戏?的访问速度、搜索引擎收录以及索引量、用户体验等。 要评估一个站的价值,最主要还是需要根据您自身的需求,如网站IP、PV、跳出率等!