免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2791 | 回复: 1

[原创]python打小球游戏 [复制链接]

论坛徽章:
0
发表于 2007-03-21 16:31 |显示全部楼层
去年国庆节写的

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###############################################################################
  4. # Brick & Ball in Python Script                                               #
  5. # by Jerry Fleming <jerryfleming2006@gmail.com>                               #
  6. #                                                                             #
  7. # This is a small game inspired from similar one in Motorola Mobile C289,     #
  8. # and my first game in Python Script :) As I am a newbie to Python script,    #
  9. # please tell me if you have a better implementation or any suggestions.      #
  10. #                                                                             #
  11. # CONVENSIONS:                                                                #
  12. # Variable i and j stards for the row and column of bricks, while x and y     #
  13. # indicates its coordinates.                                                  #
  14. #                                                                             #
  15. # HISTORY:                                                                    #
  16. # 2006-10-01: second (current) version with tkinter                           #
  17. # 2006-04-19: first version with curses                                       #
  18. #                                                                             #
  19. # TODO:                                                                       #
  20. # Nothing to do right now :) If you have any ideas to improve or enhance it,  #
  21. # please contact me.                                                          #
  22. ###############################################################################

  23. from Tkinter import *
  24. from tkMessageBox import askyesno, showinfo
  25. from string import split
  26. from random import randint

  27. # globals for bricks (adjust these values for different board size) {{{
  28. ROWS = 5
  29. COLS = 10 # the row and column of bricks to be displayed
  30. WIDTH = 40
  31. HEIGHT = 15 # the size of bricks
  32. GAP = 8 # the interval between rows and columns of bricks, and between bricks
  33.         # and the play board
  34. DIAMETER = 10 # the DIAMETER of the ball
  35. SPEED = 10 # normal speed of ball
  36. BGCOLOR = '#a586ca'
  37. FILLCOLOR = '#000000'
  38. LINECOLOR = '#000000'
  39. GAPCOLOR = '#ff0000'
  40. # the following are automatically updated, do not edit
  41. BOARD_WIDTH = (WIDTH + GAP) * COLS + GAP # the width of the board
  42. BOARD_HEIGHT = (HEIGHT + GAP) * ROWS * 3 # the height of the board
  43. CNT = ROWS * COLS # total number of bricks
  44. USAGE = "Use left or right arrow to move the pad so as to bounce the ball to hit bricks and score."
  45. # }}} globals

  46. # functions {{{
  47. def movePad(event): # {{{
  48.         '''
  49.         Move the pad to catch the ball. This is the only user input.
  50.         '''
  51.         global pad, move
  52.         if event.keysym == 'Left':
  53.                 move = -10
  54.         if event.keysym == 'Right':
  55.                 move = 10
  56.         pad = pad + move
  57.         if pad < - GAP/2:
  58.                 move = 0
  59.                 pad = - GAP/2
  60.         if pad > BOARD_WIDTH - WIDTH + GAP/2:
  61.                 move = 0
  62.                 pad = BOARD_WIDTH - WIDTH + GAP/2
  63.         board.move(padID, move, 0)
  64. # }}} def movePad

  65. def moveBall(): # {{{
  66.         '''
  67.         Move the ball to a direction continuously.
  68.         '''
  69.         global CNT
  70.         board.move(ballID, direction[0], direction[1])
  71.         ball[0] = ball[0] + direction[0]
  72.         ball[1] = ball[1] + direction[1]
  73.        
  74.         hits = board.find_overlapping(
  75.                 ball[0], ball[1],
  76.                 ball[0] + DIAMETER, ball[1] + DIAMETER
  77.         )
  78.         # delete the brick if hit
  79.         for brick in hits:
  80.                 if brick == ballID: continue
  81.                 elif brick == padID: bounceBall()
  82.                 else:
  83.                         board.delete(brick)
  84.                         CNT = CNT - 1
  85.                         if CNT == 0: quitGame('Level')
  86.                         direction[1] = - direction[1]
  87.                         SCORE.set(SCORE.get() + SPEED/10)
  88.         # hit right edge
  89.         if ball[0] + DIAMETER >= BOARD_WIDTH:
  90.                 direction[0] = - direction[0]
  91.         # hit left edge
  92.         if ball[0] <= 0:
  93.                 direction[0] = - direction[0]
  94.         # hit top edge
  95.         if ball[1] <= 0:
  96.                 direction[1] = - direction[1]
  97.         # hit the bottom: game over
  98.         if ball[1] + DIAMETER >= BOARD_HEIGHT:
  99.                 quitGame('Over')
  100.         if STATE.get() == 'Normal': root.after(SPEED, moveBall)
  101. # }}} def moveBall

  102. def bounceBall(): # {{{
  103.         # hit pad from left
  104.         if direction[0] > 0 and ball[0] + DIAMETER <= pad + direction[0]:
  105.                 direction[0] = - abs(direction[0])
  106.         # hit pad from right
  107.         if direction[0] < 0 and ball[0] >= pad + WIDTH + direction[0]:
  108.                 direction[0] =  abs(direction[0])
  109.         direction[1] = - abs(direction[1])
  110. # }}} def bounceBall

  111. def quitGame(msg='Quit'): # {{{
  112.         '''
  113.         Set the game state to and confirm quitting.
  114.         '''
  115.         STATE.set(msg)
  116.         if msg == 'Quit' and not askyesno(msg, 'Are you sure to quit the game?'):
  117.                 STATE.set('Normal')
  118.                 moveBall()
  119.         elif msg == 'Level' and askyesno(msg, 'Do you want to continue?'):
  120.                 STATE.set('Normal')
  121.                 moveBall()
  122.                 startGame()
  123.         else:
  124.                 if msg == 'Over':
  125.                         showinfo('Game Over', 'Game is over. You need more practice!')
  126.                 root.destroy()
  127.                 root.quit()
  128. # }}} def quitGame

  129. def pauseGame(): # {{{
  130.         if PAUSE.get() == 'Pause':
  131.                 PAUSE.set('Resume')
  132.                 STATE.set('Pause')
  133.         elif PAUSE.get() == 'Resume':
  134.                 PAUSE.set('Pause')
  135.                 STATE.set('Normal')
  136.                 moveBall()
  137. # }}} def pauseGame

  138. def startGame(): # {{{
  139.         '''
  140.         Start a new session of the game.
  141.         '''
  142.         global ball, pad, direction
  143.         STATE.set('Normal')
  144.         PAUSE.set('Pause')
  145.         for i in range(1, ROWS + 1):
  146.                 for j in range(1, COLS + 1):
  147.                         bricks[i][j] = board.create_rectangle(
  148.                                 j * (WIDTH + GAP) - WIDTH + GAP/2, i * (HEIGHT + GAP) - HEIGHT,
  149.                                 j * (WIDTH + GAP), i * (HEIGHT + GAP),
  150.                                 outline=LINECOLOR, fill=FILLCOLOR, stipple='gray25', width=1
  151.                         )
  152.         pad = randint(WIDTH, BOARD_WIDTH - WIDTH)
  153.         ball[1] = BOARD_HEIGHT - DIAMETER * 3
  154.         ball[0] = randint(DIAMETER, BOARD_WIDTH - DIAMETER)
  155.         while abs(ball[0] - pad) < DIAMETER:
  156.                 ball[0] = randint(DIAMETER, BOARD_WIDTH - DIAMETER)
  157.         board.coords(padID, pad, BOARD_HEIGHT - HEIGHT, pad + WIDTH, BOARD_HEIGHT)
  158.         board.coords(ballID, ball[0], ball[1],
  159.                         ball[0] + DIAMETER, ball[1] + DIAMETER)
  160.         direction = [1, -1]
  161. # }}} def startGame
  162. # }}} functions

  163. # window initialization {{{
  164. root = Tk()
  165. root.title("Brick & Ball - a Python Game")
  166. root.geometry = str(BOARD_WIDTH + 100) + 'x' + str(BOARD_HEIGHT)
  167. root.resizable(width = False, height = False)
  168. root.iconbitmap('geofuture16.ico')
  169. SCORE = IntVar(root) # score over sessions
  170. STATE = StringVar(root) # game state: 0 for normal, 1 for pause
  171. PAUSE = StringVar(root) # switch to pause and resume
  172. board = Canvas( root, width = BOARD_WIDTH,
  173.         height = BOARD_HEIGHT, borderwidth = 1,
  174.         background = BGCOLOR, highlightbackground = GAPCOLOR)
  175. board.pack(side = LEFT)
  176. panel = Frame(
  177.         root, width = 100, height = BOARD_HEIGHT, borderwidth = 1,
  178.         background = BGCOLOR, highlightthickness = 2,
  179.         highlightbackground = GAPCOLOR)
  180. panel.pack(side = RIGHT, fill=Y)
  181. ballID = board.create_oval(
  182.         0, 0, DIAMETER, DIAMETER,
  183.         outline=LINECOLOR, fill=FILLCOLOR, width=1)
  184. padID = board.create_rectangle(
  185.         0, 0, WIDTH, HEIGHT,
  186.         outline=LINECOLOR, fill=FILLCOLOR, width=1)
  187. txt1 = Label(
  188.         panel, text='STATE', font=('Arial', '13', 'bold'),
  189.         anchor=CENTER, background=BGCOLOR, foreground=FILLCOLOR)
  190. txt1.pack()
  191. txtState = Label(
  192.         panel, textvariable=STATE, font=('Arial', '13'),
  193.         anchor=CENTER, background=GAPCOLOR, foreground=FILLCOLOR)
  194. txtState.pack()
  195. txt2 = Label(
  196.         panel, text='SCORE', font=('Arial', '13', 'bold'),
  197.         anchor=CENTER, background=BGCOLOR, foreground=FILLCOLOR)
  198. txt2.pack()
  199. txtScore = Label(
  200.         panel, textvariable=SCORE, font=('Arial', '13'), anchor=CENTER,
  201.         background=GAPCOLOR, foreground=FILLCOLOR)
  202. txtScore.pack()
  203. txt3 = Label(
  204.         panel, text='AUTHOR', font=('Arial', '13', 'bold'),
  205.         anchor=CENTER, background=BGCOLOR, foreground=FILLCOLOR)
  206. txt3.pack()
  207. txt3t = Label(
  208.         panel, text="Jerry\nFleming\n" + u'\u90b5\u52a0\u8d85',
  209.         font=('Arial', '13'), anchor=CENTER,
  210.         background=GAPCOLOR, foreground=FILLCOLOR)
  211. txt3t.pack()
  212. txt4 = Label(panel, text=USAGE, anchor=CENTER,
  213.                 wraplength = 100, background=BGCOLOR, foreground=FILLCOLOR)
  214. txt4.pack()
  215. btn = Button(panel, textvariable=PAUSE, font=('Arial', '10', 'bold'),
  216.                 pady = 2, command=pauseGame)
  217. btn.pack()
  218. root.protocol('WM_DELETE_WINDOW', quitGame)
  219. board.bind_all('<Right>', movePad)
  220. board.bind_all('<Left>', movePad)
  221. # global marks for ball and pad
  222. ball = [0, BOARD_HEIGHT - DIAMETER]
  223. pad = 0
  224. direction = [0, 0]
  225. move = 0
  226. bricks = [ [1 for j in range(COLS + 1)] for i in range(ROWS + 1)]
  227. # }}} window initialization

  228. # game starts here {{{
  229. if __name__ == "__main__":
  230.         startGame()
  231.         moveBall()
  232.         root.mainloop()
  233. # }}} game start

  234. # mode line {{{
  235. # Local variables:
  236. # tab-width: 3
  237. # c-basic-offset: 3
  238. # End:
  239. #
  240. # vim: tw=80:sw=3:ts=3:ft=python:fdm=marker:
  241. # }}}

复制代码

[ 本帖最后由 jerryfleming 于 2007-3-22 11:52 编辑 ]

论坛徽章:
0
发表于 2007-03-21 19:47 |显示全部楼层
支持。。谢谢楼主的源码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP