生命游戏(c/python)

52 篇文章 0 订阅
37 篇文章 0 订阅

生命游戏的规则可简化为如下:
邻居个数为0、1、4、5、6、7、8时,则该细胞下次状态为死亡。
邻居个数为2时,则该细胞下次状态为复活。
邻居个数为3时,则该细胞下次状态为稳定。

c代码

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAXROW 10
#define MAXCOL 25
#define DEAD 0
#define ALIVE 1

int map[MAXROW][MAXCOL], newmap[MAXROW][MAXCOL];

void print_map();
void print_newmap();
void initmap();
int get_neighbor(int row, int col);
int main()
{
    char c;
    int row, col;
    initmap();
    while (1)
    {
        print_map();
        for (row = 0; row < MAXROW; row++)
        {
            for (col = 0; col < MAXCOL; col++)
            {
                switch (get_neighbor(row, col))
                {
                case 0:
                case 1:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                    newmap[row][col] = DEAD;
                    break;
                case 3:
                    newmap[row][col] = ALIVE;
                    break;
                case 2:
                    newmap[row][col] = map[row][col];
                    break;
                }
            }
        }
        print_newmap();
        printf("\nContinue next Generation ? ");
        getchar();
        c = toupper(getchar());
        if (c != 'Y')
            break;
    }

    system("pause");
    return 0;
}
void initmap()
{
    int i, j;
    for (i = 0; i < MAXROW; i++)
    {
        for (j = 0; j < MAXCOL; j++)
        {
            map[i][j] = DEAD;
        }
    }
    puts("Game of life Program");
    puts("Enter x, y where x, y is living cell");
    printf("0 <= x <= %d,0 <= y <= %d\n",
        MAXROW - 1, MAXCOL - 1);
    puts("Terminate with x, y = -1, -1");

    while (1)
    {
        scanf_s("%d%d", &i, &j);
        if (i >= 0 && i < MAXROW && j >= 0 && j < MAXCOL)
        {
            map[i][j] = ALIVE;
        }
        else if (i == -1 || j == -1)
        {
            break;
        }
        else
        {
            printf("(x,y)exceeds map range");
        }
    }
}

int get_neighbor(int row, int col)
{
    int count = 0;
    int i, j;
    for (i = row - 1; i <= row + 1; i++)
    {
        for (j = col - 1; j <= col + 1; j++)
        {
            if (i<0 || j<0 || i>MAXROW || j>MAXCOL)
                continue;
            if(map[i][j] == ALIVE)
                count++;
        }
    }
    if (map[i][j] == ALIVE)
    {
            count--;
    }
    return count;
}

void print_map()
{
    for (int i = 0; i < MAXROW; i++)
    {
        for (int j = 0; j < MAXCOL; j++)
        {
            if (map[i][j] == ALIVE)
            {
                putchar('#');
            }
            else
                putchar('-');
        }
        printf("\n");

    }
}

void print_newmap()
{
    for (int i = 0; i < MAXROW; i++)
    {
        for (int j = 0; j < MAXCOL; j++)
        {
            map[i][j] = newmap[i][j];
        }
    }
}

python代码

# -*- coding: utf-8 -*-
"""
Created on Sat Nov  4 20:22:59 2017

@author: yangwenbin
"""
import numpy as np 
Map=np.zeros((10,15))
new_map=np.zeros_like(Map)
def init_map():
    flag=True
    for col in range(10):
        for row in range(15):
            Map[col][row]=0  #0表示死亡,1表示活着,对所有位置进行初始化
            pass
        pass
    print("Game of life Program")
    print("Enter x,y where x,y is living cell")
    print("0 <= x <= %d,0 <= y <= %d"%(9, 14))
    print("Terminate with x, y = -1, -1")
    pass

    while flag:
        col = input("input col:")
        row = input("input row:")
        col=int(col)
        row=int(row)
        if col>=0 and col<9 and row >=0 and row <15:
            Map[col][row]=1
            pass
        elif col==-1 or row ==-1:
            break
        else:
            print("exceed map range")
def print_map():
    for col in range(10):
        for row in range(15):
            if Map[col][row]==1:
                print("#",end='')
                pass
            else:
                print("-",end='')
                pass
            pass
        print("\n")
        pass
    pass
def neighbor(col,row):
    count=0
    for i in range(col-1,col+2):
        for j in range(row-1,row+2):
            if i<10 and j<15 and Map[i][j]==1:
                count+=1
                continue
            pass
        pass
    if Map[col][row]==1:
        count-=1
        pass
    return count

def update_map(col,row):
    a=neighbor(col,row)
    if a!=2 and neighbor(col,row)!=3:
        new_map[col][row]=0
        pass
    elif neighbor(col,row)==2:
        new_map[col][row]=1
        pass
    else:
        new_map[col][row]=Map[col][row]
        pass
    pass
def copy_map():
    for i in range(10):
        for j in range(15):
            Map[i][j]=new_map[i][j]
            pass
        pass
    pass
if __name__=="__main__":
    init_map()
    while True:
        print_map()
        for col in range(10):
            for row in range(15):        
                update_map(col,row)
        copy_map()
        c=input("want to continue:")
        if c.upper()!='Y':
            break
        pass 
    pass 
好的,我可以为您提供一个基于Python生命游戏的图形界面实现。在这里,我们使用pygame库来创建图形化界面,并使用numpy库来处理生命游戏的逻辑。 首先,我们需要安装pygame和numpy库。可以使用以下命令进行安装: ``` pip install pygame numpy ``` 接下来,我们将创建一个游戏类,该类将包含所有游戏逻辑和图形化界面实现。在这个游戏中,我们将使用一个矩形网格来表示生命游戏的细胞。网格中每个单元格都可以是活着的或死亡的,具体取决于它周围的细胞数量。 以下是完整的代码: ```python import pygame import numpy as np class GameOfLife: def __init__(self, width=640, height=480, cell_size=10, speed=10): self.width = width self.height = height self.cell_size = cell_size self.speed = speed pygame.init() pygame.display.set_caption("Game of Life") self.screen = pygame.display.set_mode((self.width, self.height)) self.cells = np.zeros((self.width // self.cell_size, self.height // self.cell_size), dtype=bool) self.running = False def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() col, row = x // self.cell_size, y // self.cell_size self.cells[col, row] = not self.cells[col, row] elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.running = not self.running elif event.key == pygame.K_c: self.cells = np.zeros((self.width // self.cell_size, self.height // self.cell_size), dtype=bool) elif event.key == pygame.K_r: self.cells = np.random.choice([False, True], size=(self.width // self.cell_size, self.height // self.cell_size), p=[0.8, 0.2]) def get_neighbors(self, x, y): left, right = max(0, x-1), min(x+2, self.cells.shape[0]) top, bottom = max(0, y-1), min(y+2, self.cells.shape[1]) return self.cells[left:right, top:bottom] def update(self): new_cells = np.copy(self.cells) for i in range(self.cells.shape[0]): for j in range(self.cells.shape[1]): neighbors = self.get_neighbors(i, j) count = np.count_nonzero(neighbors) - self.cells[i, j] if self.cells[i, j] and (count < 2 or count > 3): new_cells[i, j] = False elif not self.cells[i, j] and count == 3: new_cells[i, j] = True self.cells = new_cells def draw(self): self.screen.fill((255, 255, 255)) for i in range(self.cells.shape[0]): for j in range(self.cells.shape[1]): if self.cells[i, j]: pygame.draw.rect(self.screen, (0, 0, 0), (i*self.cell_size, j*self.cell_size, self.cell_size, self.cell_size)) else: pygame.draw.rect(self.screen, (255, 255, 255), (i*self.cell_size, j*self.cell_size, self.cell_size, self.cell_size)) pygame.display.flip() def run(self): clock = pygame.time.Clock() self.running = True while self.running: clock.tick(self.speed) self.handle_events() if self.running: self.update() self.draw() pygame.quit() if __name__ == '__main__': game = GameOfLife() game.run() ``` 在这个实现中,我们创建了一个名为 `GameOfLife` 的类,该类包含以下方法: - `__init__`: 用于初始化游戏界面和生命游戏的初始状态。 - `handle_events`: 用于处理用户交互,例如单击鼠标、按下空格键或重新开始游戏。 - `get_neighbors`: 用于计算指定单元格周围的细胞数量。 - `update`: 用于根据生命游戏规则更新每个单元格的状态。 - `draw`: 用于绘制矩形网格并填充每个单元格的颜色。 - `run`: 用于运行游戏循环,处理事件并更新和绘制游戏状态。 在主程序中,我们创建了一个 `GameOfLife` 实例,并运行游戏循环,直到用户退出游戏。 现在,您可以运行代码并尝试模拟生命游戏。您可以使用鼠标单击单元格来切换其状态,按下空格键来暂停或继续游戏,按下“c”键来清除所有单元格,按下“r”键来随机化单元格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值