当前位置:文档之家› Python小游戏程序锦集

Python小游戏程序锦集

Python小游戏程序锦集
Python小游戏程序锦集

可拖动地图的放大镜

"""

Demonstration of a draggable magnifier on a map

"""

import simplegui

# 1521x1818 pixel map of native American language

# Source - Gutenberg project

MAP_WIDTH = 1521

MAP_HEIGHT = 1818

map_image =

simplegui.load_image("https://www.doczj.com/doc/aa4304121.html,/codeskulptor-assets/g utenberg.jpg")

# Constants

MAP_SCALE = 3

CANVAS_WIDTH = MAP_WIDTH / MAP_SCALE

CANVAS_HEIGHT = MAP_HEIGHT / MAP_SCALE

MAGNIFIER_SIZE = 120

# Event handlers

def click(pos):

"""

Reset center of magnifier pane to current click position

"""

magnifier_center[0] = pos[0]

magnifier_center[1] = pos[1]

def drag(pos):

"""

Reset center of magnifier pane to current click position

"""

magnifier_center[0] = pos[0]

magnifier_center[1] = pos[1]

def draw(canvas):

"""

Draw handler - draws map, magnifier pane, and box around magnifier """

# Draw map

canvas.draw_image(map_image, (MAP_WIDTH / 2, MAP_HEIGHT / 2), (MAP_WIDTH, MAP_HEIGHT),

(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2), (CANVAS_WIDTH, CANVAS_HEIGHT))

# Draw magnifier

source_center = (MAP_SCALE * magnifier_center[0], MAP_SCALE *

magnifier_center[1])

canvas.draw_image(map_image, source_center, [MAGNIFIER_SIZE,

MAGNIFIER_SIZE],

magnifier_center, [MAGNIFIER_SIZE, MAGNIFIER_SIZE])

# Draw outline around magnifier

mag_left = magnifier_center[0] - MAGNIFIER_SIZE / 2

mag_right = magnifier_center[0] + MAGNIFIER_SIZE / 2

mag_top = magnifier_center[1] - MAGNIFIER_SIZE / 2

mag_bottom = magnifier_center[1] + MAGNIFIER_SIZE / 2

mag_topleft = (mag_left, mag_top)

mag_topright = (mag_right, mag_top)

mag_botleft = (mag_left, mag_bottom)

mag_botright = (mag_right, mag_bottom)

box = [mag_topleft, mag_botleft, mag_botright,

mag_topright, mag_topleft]

canvas.draw_polyline(box, 4, "Blue")

# event handler for timer

def tick():

"""

Move center of magnifier pane slowly down/right

"""

magnifier_center[0] += 1

magnifier_center[1] += 1

# Create frame for map

frame = simplegui.create_frame("Map magnifier", CANVAS_WIDTH, CANVAS_HEIGHT) frame.set_draw_handler(draw)

frame.set_mouseclick_handler(click)

frame.set_mousedrag_handler(drag)

# Create timer that slowly slides the magnifier pane

timer = simplegui.create_timer(60.0,tick)

# Start timer and frame animation

magnifier_center = [CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2] timer.start()

frame.start()

骰子骰子游戏

"""

Dice game "Craps" - uses only control elements plus prints to console """

import simplegui

import random

def gen_roll():

"""

Helper function that rolls two dice and prints/returns the results

"""

die1 = random.randrange(0, 6) + 1

die2 = random.randrange(0, 6) + 1

print "You rolled", str(die1), "and", str(die2)

return die1 + die2

def process_roll():

"""

Handler for roll, encodes basic logic for Craps""" global point, point_set, bankroll

# print out message for new game"

if not point_set:

print

print "New game. Your bet is", str(bet)

# logic for first roll

roll = gen_roll()

if not point_set:

if roll == 7 or roll == 11:

bankroll += bet

print "You won. Your bankroll is", str(bankroll) elif roll == 2 or roll ==3 or roll == 12:

bankroll -= bet

print "You lost. Your bankroll is", str(bankroll) else:

point = roll

point_set = True

print "Your point is", str(point)

# logic for subsequent rolls

elif roll == 7:

bankroll -= bet

point_set = False

print "You crapped out! Your bankroll is", str(bankroll) elif roll == point:

bankroll += bet

point_set = False

print "You made your point! Your bankroll is", str(bankroll)

def set_bet(inp):

"""

Input handler for changing bet size via input, forfeits current bet """

global bet, bankroll, point_set

print

if point_set:

point_set = False

bankroll -= bet

print "Forfeiting current bet. Your bankroll is", str(bankroll) bet = int(inp)

print "New bet size is", str(bet)

# create frame and UI elements

frame = simplegui.create_frame("Craps", 200, 200) frame.add_button("Roll", process_roll, 200)

frame.add_input("Set bet", set_bet, 200)

# initialize global variables used in game

point_set = False

bet = 10

bankroll = 1000

print "Your initial bankroll is", bankroll

print "Your initial bet size is", bet

print "Click roll to start the game"

frame.start()

雪碧动画片"""

Animation of explosion using 2D sprite sheet

"""

import simplegui

# load 9 x 9 frame sprite sheet for explosion - image generated by phaedy explosion generator, source is https://www.doczj.com/doc/aa4304121.html,

EXPLOSION_CENTER = [50, 50]

EXPLOSION_SIZE = [100, 100]

EXPLOSION_DIM = [9, 9]

explosion_image =

simplegui.load_image("https://www.doczj.com/doc/aa4304121.html,/codeskulptor-assets/e xplosion.hasgraphics.png")

# define draw handler

def draw(canvas):

"""

Draw handler for simple animation using 2D sprite sheet

"""

global counter

explosion_index = [counter % EXPLOSION_DIM[0], counter // EXPLOSION_DIM[0]]

canvas.draw_image(explosion_image,

[EXPLOSION_CENTER[0] + explosion_index[0] *

EXPLOSION_SIZE[0],

EXPLOSION_CENTER[1] + explosion_index[1] *

EXPLOSION_SIZE[1]],

EXPLOSION_SIZE, EXPLOSION_CENTER, EXPLOSION_SIZE) counter = (counter + 1) % (EXPLOSION_DIM[0] * EXPLOSION_DIM[1])

# create frame and size frame based on 100x100 pixel sprite

frame = simplegui.create_frame("Asteroid sprite", EXPLOSION_SIZE[0],

EXPLOSION_SIZE[1])

# set draw handler and canvas background using custom HTML color

frame.set_draw_handler(draw)

frame.set_canvas_background("Blue")

# initialize counter for animation and start frame

counter = 0

frame.start()

俄罗斯方块

# Falling blocks as in Tetris(BUT NOT REALLY), use arrow \ #keys to move sideways and stack

import simplegui

import random

import time

#Player preferences

start_level = 0

left_movement = "left"

right_movement = "right"

clockwise_rotation = "up"

cc_rotation = "down"

soft_drop = "x"

hard_drop = "z"

# Standard Tetris grid is 10x22 blocks, top two row are # hidden

# Define each block as 20 pixels

#setting up the gui stuff

width = 10

height = 22

block_size = 20

frame_width = 16

frame_height = 22

#scoring

num_cleared = 0

score = 0

level = 0

#define initial grid

grid = [[7 for j in range(height)] for i in range(width)]

# define dictionary to lookup color from grid values

color_Dict = {0:"Aqua", 1:"Orange", 2:"Blue", 3:"Purple", \

4:"Red", 5:"Lime", 6:"Yellow", 7:"White", \

8: "Black"}

# define helpers

def draw_block(c,pos,color):

""" draws a block with position pos on the canvas c """

c.draw_polygon([[pos[0],pos[1]],[pos[0]+block_size, \

pos[1]],[pos[0]+block_size, \

pos[1]+block_size],[pos[0], \

pos[1]+block_size]],1,"White",color)

# define callbacks

def draw(c):

""" callback for draw handler, draw blocks represented \ by grid """

global frame_height

global block_size

global pos_list

global num_cleared

global score

global level

global start_level

c.draw_line((10*block_size,0), \

(10*block_size, frame_height*block_size), \

15, "Black")

c.draw_text("Next Block:", \

(11*block_size, 1*block_size) , \

12, "Black")

c.draw_text("Lines Cleared:", \

(11*block_size, 6*block_size), \

12, "Black")

c.draw_text(str(num_cleared), \

(13*block_size, 7*block_size) , \

12, "Black")

c.draw_text("Score:", (11*block_size, 9*block_size), \

12, "Black")

c.draw_text(str(score), (13*block_size, 10*block_size),\

12, "Black")

c.draw_text("Level:", (11*block_size, 12*block_size),\

12, "Black")

c.draw_text(str(level+start_level), \

(13*block_size, 13*block_size) , \

12, "Black")

#drawing next block

global width

next_piece_offset = [(width-2)*block_size, \

(2)*block_size]

#print next_piece_offset

for pos in pos_list.piece_dict[pos_list.next_piece]: draw_block(c, [pos[0]*block_size + \

next_piece_offset[0], \

pos[1]*block_size + \

next_piece_offset[1]], \

color_Dict[pos_list.next_piece])

for i in range(width):

for j in range(height):

draw_block(c,[i*block_size,j*block_size], \

color_Dict[grid[i][j]])

class Controls:

def __init__(self, left_movement, right_movement, \

clockwise_rotation, cc_rotation, \

soft_drop, hard_drop):

"""required init function"""

self.previous_key = None

self.left_movement = left_movement

self.right_movement = right_movement

self.clockwise_rotation = clockwise_rotation

https://www.doczj.com/doc/aa4304121.html,_rotation = cc_rotation #still need to do

self.soft_drop = soft_drop

self.hard_drop = hard_drop #still need to do

def keydown_handler(self, key):

"""The keydown handler"""

if self.previous_key == None:

self.previous_key = key

self.key = key

self.keydown() #so that holding down is not

#necessary

self.timer = simplegui.create_timer(1000.0/7, \

self.keydown)

self.timer.start()

def keydown(self):

""" key handler that control sideways motion of blocks """

global pos_list

global pos

#finding the side pieces

lowest_val = width

highest_val = 0

left_blocks = []

right_blocks = []

for pos in pos_list.piece:

if pos[0] < lowest_val:

lowest_val = pos[0]

left_blocks = []

left_blocks.append(pos) if pos[0] == highest_val:

left_blocks.append(pos) if pos[0] > highest_val:

highest_val = pos[0]

right_blocks = []

right_blocks .append(pos) if pos[0] == highest_val:

right_blocks .append(pos) fall = check_fall()

right, left = check_sideways()

if self.key ==simplegui.KEY_MAP\

[self.left_movement] and \

left_blocks[0][0] != 0 and left:

#update old squares to be white

for block in pos_list.piece:

grid[block[0]][block[1]]= 7

pos_list.move_piece([-1,0])

elif self.key == simplegui.KEY_MAP\

[self.right_movement] and \

right_blocks[0][0] != width-1 and right: #update old squares to be white

for block in pos_list.piece:

grid[block[0]][block[1]]= 7

pos_list.move_piece([1,0])

elif self.key == simplegui.KEY_MAP\

[self.hard_drop] and fall:

while fall:

#update old squares to be white

for block in pos_list.piece:

grid[block[0]][block[1]]= 7

pos_list.move_piece([0,1])

fall = check_fall()

elif self.key == simplegui.KEY_MAP\

[self.soft_drop] and fall:

#update old squares to be white

for block in pos_list.piece:

grid[block[0]][block[1]]= 7

pos_list.move_piece([0,1])

elif self.key == simplegui.KEY_MAP\

[self.clockwise_rotation]:

pos_list.rotate(True)

elif self.key == simplegui.KEY_MAP\

[https://www.doczj.com/doc/aa4304121.html,_rotation]:

pos_list.rotate(False)

def keyup(self, key):

if key == self.previous_key:

self.timer.stop()

self.previous_key = None

class Blocks:

def __init__(self):

#0:"I", 1:"L", 2:"J", 3:"T", 4:"Z", 5:"S", 6:"O"

#O is a character not an int

#self.block_dict = {0:"Aqua", 1:"Orange", \

#2:"Blue", 3:"Purple", 4:"Red",\

#5:"Lime", 6:"Yellow"}

self.choice = random.randint(0,6) #last number

#should be 6 and first 0 self.next_piece = random.randint(0,6)

self.piece_dict = {0:[[3,0],[4,0],[5,0],[6,0]], \

1:[[4,1],[5,1],[6,1],[6,0]], \

2:[[4,0],[4,1],[5,1],[6,1]], \

3:[[4,1],[5,1],[6,1],[5,0]], \

4:[[4,0],[5,0],[5,1],[6,1]], \

5:[[5,0],[6,0],[4,1],[5,1]], \

6:[[4,0],[5,0],[4,1],[5,1]]} def create_piece(self):

12岁的少年教你用Python做小游戏

你有没有想过电脑游戏是怎样制作出来的?其实它没有你想象的那样复杂!在这个教程里,你要学做一个叫《兔子和獾》的塔防游戏,兔子作为英雄,需要在城堡里抵御獾的进攻。 为了写这个游戏的代码,你将会用Python。好吧,我不是指一条大蟒蛇!Python是一种计算机语言。我们在这篇教程里选择Python是因为这门语言很容易上手,学习起来也很简单和有趣。 如果你是个Python方面的新手,在开始看教程之前你可以看看这本书《Think P ython: How to Think Like a Computer Scientist》。这能让你看教程的时候不那么吃力。 在看了那本书后回到这里并且准备好——兔子和獾之间有一场大战爆发,一起来加入到这场战斗中来吧!

1 2 3 4 Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 注意:如果你想迅速终止Python,你可以输入exit()然后按回车,或者是按Contr ol+D。 现在很迅速的把Python环境配置好了,为了测试下Python是否正常工作,输入print 1+1 然后按回车,应该会打印出2。你刚才就写了一个简单的Python程序!

1 Python 2.7. 2 (default, Jun 20 2012, 16:23:33)

Python-大作业之五子棋游戏(附代码)

Python 大作业——五子棋游戏 姓名:学号: 姓名:学号: 一游戏介绍: 我们设计的是五子棋游戏,支持两人一个鼠标对下,黑方用左键单击,白方用右键单击,谁先下均可,落子无悔,下过的棋子对方点击后不会变色,程序可自行判断输赢并在五子连珠时弹出结果对话框,游戏双方需遵守不在空地点击和一次下一子的规则。 二游戏代码设计: 代码均为原创,没有借鉴和抄袭,首先是用户GUI界面设计,点击start进入游戏界面,点击quit则退出程序,为了方便判断和记录,我们按从左到右,从上到下的顺序给15x15=225颗棋子编号225,左键绑定函数callback1,点击后可算出它位于哪颗棋子上再画出来黑子,并把对应编号计入record这个列表,之后进入判断函数。右键绑定函数callback2,点击后画出白子,对应编号计入recor这个列表,之后进入判断函数,其中总列表rec的作用是使棋子不被下第二遍。 三作业感想 这个游戏虽然很小但是可以供室友们晚上娱乐之用,我们倾注了很多心血,之前采用模块化编程失败了很多次,有事件响应问题,参数传递问题,到第七个程序才成功,感谢张同珍老师指点了很多,

我们学会了使用类,受益匪浅,对Python产生了浓厚的兴趣。四过程截图 五、实验代码 from Tkinter import * from tkMessageBox import * class Game: def __init__(self): self.A=[] self.B=[] self.record=set()

self.recor=set() self.rec=self.record|self.recor self.root=Tk() self.root.geometry("180x250") self.root.title("Wu Zi Qi Game") self.r=Canvas(self.root,width=180,height=210,bg="purple") pic=PhotoImage(file="beijing.gif") self.r.create_image(90,100,image=pic) self.r.place(x=0,y=15) Label(self.root,text="***Wu Zi Qi Game***",fg="red").place(x=20,y=0) Button(self.root,text="start",command=self.start).place(x=30,y=230) Button(self.root,text="quit ",command=self.root.destroy).place(x=100,y=230) self.r.mainloop() def start(self): self.root.destroy() self.top=Tk() self.top.title("Game Start") self.c=Canvas(self.top,width=480,height=480,bg="white") self.c.pack() self.c.create_rectangle(25,25,455,455,fill="gray") for i in range(30,451,30): for j in range(30,451,30): self.c.create_oval(i-2,j-2,i+2,j+2,fill="blue") for i in range(1,16): self.c.create_line(30,30*i,450,30*i) self.c.create_line(30*i,30,30*i,450) self.c.create_oval(234,234,246,246,fill="black") self.c.create_oval(115,115,125,125,fill="black") self.c.create_oval(355,115,365,125,fill="black") self.c.create_oval(115,355,125,365,fill="black") self.c.create_oval(355,355,365,365,fill="black") self.c.bind("",self.callback1) self.c.bind("",self.callback2) self.c.mainloop() def callback1(self,event): u,v=event.x,event.y s=u/15 if s%2==1: self.x=(s+1)/2 else: self.x=s/2

少儿编程分享:手把手教你用Python编写战斗机游戏(一)

游戏分享:手把手教你用Python编写 战斗机游戏 2018.1.23 游戏制作 今天我们要分享的是战斗机游戏!在这个游戏中,飞机(游戏主角)需要躲避迎面飞来的炮弹(敌人)。 下面让我们一起来看一下如何编写这个小游戏吧! 初始设置 首先,创建一个新的.py文件然后置入下面的代码: import pygame from pygame.locals import* pygame.init() 和其他所有python程序一样,我们要首先导入(import)我们所要使用的模块(module)。在今天这个例子里,我们要导入pygame以及pygame.locals,以用于后面的内容。最后一行pygame.init()将所有的PyGame模块初始化,在我们正式开始写PyGame的“正文内容”之前,都要先加上这一行。 屏幕对象 首先,我们需要为所有的物体创建一个画布窗口,我们把这个变量叫做screen。为了创建这个变量,我们需要调用pygame.display下的set_mode()方法(method),并向set_mode()传递一个元组(tuple)来表示窗口的高和宽(在这里我们设置一个高800宽600的窗口)。 import pygame

from pygame.locals import* pygame.init() screen=pygame.display.set_mode((800,600)) 现在,如果你运行程序,你将会看到一个窗口突然出现,并在我们退出程序时马上消失。看来我们已经成功创建了画布!在下一部分,我们将加入游戏的main循环,这样我们就能确保只有我们输入正确的退出命令时,程序才会退出。 游戏循环 游戏的主循环内包含了所有要发生的事件。当我们玩游戏时,这段程序一直在运行。它能够不断更新游戏的状态,渲染游戏屏幕效果,并且收集玩家输入的指令。除了让主循环在游戏进行中不断执行,我们也需要让循环在我们退出程序时停止。因而,我们需要引入一些相应的指令,让程序能够在这些指令输入(input)时作出相应的反应。所有输入的指令(以及之后一些其他的事件)都会进入PyGame 的事件队列中,我们可以通过pygame.event.get()来得到这些事件。这个命令会返回队列中的事件列表,在游戏中,程序将对这些事件进行循环,并且根据事件的类别作出相应的反应。在下一段代码中,我们要处理的是KEYDOWN和QUIT事件: #用于让主循环不断运行的变量 running=True #主循环 while running: #针对事件队列的for循环 for event in pygame.event.get(): #检测是否有KEYDOWN事件,KEYDOWN是一个在pygame.locals中定义了的事件常量,这个库我们之前导入过 if event.type==KEYDOWN: #如果按了ESC键,把running的值设为False,并退出主循环 if event.key==K_ESCAPE: running=False #检测是否有QUIT事件,如果有的话,把running的值设为Flase elif event.type==QUIT:

Python 俄罗斯方块游戏

【Python】用Python实现一个俄罗斯方块游戏 俄罗斯方块游戏,使用Python实现,总共有350+行代码,实现了俄罗斯方块游戏的基本功能,同时会记录所花费时间,消去的总行数,所得的总分,还包括一个排行榜,可以查看最高记录。 排行榜中包含一系列的统计功能,如单位时间消去的行数,单位时间得分等。 附源码: from Tkinter import* from tkMessageBox import* import random import time #俄罗斯方块界面的高度 HEIGHT=18 #俄罗斯方块界面的宽度 WIDTH=10 ACTIVE=1 PASSIVE=0 TRUE=1 FALSE=0 root=Tk();root.title('Russia') class App(Frame): def__init__(self,master): Frame.__init__(self) master.bind('',self.Up) master.bind('',self.Left) master.bind('',self.Right) master.bind('',self.Down) #master.bind('',self.Space) master.bind('',self.Space) master.bind('',self.Play) master.bind('',self.Pause) self.backg="#%02x%02x%02x"%(120,150,30) self.frontg="#%02x%02x%02x"%(40,120,150) self.nextg="#%02x%02x%02x"%(150,100,100) self.flashg="#%02x%02x%02x"%(210,130,100) self.LineDisplay=Label(master,text='Lines:',bg='black',fg='red') self.Line=Label(master,text='0',bg='black',fg='red') self.ScoreDisplay=Label(master,text='Score:',bg='black',fg='red') self.Score=Label(master,text='0',bg='black',fg='red') #Display time self.SpendTimeDisplay=Label(master,text='Time:',bg='black',fg='red') self.SpendTime=Label(master,text='0.0',bg='black',fg='red') self.LineDisplay.grid(row=HEIGHT-2,column=WIDTH,columnspan=2)

Python编的摇色子的小游戏的代码

# -*- coding:UTF-8 -*- import random def roll_dice(numbers=3, points=None): print('----- 摇骰子 -----') if points==None: points=[] while numbers > 0: point = random.randrange(1, 7) points.append(point) numbers = numbers - 1 return points def roll_result(total): isBig = 11 <= total <= 18 isSmall = 3 <= total <= 10 if isBig: return '大' else: return '小' def start_game(): your_money = 1000

while your_money > 0: print('----- 游戏开始 -----') choices = ['大', '小'] your_choice = raw_input('请下注,大 or 小:') your_bet = raw_input('下注金额:') if your_choice in choices: points = roll_dice() total = sum(points) youWin = your_choice == roll_result(total) if youWin: print(points) print('恭喜,你赢了 {} 元,你现在有 {} 元本金'.format(your_bet, your_money + int(your_bet))) your_money = your_money + int(your_bet) else: print('骰子点数:', points) print('很遗憾,你输了 {} 元,你现在有 {} 元本金'.format(your_bet, your_money - int(your_bet))) your_money = your_money - int(your_bet) else: print('输入错误') else: print('游戏结束') start_game()

Python 大作业之五子棋游戏(附代码)

Python 大作业——xx游戏 姓名: xx学号: 姓名: xx学号: 一游戏介绍: 我们设计的是五子棋游戏,支持两人一个鼠标对下,黑方用左键单击,白方用右键单击,谁先下均可,落子无悔,下过的棋子对方点击后不会变色,程序可自行判断输赢并在五子连珠时弹出结果对话框,游戏双方需遵守不在空地点击和一次下一子的规则。 二游戏代码设计: 代码均为,没有借鉴和抄袭,首先是用户GUI界面设计,点击start进入游戏界面,点击quit则退出程序,为了方便判断和记录,我们按从左到右,从上到下的顺序给15x15=225颗棋子编号225,左键绑定函数callback1,点击后可算出它位于哪颗棋子上再画出来黑子,并把对应编号计入record这个列表,之后进入判断函数。右键绑定函数callback2,点击后画出白子,对应编号计入recor 这个列表,之后进入判断函数,其中总列表rec的作用是使棋子不被下第二遍。 三作业感想 这个游戏虽然很小但是可以供室友们晚上娱乐之用,我们倾注了很多心血,之前采用模块化编程失败了很多次,有事件响应问题,参数传递问题,到第七个程序才成功,感谢张同珍老师指点了很多,我们学会了使用类,受益匪浅,对Python产生了浓厚的兴趣。 四过程截图 五、实验代码 from Tkinter import *

from tkMessageBox import * class Game: def __init__(self): self.A=[] self.B=[] self.record=set() self.recor=set() self.rec=self.record|self.recor self.root=Tk() self.root.geometry("180x250") self.root.title("Wu Zi Qi Game") self.r=Canvas(self.root,width=180,height=210,bg="purple") pic=PhotoImage(file="beijing.gif") self.r.create_image(90,100,image=pic) self.r.place(x=0,y=15) Label(self.root,text="***Wu Zi Qi Game***",fg="red").place(x=20,y=0) self.r.mainloop() def start(self): self.root.destroy() self.top=Tk()

基于Python的游戏app充值api调用代码实例

基于Python的游戏app充值api调用代码实例代码描述:基于Python的游戏app充值api调用代码实例 代码平台:聚合数据 #!/usr/bin/python # -*- coding: utf-8 -*- import json, urllib from urllib import urlencode #---------------------------------- # 游戏充值调用示例代码-聚合数据 # 在线接口文档:https://www.doczj.com/doc/aa4304121.html,/docs/88 #---------------------------------- def main(): #配置您申请的APPKey appkey ="*********************" #1.商品小类列表 request1(appkey,"GET") #2.商品信息 request2(appkey,"GET") #3.商品价格查询 request3(appkey,"GET") #4.游戏直充区服查询 request4(appkey,"GET") #5.游戏直充 request5(appkey,"GET") #6.订单状态查询 request6(appkey,"GET") #商品小类列表 def request1(appkey, m="GET"):

url ="https://www.doczj.com/doc/aa4304121.html,/ofpay/game/cardlist" params ={ "key": appkey, #应用APPKEY(应用详细页查询) } params =urlencode(params) if m =="GET": f =urllib.urlopen("%s?%s"%(url, params)) else: f =urllib.urlopen(url, params) content =f.read() res =json.loads(content) if res: error_code =res["error_code"] if error_code ==0: #成功请求 print res["result"] else: print"%s:%s"%(res["error_code"],res["reason"]) else: print"request api error" #商品信息 def request2(appkey, m="GET"): url ="https://www.doczj.com/doc/aa4304121.html,/ofpay/game/cardinfo" params ={ "cardid": "", #对应接口1的cardid "key": appkey, #应用APPKEY(应用详细页查询) } params =urlencode(params) if m =="GET": f =urllib.urlopen("%s?%s"%(url, params)) else: f =urllib.urlopen(url, params) content =f.read() res =json.loads(content) if res: error_code =res["error_code"] if error_code ==0: #成功请求 print res["result"]

少儿编程分享:手把手教你用Python编写贪吃蛇小游戏(一)

游戏分享:手把手教你用Python编写 贪吃蛇(一) 2018.1.10 今天我们将分享用Python制作贪吃蛇游戏。来试着挑战一下自己吧! 贪吃蛇游戏玩法 在贪吃蛇游戏中,玩家将控制一只不断在屏幕上四处行进的小蛇。玩家不能让小蛇减速,只能够控制小蛇的转向。每隔一段时间,屏幕上将出现一个红苹果,苹果的位置是随机的,玩家的目标是让小蛇吃到苹果。游戏开始的时候,蛇的长度很短,之后每一次吃到苹果,小蛇都会变长一点。当小蛇撞到屏幕的边缘时,游戏就结束了。 下面,让我们一起用Python一步步制作贪吃蛇游戏吧! 游戏网格 如果你之前玩过贪吃蛇游戏,你会发现苹果和小蛇的位置其实都是由网格线确定的。这些由网格线确定的小方格有它们自己的坐标系,如上图,最左上角的小方格坐标为(0,0),最右下角的坐标为(31,23)。

初始代码 1.#贪吃蛇游戏 2.#关注码趣学院 3. 4. 5. 6.import random,pygame,sys 7.from pygame.locals import* 8. 9.FPS=15 10.WINDOWWIDTH=640 11.WINDOWHEIGHT=480 12.CELLSIZE=20 13.assert WINDOWWIDTH%CELLSIZE==0,"Window width must be a multiple of cell size." 14.assert WINDOWHEIGHT%CELLSIZE==0,"Window height must be a multiple of cell size." 15.CELLWIDTH=int(WINDOWWIDTH/CELLSIZE) 16.CELLHEIGHT=int(WINDOWHEIGHT/CELLSIZE) 上面的代码设定了游戏的常量(constant variables),这些量在游戏进行的过程中将不会被改变。小方格的边长被储存在变量CELLSIZE中。assert语句(第13,14行)确保小方格的尺寸能够和游戏窗口完美契合。例如,如果变量CELLSIZE为10,而游戏窗口的宽WINDOWWIDTH和高WINDOWHEIGHT都被设置为15,那么整个游戏窗口只能放进1.5个小方格。assert语句确保窗口中的小方格数量为整数。 18.#R红G绿B蓝 19.WHITE=(255,255,255) 20.BLACK=(0,0,0) 21.RED=(255,0,0) 22.GREEN=(0,255,0)

小游戏代码