python pygame实现2048游戏

时间:2022-11-27 22:39:40

实现2048相对来说比较简单,用4*4的二维数组保存地图,pygame.key.get_pressed()获取键盘操作,详见代码。

效果图

python pygame实现2048游戏

python pygame实现2048游戏

代码

python" id="highlighter_270349">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# -*- coding: utf-8 -*-
#!/usr/bin/python
'''
created on may 31, 2014
@author: yuanzi
'''
import random
import sys
import pygame
from pygame.locals import *
 
pixel = 150
score_pixel = 100
size = 4
 
# 地图的类
class map:
  def __init__(self, size):
    self.size = size
    self.score = 0
    self.map = [[0 for i in range(size)] for i in range(size)]
    self.add()
    self.add()
  
  # 新增2或4,有1/4概率产生4
  def add(self):
    while true:
      p = random.randint(0, self.size * self.size - 1)
      if self.map[p / self.size][p % self.size] == 0:
        x = random.randint(0, 3) > 0 and 2 or 4
        self.map[p / self.size][p % self.size] = x
        self.score += x
        break
  
  # 地图向左靠拢,其他方向的靠拢可以通过适当旋转实现,返回地图是否更新
  def adjust(self):
    changed = false
    for a in self.map:
      b = []
      last = 0
      for v in a:
        if v != 0:
          if v == last:
            b.append(b.pop() << 1)
            last = 0
          else:
            b.append(v)
            last = v
      b += [0] * (self.size - len(b))
      for i in range(self.size):
        if a[i] != b[i]:
          changed = true
      a[ : ] = b
    return changed
  
  # 逆时针旋转地图90度
  def rotate90(self):
    self.map = [[self.map[c][r] for c in range(self.size)] for r in reversed(range(self.size))]
  
  # 判断游戏结束
  def over(self):
    for r in range(self.size):
      for c in range(self.size):
        if self.map[r][c] == 0:
          return false
    for r in range(self.size):
      for c in range(self.size - 1):
        if self.map[r][c] == self.map[r][c + 1]:
          return false
    for r in range(self.size - 1):
      for c in range(self.size):
        if self.map[r][c] == self.map[r + 1][c]:
          return false
    return true
  
  def moveup(self):
    self.rotate90()
    if self.adjust():
      self.add()
    self.rotate90()
    self.rotate90()
    self.rotate90()
  
  def moveright(self):
    self.rotate90()
    self.rotate90()
    if self.adjust():
      self.add()
    self.rotate90()
    self.rotate90()
  
  def movedown(self):
    self.rotate90()
    self.rotate90()
    self.rotate90()
    if self.adjust():
      self.add()
    self.rotate90()
  
  def moveleft(self):
    if self.adjust():
      self.add()
 
# 更新屏幕
def show(map):
  for i in range(size):
    for j in range(size):
      # 背景颜色块
      screen.blit(map.map[i][j] == 0 and block[(i + j) % 2] or block[2 + (i + j) % 2], (pixel * j, pixel * i))
      # 数值显示
      if map.map[i][j] != 0:
        map_text = map_font.render(str(map.map[i][j]), true, (106, 90, 205))
        text_rect = map_text.get_rect()
        text_rect.center = (pixel * j + pixel / 2, pixel * i + pixel / 2)
        screen.blit(map_text, text_rect)
  # 分数显示
  screen.blit(score_block, (0, pixel * size))
  score_text = score_font.render((map.over() and "game over with score " or "score: ") + str(map.score), true, (106, 90, 205))
  score_rect = score_text.get_rect()
  score_rect.center = (pixel * size / 2, pixel * size + score_pixel / 2)
  screen.blit(score_text, score_rect)
  pygame.display.update()
 
map = map(size)
pygame.init()
screen = pygame.display.set_mode((pixel * size, pixel * size + score_pixel))
pygame.display.set_caption("2048")
block = [pygame.surface((pixel, pixel)) for i in range(4)]
# 设置颜色
block[0].fill((152, 251, 152))
block[1].fill((240, 255, 255))
block[2].fill((0, 255, 127))
block[3].fill((225, 255, 255))
score_block = pygame.surface((pixel * size, score_pixel))
score_block.fill((245, 245, 245))
# 设置字体
map_font = pygame.font.font(none, pixel * 2 / 3)
score_font = pygame.font.font(none, score_pixel * 2 / 3)
clock = pygame.time.clock()
show(map)
 
while not map.over():
  # 12为实验参数
  clock.tick(12)
  for event in pygame.event.get():
    if event.type == quit:
      sys.exit()
  # 接收玩家操作
  pressed_keys = pygame.key.get_pressed()
  if pressed_keys[k_w] or pressed_keys[k_up]:
    map.moveup()
  elif pressed_keys[k_s] or pressed_keys[k_down]:
    map.movedown()
  elif pressed_keys[k_a] or pressed_keys[k_left]:
    map.moveleft()
  elif pressed_keys[k_d] or pressed_keys[k_right]:
    map.moveright()
  show(map)
 
# 游戏结束
pygame.time.delay(3000)

后续可以考虑实现动画和ai。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u012730439/article/details/27839449