From ea62d60eb819a47b18a01ba6a49045fb32b5225f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AD=8F=E6=A2=93=E8=A8=80?= <14229776+weizy26@user.noreply.gitee.com> Date: Fri, 19 Jul 2024 06:39:11 +0000 Subject: [PATCH] Added client and server structure to save the current score and high score after each game. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 魏梓言 <14229776+weizy26@user.noreply.gitee.com> --- snakeServer.py | 38 ++++++++++++ snakeclient.py | 163 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 snakeServer.py create mode 100644 snakeclient.py diff --git a/snakeServer.py b/snakeServer.py new file mode 100644 index 0000000..b600a9b --- /dev/null +++ b/snakeServer.py @@ -0,0 +1,38 @@ +import socket +import pickle + +# 服务器地址和端口 +SERVER_IP = '127.0.0.1' +SERVER_PORT = 5555 + +# 保存最高分 +high_score = 0 + +def handle_client(client_socket): + global high_score + while True: + try: + data = client_socket.recv(4096) + if not data: + break + scores = pickle.loads(data) + if scores > high_score: + high_score = scores + client_socket.sendall(pickle.dumps(high_score)) + except: + break + client_socket.close() + +def main(): + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind((SERVER_IP, SERVER_PORT)) + server.listen(5) + print(f'Server listening on {SERVER_IP}:{SERVER_PORT}') + + while True: + client_socket, addr = server.accept() + print(f'Accepted connection from {addr}') + handle_client(client_socket) + +if __name__ == '__main__': + main() diff --git a/snakeclient.py b/snakeclient.py new file mode 100644 index 0000000..2fcaa35 --- /dev/null +++ b/snakeclient.py @@ -0,0 +1,163 @@ +import pygame +import socket +import pickle +import random +import sys + +# 全局定义 +SCREEN_X = 600 +SCREEN_Y = 600 +WHITE = (255, 255, 255) +GREEN = (20, 220, 39) +RED = (136, 0, 21) +BLACK = (0, 0, 0) + + +# 蛇类 +class Snake: + def __init__(self): + self.direction = pygame.K_RIGHT + self.body = [] + for x in range(5): + self.add_node() + + def add_node(self): + left, top = (0, 0) # 初始化在左上角 + if self.body: + left, top = (self.body[0].left, self.body[0].top) + node = pygame.Rect(left, top, 25, 25) + if self.direction == pygame.K_LEFT: + node.left -= 25 + elif self.direction == pygame.K_RIGHT: + node.left += 25 + elif self.direction == pygame.K_UP: + node.top -= 25 + elif self.direction == pygame.K_DOWN: + node.top += 25 + self.body.insert(0, node) + + def del_node(self): + self.body.pop() + + def is_dead(self): + if self.body[0].x < 0 or self.body[0].x >= SCREEN_X: + return True + if self.body[0].y < 0 or self.body[0].y >= SCREEN_Y: + return True + if self.body[0] in self.body[1:]: + return True + return False + + def move(self): + self.add_node() + self.del_node() + + def change_direction(self, curkey): + LR = [pygame.K_LEFT, pygame.K_RIGHT] + UD = [pygame.K_UP, pygame.K_DOWN] + if curkey in LR + UD: + if (curkey in LR) and (self.direction in LR): + return + if (curkey in UD) and (self.direction in UD): + return + self.direction = curkey + + +# 食物类 +class Food: + def __init__(self): + self.rect = pygame.Rect(-25, 0, 25, 25) + + def remove(self): + self.rect.x = -25 + + def set(self, snake_body): + if self.rect.x == -25: + while True: + pos_x = random.randint(0, (SCREEN_X // 25) - 1) * 25 + pos_y = random.randint(0, (SCREEN_Y // 25) - 1) * 25 + self.rect.left = pos_x + self.rect.top = pos_y + if self.rect not in snake_body: + break + + +def show_text(screen, pos, text, color, font_size=60, font_bold=False, font_italic=False): + cur_font = pygame.font.SysFont("宋体", font_size) + cur_font.set_bold(font_bold) + cur_font.set_italic(font_italic) + text_fmt = cur_font.render(text, 1, color) + screen.blit(text_fmt, pos) + + +def main(): + pygame.init() + screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) + pygame.display.set_caption('Snake Client') + clock = pygame.time.Clock() + + def connect_to_server(): + conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + conn.connect(('127.0.0.1', 5555)) + return conn + + conn = connect_to_server() + scores = 0 + is_dead = False + high_score = 0 + new_record = False + + snake = Snake() + food = Food() + + while True: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + sys.exit() + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_SPACE and is_dead: + conn.close() + return main() # 重新开始游戏并重新连接服务器 + snake.change_direction(event.key) + + if not is_dead: + scores += 1 + snake.move() + screen.fill(WHITE) + for rect in snake.body: + pygame.draw.rect(screen, GREEN, rect, 0) + + if snake.is_dead(): + is_dead = True + conn.sendall(pickle.dumps(scores)) + received_high_score = pickle.loads(conn.recv(4096)) + if scores > received_high_score: + new_record = True + high_score = scores + else: + new_record = False + high_score = received_high_score + + show_text(screen, (100, 200), 'YOU DEAD!', RED, 100) + show_text(screen, (150, 260), f'Your score: {scores}', BLACK, 30) + show_text(screen, (150, 300), f'Best score: {high_score}', BLACK, 30) + show_text(screen, (150, 380), 'Press space to try again...', BLACK, 30) + else: + if food.rect.colliderect(snake.body[0]): + scores += 50 + food.remove() + snake.add_node() + + food.set(snake.body) + pygame.draw.rect(screen, RED, food.rect, 0) + + show_text(screen, (50, 500), 'Scores: ' + str(scores), BLACK, 30) + show_text(screen, (50, 540), 'High Score: ' + str(high_score), BLACK, 30) + + pygame.display.update() + clock.tick(5) # 减慢蛇的移动速度,每秒5帧 + + +if __name__ == '__main__': + main() -- Gitee