当前位置:   article > 正文

python编写小游戏详细教程,python编程小游戏代码_python游戏编程

python游戏编程

本篇文章给大家谈谈一些简单好玩的python编程游戏,以及python编写的入门简单小游戏,希望对各位有所帮助,不要忘了收藏本站喔。

这些游戏你玩过几个?

1.贪吃蛇

游戏规则:使用方向键控制蛇去吃球。每吃一次球,蛇身就长出一格python画六瓣花。吃到自己或者出界游戏结束。

  1. from random import randrange
  2. from turtle import *
  3. from freegames import square, vector
  4. food = vector(0, 0)
  5. snake = [vector(10, 0)]
  6. aim = vector(0, -10)
  7. def change(x, y):
  8. """Change snake direction."""
  9. aim.x = x
  10. aim.y = y
  11. def inside(head):
  12. """Return True if head inside boundaries."""
  13. return -200 < head.x < 190 and -200 < head.y < 190
  14. def move():
  15. """Move snake forward one segment."""
  16. head = snake[-1].copy()
  17. head.move(aim)
  18. if not inside(head) or head in snake:
  19. square(head.x, head.y, 9, 'red')
  20. update()
  21. return
  22. snake.append(head)
  23. if head == food:
  24. print('Snake:', len(snake))
  25. food.x = randrange(-15, 15) * 10
  26. food.y = randrange(-15, 15) * 10
  27. else:
  28. snake.pop(0)
  29. clear()
  30. for body in snake:
  31. square(body.x, body.y, 9, 'black')
  32. square(food.x, food.y, 9, 'green')
  33. update()
  34. ontimer(move, 100)
  35. setup(420, 420, 370, 0)
  36. hideturtle()
  37. tracer(False)
  38. listen()
  39. onkey(lambda: change(10, 0), 'Right')
  40. onkey(lambda: change(-10, 0), 'Left')
  41. onkey(lambda: change(0, 10), 'Up')
  42. onkey(lambda: change(0, -10), 'Down')
  43. move()
  44. done()

游戏演示:

在这里插入图片描述

2.吃豆人

游戏规则:用箭头导航控制黄色吃豆人吃掉所有白色食物,若被红色的鬼魂抓住,游戏结束。

  1. from random import choice
  2. from turtle import *
  3. from freegames import floor, vector
  4. state = {'score': 0}
  5. path = Turtle(visible=False)
  6. writer = Turtle(visible=False)
  7. aim = vector(5, 0)
  8. pacman = vector(-40, -80)
  9. ghosts = [
  10. [vector(-180, 160), vector(5, 0)],
  11. [vector(-180, -160), vector(0, 5)],
  12. [vector(100, 160), vector(0, -5)],
  13. [vector(100, -160), vector(-5, 0)],
  14. ]
  15. # fmt: off
  16. tiles = [
  17. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  18. 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  19. 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  20. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  21. 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  22. 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
  23. 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  24. 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  25. 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  26. 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  27. 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  28. 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  29. 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  30. 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0,
  31. 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
  32. 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
  33. 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  34. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  35. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  36. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  37. ]
  38. # fmt: on
  39. def square(x, y):
  40. """Draw square using path at (x, y)."""
  41. path.up()
  42. path.goto(x, y)
  43. path.down()
  44. path.begin_fill()
  45. for count in range(4):
  46. path.forward(20)
  47. path.left(90)
  48. path.end_fill()
  49. def offset(point):
  50. """Return offset of point in tiles."""
  51. x = (floor(point.x, 20) + 200) / 20
  52. y = (180 - floor(point.y, 20)) / 20
  53. index = int(x + y * 20)
  54. return index
  55. def valid(point):
  56. """Return True if point is valid in tiles."""
  57. index = offset(point)
  58. if tiles[index] == 0:
  59. return False
  60. index = offset(point + 19)
  61. if tiles[index] == 0:
  62. return False
  63. return point.x % 20 == 0 or point.y % 20 == 0
  64. def world():
  65. """Draw world using path."""
  66. bgcolor('black')
  67. path.color('blue')
  68. for index in range(len(tiles)):
  69. tile = tiles[index]
  70. if tile > 0:
  71. x = (index % 20) * 20 - 200
  72. y = 180 - (index // 20) * 20
  73. square(x, y)
  74. if tile == 1:
  75. path.up()
  76. path.goto(x + 10, y + 10)
  77. path.dot(2, 'white')
  78. def move():
  79. """Move pacman and all ghosts."""
  80. writer.undo()
  81. writer.write(state['score'])
  82. clear()
  83. if valid(pacman + aim):
  84. pacman.move(aim)
  85. index = offset(pacman)
  86. if tiles[index] == 1:
  87. tiles[index] = 2
  88. state['score'] += 1
  89. x = (index % 20) * 20 - 200
  90. y = 180 - (index // 20) * 20
  91. square(x, y)
  92. up()
  93. goto(pacman.x + 10, pacman.y + 10)
  94. dot(20, 'yellow')
  95. for point, course in ghosts:
  96. if valid(point + course):
  97. point.move(course)
  98. else:
  99. options = [
  100. vector(5, 0),
  101. vector(-5, 0),
  102. vector(0, 5),
  103. vector(0, -5),
  104. ]
  105. plan = choice(options)
  106. course.x = plan.x
  107. course.y = plan.y
  108. up()
  109. goto(point.x + 10, point.y + 10)
  110. dot(20, 'red')
  111. update()
  112. for point, course in ghosts:
  113. if abs(pacman - point) < 20:
  114. return
  115. ontimer(move, 100)
  116. def change(x, y):
  117. """Change pacman aim if valid."""
  118. if valid(pacman + vector(x, y)):
  119. aim.x = x
  120. aim.y = y
  121. setup(420, 420, 370, 0)
  122. hideturtle()
  123. tracer(False)
  124. writer.goto(160, 160)
  125. writer.color('white')
  126. writer.write(state['score'])
  127. listen()
  128. onkey(lambda: change(5, 0), 'Right')
  129. onkey(lambda: change(-5, 0), 'Left')
  130. onkey(lambda: change(0, 5), 'Up')
  131. onkey(lambda: change(0, -5), 'Down')
  132. world()
  133. move()
  134. done()

游戏演示:

在这里插入图片描述

3.加农炮

游戏规则:点击屏幕发射炮弹。炮弹在它的路径上弹出蓝色气球。在气球穿过屏幕之前把它们全部弹出。

  1. from random import randrange
  2. from turtle import *
  3. from freegames import vector
  4. ball = vector(-200, -200)
  5. speed = vector(0, 0)
  6. targets = []
  7. def tap(x, y):
  8. """Respond to screen tap."""
  9. if not inside(ball):
  10. ball.x = -199
  11. ball.y = -199
  12. speed.x = (x + 200) / 25
  13. speed.y = (y + 200) / 25
  14. def inside(xy):
  15. """Return True if xy within screen."""
  16. return -200 < xy.x < 200 and -200 < xy.y < 200
  17. def draw():
  18. """Draw ball and targets."""
  19. clear()
  20. for target in targets:
  21. goto(target.x, target.y)
  22. dot(20, 'blue')
  23. if inside(ball):
  24. goto(ball.x, ball.y)
  25. dot(6, 'red')
  26. update()
  27. def move():
  28. """Move ball and targets."""
  29. if randrange(40) == 0:
  30. y = randrange(-150, 150)
  31. target = vector(200, y)
  32. targets.append(target)
  33. for target in targets:
  34. target.x -= 0.5
  35. if inside(ball):
  36. speed.y -= 0.35
  37. ball.move(speed)
  38. dupe = targets.copy()
  39. targets.clear()
  40. for target in dupe:
  41. if abs(target - ball) > 13:
  42. targets.append(target)
  43. draw()
  44. for target in targets:
  45. if not inside(target):
  46. return
  47. ontimer(move, 50)
  48. setup(420, 420, 370, 0)
  49. hideturtle()
  50. up()
  51. tracer(False)
  52. onscreenclick(tap)
  53. move()
  54. done()

游戏演示:

在这里插入图片描述

4.四子棋

游戏规则:单击行可放置光盘。第一个垂直、水平或对角连接四张光盘的玩家获胜。

  1. from turtle import *
  2. from freegames import line
  3. turns = {'red': 'yellow', 'yellow': 'red'}
  4. state = {'player': 'yellow', 'rows': [0] * 8}
  5. def grid():
  6. """Draw Connect Four grid."""
  7. bgcolor('light blue')
  8. for x in range(-150, 200, 50):
  9. line(x, -200, x, 200)
  10. for x in range(-175, 200, 50):
  11. for y in range(-175, 200, 50):
  12. up()
  13. goto(x, y)
  14. dot(40, 'white')
  15. update()
  16. def tap(x, y):
  17. """Draw red or yellow circle in tapped row."""
  18. player = state['player']
  19. rows = state['rows']
  20. row = int((x + 200) // 50)
  21. count = rows[row]
  22. x = ((x + 200) // 50) * 50 - 200 + 25
  23. y = count * 50 - 200 + 25
  24. up()
  25. goto(x, y)
  26. dot(40, player)
  27. update()
  28. rows[row] = count + 1
  29. state['player'] = turns[player]
  30. setup(420, 420, 370, 0)
  31. hideturtle()
  32. tracer(False)
  33. grid()
  34. onscreenclick(tap)
  35. done()

游戏演示:

在这里插入图片描述

5. Fly Bird

游戏规则:点击屏幕来拍打鸟的翅膀。飞过屏幕被黑色乌鸦碰到,游戏结束。

  1. from random import *
  2. from turtle import *
  3. from freegames import vector
  4. bird = vector(0, 0)
  5. balls = []
  6. def tap(x, y):
  7. """Move bird up in response to screen tap."""
  8. up = vector(0, 30)
  9. bird.move(up)
  10. def inside(point):
  11. """Return True if point on screen."""
  12. return -200 < point.x < 200 and -200 < point.y < 200
  13. def draw(alive):
  14. """Draw screen objects."""
  15. clear()
  16. goto(bird.x, bird.y)
  17. if alive:
  18. dot(10, 'green')
  19. else:
  20. dot(10, 'red')
  21. for ball in balls:
  22. goto(ball.x, ball.y)
  23. dot(20, 'black')
  24. update()
  25. def move():
  26. """Update object positions."""
  27. bird.y -= 5
  28. for ball in balls:
  29. ball.x -= 3
  30. if randrange(10) == 0:
  31. y = randrange(-199, 199)
  32. ball = vector(199, y)
  33. balls.append(ball)
  34. while len(balls) > 0 and not inside(balls[0]):
  35. balls.pop(0)
  36. if not inside(bird):
  37. draw(False)
  38. return
  39. for ball in balls:
  40. if abs(ball - bird) < 15:
  41. draw(False)
  42. return
  43. draw(True)
  44. ontimer(move, 50)
  45. setup(420, 420, 370, 0)
  46. hideturtle()
  47. up()
  48. tracer(False)
  49. onscreenclick(tap)
  50. move()
  51. done()

游戏演示:

在这里插入图片描述

6.记忆:数字对拼图游戏(欢迎挑战!用时:2min)

游戏规则:单击方格用于显示数字。匹配两个数字,方格将显示从而显示图像。

  1. from random import *
  2. from turtle import *
  3. from freegames import path
  4. car = path('car.gif')
  5. tiles = list(range(32)) * 2
  6. state = {'mark': None}
  7. hide = [True] * 64
  8. def square(x, y):
  9. """Draw white square with black outline at (x, y)."""
  10. up()
  11. goto(x, y)
  12. down()
  13. color('black', 'white')
  14. begin_fill()
  15. for count in range(4):
  16. forward(50)
  17. left(90)
  18. end_fill()
  19. def index(x, y):
  20. """Convert (x, y) coordinates to tiles index."""
  21. return int((x + 200) // 50 + ((y + 200) // 50) * 8)
  22. def xy(count):
  23. """Convert tiles count to (x, y) coordinates."""
  24. return (count % 8) * 50 - 200, (count // 8) * 50 - 200
  25. def tap(x, y):
  26. """Update mark and hidden tiles based on tap."""
  27. spot = index(x, y)
  28. mark = state['mark']
  29. if mark is None or mark == spot or tiles[mark] != tiles[spot]:
  30. state['mark'] = spot
  31. else:
  32. hide[spot] = False
  33. hide[mark] = False
  34. state['mark'] = None
  35. def draw():
  36. """Draw image and tiles."""
  37. clear()
  38. goto(0, 0)
  39. shape(car)
  40. stamp()
  41. for count in range(64):
  42. if hide[count]:
  43. x, y = xy(count)
  44. square(x, y)
  45. mark = state['mark']
  46. if mark is not None and hide[mark]:
  47. x, y = xy(mark)
  48. up()
  49. goto(x + 2, y)
  50. color('black')
  51. write(tiles[mark], font=('Arial', 30, 'normal'))
  52. update()
  53. ontimer(draw, 100)
  54. shuffle(tiles)
  55. setup(420, 420, 370, 0)
  56. addshape(car)
  57. hideturtle()
  58. tracer(False)
  59. onscreenclick(tap)
  60. draw()
  61. done()

游戏演示:

在这里插入图片描述

7.乒乓球

游戏规则:用键盘上下移动划桨,谁先丢失球,谁输!(左ws上下,右ik上下)

  1. from random import choice, random
  2. from turtle import *
  3. from freegames import vector
  4. def value():
  5. """Randomly generate value between (-5, -3) or (3, 5)."""
  6. return (3 + random() * 2) * choice([1, -1])
  7. ball = vector(0, 0)
  8. aim = vector(value(), value())
  9. state = {1: 0, 2: 0}
  10. def move(player, change):
  11. """Move player position by change."""
  12. state[player] += change
  13. def rectangle(x, y, width, height):
  14. """Draw rectangle at (x, y) with given width and height."""
  15. up()
  16. goto(x, y)
  17. down()
  18. begin_fill()
  19. for count in range(2):
  20. forward(width)
  21. left(90)
  22. forward(height)
  23. left(90)
  24. end_fill()
  25. def draw():
  26. """Draw game and move pong ball."""
  27. clear()
  28. rectangle(-200, state[1], 10, 50)
  29. rectangle(190, state[2], 10, 50)
  30. ball.move(aim)
  31. x = ball.x
  32. y = ball.y
  33. up()
  34. goto(x, y)
  35. dot(10)
  36. update()
  37. if y < -200 or y > 200:
  38. aim.y = -aim.y
  39. if x < -185:
  40. low = state[1]
  41. high = state[1] + 50
  42. if low <= y <= high:
  43. aim.x = -aim.x
  44. else:
  45. return
  46. if x > 185:
  47. low = state[2]
  48. high = state[2] + 50
  49. if low <= y <= high:
  50. aim.x = -aim.x
  51. else:
  52. return
  53. ontimer(draw, 50)
  54. setup(420, 420, 370, 0)
  55. hideturtle()
  56. tracer(False)
  57. listen()
  58. onkey(lambda: move(1, 20), 'w')
  59. onkey(lambda: move(1, -20), 's')
  60. onkey(lambda: move(2, 20), 'i')
  61. onkey(lambda: move(2, -20), 'k')
  62. draw()
  63. done()

游戏演示:

在这里插入图片描述

8.上课划水必备-井字游戏(我敢说100%的人都玩过)

游戏规则:点击屏幕放置一个X或O。连续连接三个,就赢了!

  1. from turtle import *
  2. from freegames import line
  3. def grid():
  4. """Draw tic-tac-toe grid."""
  5. line(-67, 200, -67, -200)
  6. line(67, 200, 67, -200)
  7. line(-200, -67, 200, -67)
  8. line(-200, 67, 200, 67)
  9. def drawx(x, y):
  10. """Draw X player."""
  11. line(x, y, x + 133, y + 133)
  12. line(x, y + 133, x + 133, y)
  13. def drawo(x, y):
  14. """Draw O player."""
  15. up()
  16. goto(x + 67, y + 5)
  17. down()
  18. circle(62)
  19. def floor(value):
  20. """Round value down to grid with square size 133."""
  21. return ((value + 200) // 133) * 133 - 200
  22. state = {'player': 0}
  23. players = [drawx, drawo]
  24. def tap(x, y):
  25. """Draw X or O in tapped square."""
  26. x = floor(x)
  27. y = floor(y)
  28. player = state['player']
  29. draw = players[player]
  30. draw(x, y)
  31. update()
  32. state['player'] = not player
  33. setup(420, 420, 370, 0)
  34. hideturtle()
  35. tracer(False)
  36. grid()
  37. update()
  38. onscreenclick(tap)
  39. done()

游戏演示:

在这里插入图片描述

9.将数字滑动到位的拼图游戏

游戏规则:单击靠近空正方形的方格以交换位置。将所有数字从左到右按顺序排列。

  1. from random import *
  2. from turtle import *
  3. from freegames import floor, vector
  4. tiles = {}
  5. neighbors = [
  6. vector(100, 0),
  7. vector(-100, 0),
  8. vector(0, 100),
  9. vector(0, -100),
  10. ]
  11. def load():
  12. """Load tiles and scramble."""
  13. count = 1
  14. for y in range(-200, 200, 100):
  15. for x in range(-200, 200, 100):
  16. mark = vector(x, y)
  17. tiles[mark] = count
  18. count += 1
  19. tiles[mark] = None
  20. for count in range(1000):
  21. neighbor = choice(neighbors)
  22. spot = mark + neighbor
  23. if spot in tiles:
  24. number = tiles[spot]
  25. tiles[spot] = None
  26. tiles[mark] = number
  27. mark = spot
  28. def square(mark, number):
  29. """Draw white square with black outline and number."""
  30. up()
  31. goto(mark.x, mark.y)
  32. down()
  33. color('black', 'white')
  34. begin_fill()
  35. for count in range(4):
  36. forward(99)
  37. left(90)
  38. end_fill()
  39. if number is None:
  40. return
  41. elif number < 10:
  42. forward(20)
  43. write(number, font=('Arial', 60, 'normal'))
  44. def tap(x, y):
  45. """Swap tile and empty square."""
  46. x = floor(x, 100)
  47. y = floor(y, 100)
  48. mark = vector(x, y)
  49. for neighbor in neighbors:
  50. spot = mark + neighbor
  51. if spot in tiles and tiles[spot] is None:
  52. number = tiles[mark]
  53. tiles[spot] = number
  54. square(spot, number)
  55. tiles[mark] = None
  56. square(mark, None)
  57. def draw():
  58. """Draw all tiles."""
  59. for mark in tiles:
  60. square(mark, tiles[mark])
  61. update()
  62. setup(420, 420, 370, 0)
  63. hideturtle()
  64. tracer(False)
  65. load()
  66. draw()
  67. onscreenclick(tap)
  68. done()

游戏演示:

在这里插入图片描述

10.迷宫(我己经晕了,你们来)

游戏规则:从一边移到另一边。轻触屏幕可跟踪从一侧到另一侧的路径。

  1. from random import random
  2. from turtle import *
  3. from freegames import line
  4. def draw():
  5. """Draw maze."""
  6. color('black')
  7. width(5)
  8. for x in range(-200, 200, 40):
  9. for y in range(-200, 200, 40):
  10. if random() > 0.5:
  11. line(x, y, x + 40, y + 40)
  12. else:
  13. line(x, y + 40, x + 40, y)
  14. update()
  15. def tap(x, y):
  16. """Draw line and dot for screen tap."""
  17. if abs(x) > 198 or abs(y) > 198:
  18. up()
  19. else:
  20. down()
  21. width(2)
  22. color('red')
  23. goto(x, y)
  24. dot(4)
  25. setup(420, 420, 370, 0)
  26. hideturtle()
  27. tracer(False)
  28. draw()
  29. onscreenclick(tap)
  30. done()

游戏演示:

在这里插入图片描述

结语

以上就是今天的小游戏分享了,后续出下篇。
关注我咱们下期再见!!

文章知识点与官方知识档案匹配,可进一步学习相关知识
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/546642
推荐阅读
相关标签
  

闽ICP备14008679号