ChatGPT能成为编程学习利器吗?五分钟游戏编写揭秘!附全套教程

ChatGPT能成为编程学习利器吗?五分钟游戏编写揭秘!附全套教程

首页角色扮演代号DGame更新时间:2024-04-16

都说程序员要失业了!

我先不判断这句话的真假,先来看看我用ChatGPT仅仅五分钟写出的几个小游戏……

我尝试让Chat GPT帮我写一个魂斗罗,结果它歇菜了,还是写不出来的……

但是对于简单的游戏,还是游刃有余的!

俄 罗 斯方块写出来的代码,我只是简单的修改完善了一下,即可正常运行。

虽然Chat GPT可以提高程序员工作效率,这一点大家都有共识!

但我觉得Chat GPT完全可以胜任初级程序员的导师,而且是几乎是免费的。

对于个编程初学者来说,或许跟跟Chat GPT学 习 编程会是更好的选择!

来分享一下游戏撰写步骤,后面附可运行代码(贪吃蛇、俄罗斯方块、五子棋等)

1、先尝试下达游戏撰写命令

写完基本就可以运行了,竟然没有错。前提是你得配置好python以及pygame库。

python跟pygame的安装和配置教程 我知乎写的有,大家去我的文章里找。

2、问题调试

生成的代码是可以运行,但是蛇总是吃不到方块,所以需要调试。

而且它一次并不能搞定,继续问:

问了好多次,还是没办法运行。我就大概看了一下,代码发现其吃方块的逻辑有问题。

但是,我是老板,我可不能写代码,得让gpt继续写。

于是给它一些提示:

然后它立刻就明白了,把中间贪吃蛇吃东西的逻辑又写了一遍,返回了一部分代码,替换相关的代码后,游戏就可以正常玩了!(代码在最后!)

4、需求变更

如果你能一次性的说明需求最好,但是很多时候都得看了运行效果以后才能追加需求。

你可以成为一个苛刻的产品经理,作为一个程序员,把自己曾经受过的伤害都给chatGPT来一遍。

比如我让它在写五子棋游戏的时候,我是这样*!

是不是很爽?让干啥干啥,而且分分钟反馈。

5、关于常用配置

Gpt不但能写代码,分析bug,而且能教你更多的东西。

作为一个老C 人员,工作原因,很久没有写C 代码,最新的Visual Studio也不怎么会用。

前段时间,有个大学生要做一个编程课程设计,要求用C 写一个放烟花的程序。

我才临时给自己电脑装了最新的Visual studio,但是很多配置都不熟悉了,于是我就问ChatGPT

没想到,它回答的异常精准。

首先我发送了撰写C 游戏的指令:

其代码是一个裸C 代码,我想用visual studio 这个我熟悉的IDE,所以,我就问:

GPT就乖乖的又写了一个基于windows窗口的游戏程序。

我再问,如何运行呢? 其实我是忘记了创建何种类型的project……

其配置流程写的特别详细:

在Visual Studio中运行这个文件,首先确保你的Visual Studio已经安装并配置好。接下来,按照以下步骤进行操作: 1. **打开 Visual Studio:** 打开 Visual Studio,并确保你有一个项目或者创建一个新项目。 2. **创建新项目:** 如果你没有现有项目,可以选择创建一个新项目。在Visual Studio的菜单中,选择 "File" -> "New" -> "Project...". 3. **选择项目类型:** 在 "Create a new project" 对话框中,选择 "Empty Project" 或者 "Windows Desktop Wizard",然后点击 "Next". 4. **填写项目信息:** 输入项目的名称和位置,然后点击 "Create." 5. **添加源文件:** 在 Solution Explorer(解决方案资源管理器)中,右键点击 "Source Files",然后选择 "Add" -> "Existing Item...". 选择你的 C 源文件,然后点击 "Add." 6. **配置项目属性:** 在 Solution Explorer 中,右键点击你的项目,然后选择 "Properties." - 在 "Configuration Properties" -> "General" 中,确保 "Character Set" 设置为 "Use Unicode Character Set." - 在 "Configuration Properties" -> "Linker" -> "System" 中,确保 "Subsystem" 设置为 "Windows (/SUBSYSTEM:WINDOWS)." - 在 "Configuration Properties" -> "C/C " -> "Code Generation" 中,确保 "Runtime Library" 设置为 "Multi-threaded (/MT)." 7. **配置额外的依赖项:** 如果你在使用`graphics.h`和`dos.h`,你可能需要配置额外的依赖项。在 "Configuration Properties" -> "C/C " -> "General" 中,找到 "Additional Include Directories",并添加`C:\Turboc3\BGI`或你图形库的路径。 8. **添加音频文件:** 将你的音频文件(`explosion.wav`和`background_music.wav`)放置在项目的源代码文件夹中,或者你可以在 `PlaySound` 函数中指定完整路径。 9. **运行程序:** 在 Visual Studio 的工具栏中,选择 "Local Windows Debugger"(通常是一个绿色的运行按钮)来构建和运行你的程序。 这样就应该可以在 Visual Studio 中运行你的程序了。请注意,由于`graphics.h`和`dos.h`库在较新的编译器中可能无法正常使用,你可能需要使用Turbo C 等兼容的编译器来运行这个特定的图形程序。

出现未定义的bug,也可以直接问:

或者把运行或者编译错误直接扔给它,它也可以解决。

有问题继续:

最终只放了一只烟花,增加需求:

我想给工程增加graphics绘图库,忘记怎么加了,直接问题:

我想说,回答的真详细……

一对一老师都没这么详细!

6、关于常用配置

有了ChatGPT,对于初学编程的人员来说,简直是福音,比编程私教老师好太多了!

你可以咨询你想问的任何问题……

但话说回来了,它会写,并不代表你会写,你还得花时间学习,只是提高了你得学习效率。

不然它的对不对,好不好,你都没有判断能力。

对于日常程序员来说,可以让它帮们分析一些逻辑,或者构建一些我们不熟悉的软件逻辑。

比如构建一个可自定义线程数量的线程池:

这段代码的正确性我就不再验证了,目测至少基本逻辑出来了,适当调试后,即可学习甚至应用。

从这个案例可以得出结论:AI虽说不能完全替代程序员,但是回大大的压缩程序员的生存空间。

为什么?

因为之前三个人初级人员的活,现在一个人都可以搞定了,这是我笃信的事实!

好了,今天的分享就到这里,期望大家都赶紧把AI用起来,学习、找工作、加薪、晋升都很有用!

有问题的小伙伴关注、留言,会抽空一一回复!


来!奉上以上案例所有的代码!可运行的……

贪吃蛇的详细代码如下:

#贪吃蛇 import pygame import random import math # 初始化 Pygame pygame.init() # 设置屏幕宽度和高度 SCREEN_WIDTH, SCREEN_HEIGHT = 600, 400 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('snake Game') # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # 定义方向 UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 # 定义方块大小和初始位置 BLOCK_SIZE = 15 snake = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)] snake_direction = RIGHT snake_speed = 5 # 食物初始位置 food = (random.randint(0, (SCREEN_WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE, random.randint(0, (SCREEN_HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE) # 游戏结束标志 game_over = False game_font = pygame.font.Font(None, 36) # 游戏循环标志 running = True # 游戏主循环 clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_direction != DOWN: snake_direction = UP elif event.key == pygame.K_DOWN and snake_direction != UP: snake_direction = DOWN elif event.key == pygame.K_LEFT and snake_direction != RIGHT: snake_direction = LEFT elif event.key == pygame.K_RIGHT and snake_direction != LEFT: snake_direction = RIGHT if not game_over: # 移动蛇 x, y = snake[0] if snake_direction == UP: y -= BLOCK_SIZE elif snake_direction == DOWN: y = BLOCK_SIZE elif snake_direction == LEFT: x -= BLOCK_SIZE elif snake_direction == RIGHT: x = BLOCK_SIZE # 检查游戏结束条件(撞到边界或撞到自己) if x < 0 or x >= SCREEN_WIDTH or y < 0 or y >= SCREEN_HEIGHT or (x, y) in snake[1:]: game_over = True # 检查是否吃到食物 food_x, food_y = food distance = math.sqrt((x - food_x) ** 2 (y - food_y) ** 2) if distance < BLOCK_SIZE: # 当蛇头与食物距离小于方块大小时,判定为吃到食物 snake.append((x, y)) # 增加蛇的长度 food = (random.randint(0, (SCREEN_WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE, random.randint(0, (SCREEN_HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE) else: snake.pop() # 更新蛇的位置 snake.insert(0, (x, y)) # 绘制屏幕 screen.fill(BLACK) # 绘制食物 pygame.draw.rect(screen, RED, (food[0], food[1], BLOCK_SIZE, BLOCK_SIZE)) # 绘制蛇 for segment in snake: pygame.draw.rect(screen, GREEN, (segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE)) # 绘制游戏结束信息 if game_over: game_over_text = game_font.render('Game Over', True, WHITE) screen.blit(game_over_text, (SCREEN_WIDTH // 2 - 100, SCREEN_HEIGHT // 2)) # 更新屏幕 pygame.display.flip() # 控制游戏速度 clock.tick(snake_speed) # 退出游戏 pygame.quit()

五子棋的代码:

import pygame import sys # 初始化 Pygame pygame.init() # 设置屏幕宽度和高度 ROW_COUNT = 15 COLUMN_COUNT = 15 SQUARE_SIZE = 40 SCREEN_WIDTH = COLUMN_COUNT * SQUARE_SIZE SCREEN_HEIGHT = ROW_COUNT * SQUARE_SIZE 100 # 增加按钮显示区域高度 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Five in a Row') # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) BEIJING_COLOR = (205, 223, 218) # 北京色(自定义颜色) BUTTON_COLOR = (100, 100, 100) # 按钮颜色 # 初始化棋盘 board = [[0 for _ in range(COLUMN_COUNT)] for _ in range(ROW_COUNT)] # 游戏状态 game_over = False turn = 1 # 玩家1为黑子,玩家2为白子 winner = None # 绘制棋盘背景 def draw_board(): screen.fill(BEIJING_COLOR) # 更改背景色为北京色 for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.rect(screen, BLACK, (c * SQUARE_SIZE, r * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE), 1) # 绘制棋子 def draw_pieces(): for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == 1: pygame.draw.circle(screen, BLACK, (c * SQUARE_SIZE SQUARE_SIZE // 2, r * SQUARE_SIZE SQUARE_SIZE // 2), SQUARE_SIZE // 2 - 2) elif board[r][c] == 2: pygame.draw.circle(screen, WHITE, (c * SQUARE_SIZE SQUARE_SIZE // 2, r * SQUARE_SIZE SQUARE_SIZE // 2), SQUARE_SIZE // 2 - 2) # 检查胜利条件 def check_winner(row, col): directions = [(1, 0), (0, 1), (1, 1), (-1, 1)] # 水平、垂直、对角线方向 for d in directions: count = 1 for i in range(1, 5): r = row d[0] * i c = col d[1] * i if 0 <= r < ROW_COUNT and 0 <= c < COLUMN_COUNT and board[r][c] == board[row][col]: count = 1 else: break for i in range(1, 5): r = row - d[0] * i c = col - d[1] * i if 0 <= r < ROW_COUNT and 0 <= c < COLUMN_COUNT and board[r][c] == board[row][col]: count = 1 else: break if count >= 5: return True return False # 绘制重新开始按钮 def draw_button(): pygame.draw.rect(screen, BUTTON_COLOR, (0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100)) font = pygame.font.SysFont(None, 40) text = font.render("Restart", True, WHITE) screen.blit(text, (SCREEN_WIDTH // 2 - 60, SCREEN_HEIGHT - 70)) # 检查鼠标点击位置 def check_click(pos): global game_over, winner, turn, board x, y = pos if SCREEN_HEIGHT - 100 <= y <= SCREEN_HEIGHT: if 0 <= x <= SCREEN_WIDTH: game_over = False winner = None turn = 1 board = [[0 for _ in range(COLUMN_COUNT)] for _ in range(ROW_COUNT)] # 游戏主循环 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if not game_over: mouse_x, mouse_y = event.pos col = mouse_x // SQUARE_SIZE row = mouse_y // SQUARE_SIZE if board[row][col] == 0: board[row][col] = turn if check_winner(row, col): game_over = True winner = "Black" if turn == 1 else "White" turn = 3 - turn # 切换玩家回合 else: check_click(pygame.mouse.get_pos()) draw_board() draw_pieces() draw_button() if game_over: font = pygame.font.SysFont(None, 60) text = font.render(f"{winner} wins!", True, BLACK) screen.blit(text, (SCREEN_WIDTH // 2 - 120, SCREEN_HEIGHT // 2)) pygame.display.update()

球碰砖游戏的代码:

import pygame import random # 初始化 Pygame pygame.init() # 设置屏幕宽度和高度 SCREEN_WIDTH, SCREEN_HEIGHT = 600, 400 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Breakout Game') # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) # 定义板和球的初始位置、大小和速度 paddle_width, paddle_height = 100, 10 paddle_x, paddle_y = (SCREEN_WIDTH - paddle_width) // 2, SCREEN_HEIGHT - 2 * paddle_height paddle_speed = 10 ball_radius = 10 ball_x, ball_y = SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 ball_speed_x, ball_speed_y = 7, 7 # 定义砖块的行列数、大小和间距 brick_rows = 5 brick_cols = 8 brick_width = 70 brick_height = 20 brick_padding = 5 # 创建砖块 bricks = [] for row in range(brick_rows): for col in range(brick_cols): brick_x = col * (brick_width brick_padding) brick_padding brick_y = row * (brick_height brick_padding) brick_padding 50 bricks.append(pygame.Rect(brick_x, brick_y, brick_width, brick_height)) # 游戏结束标志 game_over = False # 游戏循环标志 running = True # 游戏主循环 clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if not game_over: # 移动挡板 keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and paddle_x > 0: paddle_x -= paddle_speed if keys[pygame.K_RIGHT] and paddle_x < SCREEN_WIDTH - paddle_width: paddle_x = paddle_speed # 移动球 ball_x = ball_speed_x ball_y = ball_speed_y # 球碰到边界的反弹 if ball_x <= ball_radius or ball_x >= SCREEN_WIDTH - ball_radius: ball_speed_x = -ball_speed_x if ball_y <= ball_radius: ball_speed_y = -ball_speed_y # 球碰到挡板的反弹 if ball_y >= paddle_y - ball_radius and paddle_x < ball_x < paddle_x paddle_width: ball_speed_y = -ball_speed_y # 球碰到砖块的处理 for brick in bricks: if brick.collidepoint(ball_x, ball_y): bricks.remove(brick) ball_speed_y = -ball_speed_y # 判断游戏是否结束 if ball_y >= SCREEN_HEIGHT - ball_radius: game_over = True # 绘制屏幕 screen.fill(BLACK) # 绘制挡板和球 pygame.draw.rect(screen, BLUE, (paddle_x, paddle_y, paddle_width, paddle_height)) pygame.draw.circle(screen, RED, (ball_x, ball_y), ball_radius) # 绘制砖块 for brick in bricks: pygame.draw.rect(screen, WHITE, brick) # 绘制游戏结束信息 if game_over: game_over_text = pygame.font.Font(None, 50).render('Game Over', True, WHITE) screen.blit(game_over_text, (SCREEN_WIDTH // 2 - 150, SCREEN_HEIGHT // 2)) # 更新屏幕 pygame.display.flip() # 控制游戏速度 clock.tick(10) # 退出游戏 pygame.quit()

俄罗斯方块的代码:

import pygame import random # 初始化游戏 pygame.init() # 设置游戏界面尺寸 screen_width = 400 screen_height = 500 play_width = 300 play_height = 600 block_size = 30 top_left_x = (screen_width - play_width) // 2 top_left_y = screen_height - play_height # 定义各种形状的方块 S = [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....']] Z = [['.....', '.....', '.00..', '..00.', '.....'], ['.....', '..0..', '.00..', '.0...', '.....']] I = [['..0..', '..0..', '..0..', '..0..', '.....'], ['.....', '0000.', '.....', '.....', '.....']] O = [['.....', '.....', '.00..', '.00..', '.....']] J = [['.....', '.0...', '.000.', '.....', '.....'], ['.....', '..00.', '..0..', '..0..', '.....'], ['.....', '.....', '.000.', '...0.', '.....'], ['.....', '..0..', '..0..', '.00..', '.....']] L = [['.....', '...0.', '.000.', '.....', '.....'], ['.....', '..0..', '..0..', '..00.', '.....'], ['.....', '.....', '.000.', '.0...', '.....'], ['.....', '.00..', '..0..', '..0..', '.....']] T = [['.....', '..0..', '.000.', '.....', '.....'], ['.....', '..0..', '..00.', '..0..', '.....'], ['.....', '.....', '.000.', '..0..', '.....'], ['.....', '..0..', '.00..', '..0..', '.....']] shapes = [S, Z, I, O, J, L, T] shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)] # 定义方块类 class Piece(object): def __init__(self, x, y, shape): self.x = x self.y = y self.shape = shape self.color = shape_colors[shapes.index(shape)] self.rotation = 0 # 创建游戏区域 def create_grid(locked_pos={}): grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)] for y in range(len(grid)): for x in range(len(grid[y])): if (x, y) in locked_pos: color = locked_pos[(x, y)] grid[y][x] = color return grid # 转换形状格式 def convert_shape_format(piece): positions = [] shape_format = piece.shape[piece.rotation % len(piece.shape)] for i, line in enumerate(shape_format): row = list(line) for j, column in enumerate(row): if column == '0': positions.append((piece.x j, piece.y i)) for i, pos in enumerate(positions): positions[i] = (pos[0] - 2, pos[1] - 4) return positions # 检查位置是否有效 def valid_space(piece, grid): accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0, 0, 0)] for i in range(20)] accepted_positions = [j for sub in accepted_positions for j in sub] formatted = convert_shape_format(piece) for pos in formatted: if pos not in accepted_positions: if pos[1] > -1: return False return True # 检查是否游戏结束 def check_lost(positions): for pos in positions: x, y = pos if y < 1: return True return False # 获取一个随机形状的方块 def get_shape(): return Piece(5, 0, random.choice(shapes)) # 绘制游戏区域的方块 def draw_grid(surface, grid): for y in range(len(grid)): for x in range(len(grid[y])): pygame.draw.rect(surface, grid[y][x], (top_left_x x * block_size, top_left_y y * block_size, block_size, block_size), 0) pygame.draw.line(surface, (128, 128, 128), (top_left_x, top_left_y y * block_size), (top_left_x play_width, top_left_y y * block_size)) for x in range(len(grid[y])): pygame.draw.line(surface, (128, 128, 128), (top_left_x x * block_size, top_left_y), (top_left_x x * block_size, top_left_y play_height)) # 绘制当前方块和已固定的方块 def draw_window(surface, grid): surface.fill((0, 0, 0)) pygame.font.init() font = pygame.font.SysFont('comicsans', 60) label = font.render('Tetris', 1, (255, 255, 255)) surface.blit(label, (top_left_x play_width / 2 - (label.get_width() / 2), 30)) for y in range(len(grid)): for x in range(len(grid[y])): pygame.draw.rect(surface, grid[y][x], (top_left_x x * block_size, top_left_y y * block_size, block_size, block_size), 0) pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width, play_height), 5) draw_grid(surface, grid) pygame.display.update() # 主游戏逻辑 def main(): locked_positions = {} grid = create_grid(locked_positions) change_piece = False run = True current_piece = get_shape() next_piece = get_shape() clock = pygame.time.Clock() fall_time = 0 fall_speed = 0.27 level_time = 0 score = 0 while run: grid = create_grid(locked_positions) fall_time = clock.get_rawtime() level_time = clock.get_rawtime() clock.tick() # 控制方块下落速度 if level_time / 1000 > 5: level_time = 0 if fall_speed > 0.12: fall_speed -= 0.005 if fall_time / 1000 > fall_speed: fall_time = 0 current_piece.y = 1 if not (valid_space(current_piece, grid)) and current_piece.y > 0: current_piece.y -= 1 change_piece = True for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: current_piece.x -= 1 if not valid_space(current_piece, grid): current_piece.x = 1 elif event.key == pygame.K_RIGHT: current_piece.x = 1 if not valid_space(current_piece, grid): current_piece.x -= 1 elif event.key == pygame.K_DOWN: current_piece.y = 1 if not valid_space(current_piece, grid): current_piece.y -= 1 elif event.key == pygame.K_UP: current_piece.rotation = 1 if not valid_space(current_piece, grid): current_piece.rotation -= 1 shape_pos = convert_shape_format(current_piece) for i in range(len(shape_pos)): x, y = shape_pos[i] if y > -1: grid[y][x] = current_piece.color if change_piece: for pos in shape_pos: p = (pos[0], pos[1]) locked_positions[p] = current_piece.color current_piece = next_piece next_piece = get_shape() change_piece = False score = 10 # 消除满行 for y in range(len(grid) - 1, -1, -1): row = grid[y] if (0, 0, 0) not in row: ind = y for x in range(len(row)): try: del locked_positions[(x, y)] except: continue for key in sorted(list(locked_positions), key=lambda x: x[1])[::-1]: x, y = key if y < ind: newKey = (x, y 1) locked_positions[newKey] = locked_positions.pop(key) draw_window(win, grid) # 游戏结束条件 if check_lost(locked_positions): run = False pygame.display.quit() quit() win = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Tetris')

main()

查看全文
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved